blob: 63dbf7f42805e9cb85e0c876a4f2fc57ea26936d [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
Janis Danisevskis030ba022021-05-26 11:15:30 -070045pub(crate) mod utils;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -070046mod versioning;
Matthew Maurerd7815ca2021-05-06 21:58:45 -070047
Janis Danisevskis11bd2592022-01-04 19:59:26 -080048use crate::gc::Gc;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use crate::impl_metadata; // This is in db_utils.rs
Eric Biggersb0478cf2023-10-27 03:55:29 +000050use crate::key_parameter::{KeyParameter, KeyParameterValue, Tag};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000051use crate::ks_err;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070052use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000053use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070055 error::{Error as KsError, ErrorCode, ResponseCode},
56 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080057};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000058use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Tri Voa1634bb2022-12-01 15:54:19 -080059 HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
60 SecurityLevel::SecurityLevel,
61};
62use android_security_metrics::aidl::android::security::metrics::{
Tri Vo0346bbe2023-05-12 14:16:31 -040063 Storage::Storage as MetricsStorage, StorageStats::StorageStats,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080064};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070065use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070066 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070067};
Shaquille Johnson7f5a8152023-09-27 18:46:27 +010068use anyhow::{anyhow, Context, Result};
69use keystore2_flags;
70use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
71use utils as db_utils;
72use utils::SqlField;
Max Bires2b2e6562020-09-22 11:22:36 -070073
74use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080075use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000076use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070077#[cfg(not(test))]
78use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070079use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070080 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080081 types::FromSql,
82 types::FromSqlResult,
83 types::ToSqlOutput,
84 types::{FromSqlError, Value, ValueRef},
Andrew Walbran78abb1e2023-05-30 16:20:56 +000085 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070086};
Max Bires2b2e6562020-09-22 11:22:36 -070087
Janis Danisevskisaec14592020-11-12 09:41:49 -080088use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080089 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080090 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070091 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080093};
Max Bires2b2e6562020-09-22 11:22:36 -070094
Joel Galenson0891bc12020-07-20 10:37:03 -070095#[cfg(test)]
96use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070097
Janis Danisevskisb42fc182020-12-15 08:41:27 -080098impl_metadata!(
99 /// A set of metadata for key entries.
100 #[derive(Debug, Default, Eq, PartialEq)]
101 pub struct KeyMetaData;
102 /// A metadata entry for key entries.
103 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
104 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800105 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800106 CreationDate(DateTime) with accessor creation_date,
107 /// Expiration date for attestation keys.
108 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700109 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
110 /// provisioning
111 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
112 /// Vector representing the raw public key so results from the server can be matched
113 /// to the right entry
114 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700115 /// SEC1 public key for ECDH encryption
116 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800117 // --- ADD NEW META DATA FIELDS HERE ---
118 // For backwards compatibility add new entries only to
119 // end of this list and above this comment.
120 };
121);
122
123impl KeyMetaData {
124 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
125 let mut stmt = tx
126 .prepare(
127 "SELECT tag, data from persistent.keymetadata
128 WHERE keyentryid = ?;",
129 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000130 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800131
132 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
133
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000134 let mut rows = stmt
135 .query(params![key_id])
136 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800137 db_utils::with_rows_extract_all(&mut rows, |row| {
138 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
139 metadata.insert(
140 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700141 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800142 .context("Failed to read KeyMetaEntry.")?,
143 );
144 Ok(())
145 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000146 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800147
148 Ok(Self { data: metadata })
149 }
150
151 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
152 let mut stmt = tx
153 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000154 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800155 VALUES (?, ?, ?);",
156 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000157 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800158
159 let iter = self.data.iter();
160 for (tag, entry) in iter {
161 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000162 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800163 })?;
164 }
165 Ok(())
166 }
167}
168
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800169impl_metadata!(
170 /// A set of metadata for key blobs.
171 #[derive(Debug, Default, Eq, PartialEq)]
172 pub struct BlobMetaData;
173 /// A metadata entry for key blobs.
174 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
175 pub enum BlobMetaEntry {
176 /// If present, indicates that the blob is encrypted with another key or a key derived
177 /// from a password.
178 EncryptedBy(EncryptedBy) with accessor encrypted_by,
179 /// If the blob is password encrypted this field is set to the
180 /// salt used for the key derivation.
181 Salt(Vec<u8>) with accessor salt,
182 /// If the blob is encrypted, this field is set to the initialization vector.
183 Iv(Vec<u8>) with accessor iv,
184 /// If the blob is encrypted, this field holds the AEAD TAG.
185 AeadTag(Vec<u8>) with accessor aead_tag,
186 /// The uuid of the owning KeyMint instance.
187 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700188 /// If the key is ECDH encrypted, this is the ephemeral public key
189 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000190 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
191 /// of that key
192 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800193 // --- ADD NEW META DATA FIELDS HERE ---
194 // For backwards compatibility add new entries only to
195 // end of this list and above this comment.
196 };
197);
198
199impl BlobMetaData {
200 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
201 let mut stmt = tx
202 .prepare(
203 "SELECT tag, data from persistent.blobmetadata
204 WHERE blobentryid = ?;",
205 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000206 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800207
208 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
209
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000210 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800211 db_utils::with_rows_extract_all(&mut rows, |row| {
212 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
213 metadata.insert(
214 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700215 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800216 .context("Failed to read BlobMetaEntry.")?,
217 );
218 Ok(())
219 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000220 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221
222 Ok(Self { data: metadata })
223 }
224
225 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
226 let mut stmt = tx
227 .prepare(
228 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
229 VALUES (?, ?, ?);",
230 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000231 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800232
233 let iter = self.data.iter();
234 for (tag, entry) in iter {
235 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000236 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800237 })?;
238 }
239 Ok(())
240 }
241}
242
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800243/// Indicates the type of the keyentry.
244#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
245pub enum KeyType {
246 /// This is a client key type. These keys are created or imported through the Keystore 2.0
247 /// AIDL interface android.system.keystore2.
248 Client,
249 /// This is a super key type. These keys are created by keystore itself and used to encrypt
250 /// other key blobs to provide LSKF binding.
251 Super,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800252}
253
254impl ToSql for KeyType {
255 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
256 Ok(ToSqlOutput::Owned(Value::Integer(match self {
257 KeyType::Client => 0,
258 KeyType::Super => 1,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800259 })))
260 }
261}
262
263impl FromSql for KeyType {
264 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
265 match i64::column_result(value)? {
266 0 => Ok(KeyType::Client),
267 1 => Ok(KeyType::Super),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800268 v => Err(FromSqlError::OutOfRange(v)),
269 }
270 }
271}
272
Max Bires8e93d2b2021-01-14 13:17:59 -0800273/// Uuid representation that can be stored in the database.
274/// Right now it can only be initialized from SecurityLevel.
275/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
276#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
277pub struct Uuid([u8; 16]);
278
279impl Deref for Uuid {
280 type Target = [u8; 16];
281
282 fn deref(&self) -> &Self::Target {
283 &self.0
284 }
285}
286
287impl From<SecurityLevel> for Uuid {
288 fn from(sec_level: SecurityLevel) -> Self {
289 Self((sec_level.0 as u128).to_be_bytes())
290 }
291}
292
293impl ToSql for Uuid {
294 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
295 self.0.to_sql()
296 }
297}
298
299impl FromSql for Uuid {
300 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
301 let blob = Vec::<u8>::column_result(value)?;
302 if blob.len() != 16 {
303 return Err(FromSqlError::OutOfRange(blob.len() as i64));
304 }
305 let mut arr = [0u8; 16];
306 arr.copy_from_slice(&blob);
307 Ok(Self(arr))
308 }
309}
310
311/// Key entries that are not associated with any KeyMint instance, such as pure certificate
312/// entries are associated with this UUID.
313pub static KEYSTORE_UUID: Uuid = Uuid([
314 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
315]);
316
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800317/// Indicates how the sensitive part of this key blob is encrypted.
318#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
319pub enum EncryptedBy {
320 /// The keyblob is encrypted by a user password.
321 /// In the database this variant is represented as NULL.
322 Password,
323 /// The keyblob is encrypted by another key with wrapped key id.
324 /// In the database this variant is represented as non NULL value
325 /// that is convertible to i64, typically NUMERIC.
326 KeyId(i64),
327}
328
329impl ToSql for EncryptedBy {
330 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
331 match self {
332 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
333 Self::KeyId(id) => id.to_sql(),
334 }
335 }
336}
337
338impl FromSql for EncryptedBy {
339 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
340 match value {
341 ValueRef::Null => Ok(Self::Password),
342 _ => Ok(Self::KeyId(i64::column_result(value)?)),
343 }
344 }
345}
346
347/// A database representation of wall clock time. DateTime stores unix epoch time as
348/// i64 in milliseconds.
349#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
350pub struct DateTime(i64);
351
352/// Error type returned when creating DateTime or converting it from and to
353/// SystemTime.
354#[derive(thiserror::Error, Debug)]
355pub enum DateTimeError {
356 /// This is returned when SystemTime and Duration computations fail.
357 #[error(transparent)]
358 SystemTimeError(#[from] SystemTimeError),
359
360 /// This is returned when type conversions fail.
361 #[error(transparent)]
362 TypeConversion(#[from] std::num::TryFromIntError),
363
364 /// This is returned when checked time arithmetic failed.
365 #[error("Time arithmetic failed.")]
366 TimeArithmetic,
367}
368
369impl DateTime {
370 /// Constructs a new DateTime object denoting the current time. This may fail during
371 /// conversion to unix epoch time and during conversion to the internal i64 representation.
372 pub fn now() -> Result<Self, DateTimeError> {
373 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
374 }
375
376 /// Constructs a new DateTime object from milliseconds.
377 pub fn from_millis_epoch(millis: i64) -> Self {
378 Self(millis)
379 }
380
381 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700382 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800383 self.0
384 }
385
386 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700387 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800388 self.0 / 1000
389 }
390}
391
392impl ToSql for DateTime {
393 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
394 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
395 }
396}
397
398impl FromSql for DateTime {
399 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
400 Ok(Self(i64::column_result(value)?))
401 }
402}
403
404impl TryInto<SystemTime> for DateTime {
405 type Error = DateTimeError;
406
407 fn try_into(self) -> Result<SystemTime, Self::Error> {
408 // We want to construct a SystemTime representation equivalent to self, denoting
409 // a point in time THEN, but we cannot set the time directly. We can only construct
410 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
411 // and between EPOCH and THEN. With this common reference we can construct the
412 // duration between NOW and THEN which we can add to our SystemTime representation
413 // of NOW to get a SystemTime representation of THEN.
414 // Durations can only be positive, thus the if statement below.
415 let now = SystemTime::now();
416 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
417 let then_epoch = Duration::from_millis(self.0.try_into()?);
418 Ok(if now_epoch > then_epoch {
419 // then = now - (now_epoch - then_epoch)
420 now_epoch
421 .checked_sub(then_epoch)
422 .and_then(|d| now.checked_sub(d))
423 .ok_or(DateTimeError::TimeArithmetic)?
424 } else {
425 // then = now + (then_epoch - now_epoch)
426 then_epoch
427 .checked_sub(now_epoch)
428 .and_then(|d| now.checked_add(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 })
431 }
432}
433
434impl TryFrom<SystemTime> for DateTime {
435 type Error = DateTimeError;
436
437 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
438 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
439 }
440}
441
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800442#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
443enum KeyLifeCycle {
444 /// Existing keys have a key ID but are not fully populated yet.
445 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
446 /// them to Unreferenced for garbage collection.
447 Existing,
448 /// A live key is fully populated and usable by clients.
449 Live,
450 /// An unreferenced key is scheduled for garbage collection.
451 Unreferenced,
452}
453
454impl ToSql for KeyLifeCycle {
455 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
456 match self {
457 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
458 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
459 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
460 }
461 }
462}
463
464impl FromSql for KeyLifeCycle {
465 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
466 match i64::column_result(value)? {
467 0 => Ok(KeyLifeCycle::Existing),
468 1 => Ok(KeyLifeCycle::Live),
469 2 => Ok(KeyLifeCycle::Unreferenced),
470 v => Err(FromSqlError::OutOfRange(v)),
471 }
472 }
473}
474
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700475/// Keys have a KeyMint blob component and optional public certificate and
476/// certificate chain components.
477/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
478/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800479#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700480pub struct KeyEntryLoadBits(u32);
481
482impl KeyEntryLoadBits {
483 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
484 pub const NONE: KeyEntryLoadBits = Self(0);
485 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
486 pub const KM: KeyEntryLoadBits = Self(1);
487 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
488 pub const PUBLIC: KeyEntryLoadBits = Self(2);
489 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
490 pub const BOTH: KeyEntryLoadBits = Self(3);
491
492 /// Returns true if this object indicates that the public components shall be loaded.
493 pub const fn load_public(&self) -> bool {
494 self.0 & Self::PUBLIC.0 != 0
495 }
496
497 /// Returns true if the object indicates that the KeyMint component shall be loaded.
498 pub const fn load_km(&self) -> bool {
499 self.0 & Self::KM.0 != 0
500 }
501}
502
Janis Danisevskisaec14592020-11-12 09:41:49 -0800503lazy_static! {
504 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
505}
506
507struct KeyIdLockDb {
508 locked_keys: Mutex<HashSet<i64>>,
509 cond_var: Condvar,
510}
511
512/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
513/// from the database a second time. Most functions manipulating the key blob database
514/// require a KeyIdGuard.
515#[derive(Debug)]
516pub struct KeyIdGuard(i64);
517
518impl KeyIdLockDb {
519 fn new() -> Self {
520 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
521 }
522
523 /// This function blocks until an exclusive lock for the given key entry id can
524 /// be acquired. It returns a guard object, that represents the lifecycle of the
525 /// acquired lock.
526 pub fn get(&self, key_id: i64) -> KeyIdGuard {
527 let mut locked_keys = self.locked_keys.lock().unwrap();
528 while locked_keys.contains(&key_id) {
529 locked_keys = self.cond_var.wait(locked_keys).unwrap();
530 }
531 locked_keys.insert(key_id);
532 KeyIdGuard(key_id)
533 }
534
535 /// This function attempts to acquire an exclusive lock on a given key id. If the
536 /// given key id is already taken the function returns None immediately. If a lock
537 /// can be acquired this function returns a guard object, that represents the
538 /// lifecycle of the acquired lock.
539 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
540 let mut locked_keys = self.locked_keys.lock().unwrap();
541 if locked_keys.insert(key_id) {
542 Some(KeyIdGuard(key_id))
543 } else {
544 None
545 }
546 }
547}
548
549impl KeyIdGuard {
550 /// Get the numeric key id of the locked key.
551 pub fn id(&self) -> i64 {
552 self.0
553 }
554}
555
556impl Drop for KeyIdGuard {
557 fn drop(&mut self) {
558 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
559 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800560 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800561 KEY_ID_LOCK.cond_var.notify_all();
562 }
563}
564
Max Bires8e93d2b2021-01-14 13:17:59 -0800565/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700566#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800567pub struct CertificateInfo {
568 cert: Option<Vec<u8>>,
569 cert_chain: Option<Vec<u8>>,
570}
571
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800572/// This type represents a Blob with its metadata and an optional superseded blob.
573#[derive(Debug)]
574pub struct BlobInfo<'a> {
575 blob: &'a [u8],
576 metadata: &'a BlobMetaData,
577 /// Superseded blobs are an artifact of legacy import. In some rare occasions
578 /// the key blob needs to be upgraded during import. In that case two
579 /// blob are imported, the superseded one will have to be imported first,
580 /// so that the garbage collector can reap it.
581 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
582}
583
584impl<'a> BlobInfo<'a> {
585 /// Create a new instance of blob info with blob and corresponding metadata
586 /// and no superseded blob info.
587 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
588 Self { blob, metadata, superseded_blob: None }
589 }
590
591 /// Create a new instance of blob info with blob and corresponding metadata
592 /// as well as superseded blob info.
593 pub fn new_with_superseded(
594 blob: &'a [u8],
595 metadata: &'a BlobMetaData,
596 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
597 ) -> Self {
598 Self { blob, metadata, superseded_blob }
599 }
600}
601
Max Bires8e93d2b2021-01-14 13:17:59 -0800602impl CertificateInfo {
603 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
604 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
605 Self { cert, cert_chain }
606 }
607
608 /// Take the cert
609 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
610 self.cert.take()
611 }
612
613 /// Take the cert chain
614 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
615 self.cert_chain.take()
616 }
617}
618
Max Bires2b2e6562020-09-22 11:22:36 -0700619/// This type represents a certificate chain with a private key corresponding to the leaf
620/// 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 -0700621pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800622 /// A KM key blob
623 pub private_key: ZVec,
624 /// A batch cert for private_key
625 pub batch_cert: Vec<u8>,
626 /// A full certificate chain from root signing authority to private_key, including batch_cert
627 /// for convenience.
628 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700629}
630
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631/// This type represents a Keystore 2.0 key entry.
632/// An entry has a unique `id` by which it can be found in the database.
633/// It has a security level field, key parameters, and three optional fields
634/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800635#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700636pub struct KeyEntry {
637 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800638 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700639 cert: Option<Vec<u8>>,
640 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800641 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700642 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800643 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800644 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700645}
646
647impl KeyEntry {
648 /// Returns the unique id of the Key entry.
649 pub fn id(&self) -> i64 {
650 self.id
651 }
652 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800653 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
654 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800656 /// Extracts the Optional KeyMint blob including its metadata.
657 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
658 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700659 }
660 /// Exposes the optional public certificate.
661 pub fn cert(&self) -> &Option<Vec<u8>> {
662 &self.cert
663 }
664 /// Extracts the optional public certificate.
665 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
666 self.cert.take()
667 }
668 /// Exposes the optional public certificate chain.
669 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
670 &self.cert_chain
671 }
672 /// Extracts the optional public certificate_chain.
673 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
674 self.cert_chain.take()
675 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800676 /// Returns the uuid of the owning KeyMint instance.
677 pub fn km_uuid(&self) -> &Uuid {
678 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700679 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700680 /// Exposes the key parameters of this key entry.
681 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
682 &self.parameters
683 }
684 /// Consumes this key entry and extracts the keyparameters from it.
685 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
686 self.parameters
687 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800688 /// Exposes the key metadata of this key entry.
689 pub fn metadata(&self) -> &KeyMetaData {
690 &self.metadata
691 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800692 /// This returns true if the entry is a pure certificate entry with no
693 /// private key component.
694 pub fn pure_cert(&self) -> bool {
695 self.pure_cert
696 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000697 /// Consumes this key entry and extracts the keyparameters and metadata from it.
698 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
699 (self.parameters, self.metadata)
700 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700701}
702
703/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800704#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700705pub struct SubComponentType(u32);
706impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800707 /// Persistent identifier for a key blob.
708 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700709 /// Persistent identifier for a certificate blob.
710 pub const CERT: SubComponentType = Self(1);
711 /// Persistent identifier for a certificate chain blob.
712 pub const CERT_CHAIN: SubComponentType = Self(2);
713}
714
715impl ToSql for SubComponentType {
716 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
717 self.0.to_sql()
718 }
719}
720
721impl FromSql for SubComponentType {
722 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
723 Ok(Self(u32::column_result(value)?))
724 }
725}
726
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800727/// This trait is private to the database module. It is used to convey whether or not the garbage
728/// collector shall be invoked after a database access. All closures passed to
729/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
730/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
731/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
732/// `.need_gc()`.
733trait DoGc<T> {
734 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
735
736 fn no_gc(self) -> Result<(bool, T)>;
737
738 fn need_gc(self) -> Result<(bool, T)>;
739}
740
741impl<T> DoGc<T> for Result<T> {
742 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
743 self.map(|r| (need_gc, r))
744 }
745
746 fn no_gc(self) -> Result<(bool, T)> {
747 self.do_gc(false)
748 }
749
750 fn need_gc(self) -> Result<(bool, T)> {
751 self.do_gc(true)
752 }
753}
754
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700755/// KeystoreDB wraps a connection to an SQLite database and tracks its
756/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700757pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700758 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700759 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700760 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700761}
762
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000763/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000764/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000765#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
766pub struct MonotonicRawTime(i64);
767
768impl MonotonicRawTime {
769 /// Constructs a new MonotonicRawTime
770 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000771 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000772 }
773
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000774 /// Returns the value of MonotonicRawTime in milliseconds as i64
775 pub fn milliseconds(&self) -> i64 {
776 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000777 }
778
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000779 /// Returns the integer value of MonotonicRawTime as i64
780 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000781 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000782 }
783
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800784 /// Like i64::checked_sub.
785 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
786 self.0.checked_sub(other.0).map(Self)
787 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788}
789
790impl ToSql for MonotonicRawTime {
791 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
792 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
793 }
794}
795
796impl FromSql for MonotonicRawTime {
797 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
798 Ok(Self(i64::column_result(value)?))
799 }
800}
801
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000802/// This struct encapsulates the information to be stored in the database about the auth tokens
803/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700804#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000805pub struct AuthTokenEntry {
806 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000807 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000808 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000809}
810
811impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000812 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000813 AuthTokenEntry { auth_token, time_received }
814 }
815
816 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800817 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800819 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000820 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000821 })
822 }
823
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000824 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800825 pub fn auth_token(&self) -> &HardwareAuthToken {
826 &self.auth_token
827 }
828
829 /// Returns the auth token wrapped by the AuthTokenEntry
830 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000831 self.auth_token
832 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800833
834 /// Returns the time that this auth token was received.
835 pub fn time_received(&self) -> MonotonicRawTime {
836 self.time_received
837 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000838
839 /// Returns the challenge value of the auth token.
840 pub fn challenge(&self) -> i64 {
841 self.auth_token.challenge
842 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000843}
844
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800845/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
846/// This object does not allow access to the database connection. But it keeps a database
847/// connection alive in order to keep the in memory per boot database alive.
848pub struct PerBootDbKeepAlive(Connection);
849
Joel Galenson26f4d012020-07-17 14:57:21 -0700850impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800851 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700852 const CURRENT_DB_VERSION: u32 = 1;
853 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854
Seth Moore78c091f2021-04-09 21:38:30 +0000855 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700856 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000857
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700858 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800859 /// files persistent.sqlite and perboot.sqlite in the given directory.
860 /// It also attempts to initialize all of the tables.
861 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700862 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700863 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700864 let _wp = wd::watch_millis("KeystoreDB::new", 500);
865
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700866 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700867 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800868
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700869 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700871 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000872 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800873 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800874 })?;
875 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700876 }
877
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700878 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
879 // cryptographic binding to the boot level keys was implemented.
880 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
881 tx.execute(
882 "UPDATE persistent.keyentry SET state = ?
883 WHERE
884 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
885 AND
886 id NOT IN (
887 SELECT keyentryid FROM persistent.blobentry
888 WHERE id IN (
889 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
890 )
891 );",
892 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
893 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000894 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700895 Ok(1)
896 }
897
Janis Danisevskis66784c42021-01-27 08:40:25 -0800898 fn init_tables(tx: &Transaction) -> Result<()> {
899 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700900 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700901 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800902 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700903 domain INTEGER,
904 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800905 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800906 state INTEGER,
907 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000908 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 )
910 .context("Failed to initialize \"keyentry\" table.")?;
911
Janis Danisevskis66784c42021-01-27 08:40:25 -0800912 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800913 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
914 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000915 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800916 )
917 .context("Failed to create index keyentry_id_index.")?;
918
919 tx.execute(
920 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
921 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000922 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800923 )
924 .context("Failed to create index keyentry_domain_namespace_index.")?;
925
926 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700927 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
928 id INTEGER PRIMARY KEY,
929 subcomponent_type INTEGER,
930 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800931 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000932 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700933 )
934 .context("Failed to initialize \"blobentry\" table.")?;
935
Janis Danisevskis66784c42021-01-27 08:40:25 -0800936 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800937 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
938 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000939 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800940 )
941 .context("Failed to create index blobentry_keyentryid_index.")?;
942
943 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800944 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
945 id INTEGER PRIMARY KEY,
946 blobentryid INTEGER,
947 tag INTEGER,
948 data ANY,
949 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000950 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800951 )
952 .context("Failed to initialize \"blobmetadata\" table.")?;
953
954 tx.execute(
955 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
956 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000957 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800958 )
959 .context("Failed to create index blobmetadata_blobentryid_index.")?;
960
961 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700962 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000963 keyentryid INTEGER,
964 tag INTEGER,
965 data ANY,
966 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000967 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700968 )
969 .context("Failed to initialize \"keyparameter\" table.")?;
970
Janis Danisevskis66784c42021-01-27 08:40:25 -0800971 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800972 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
973 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000974 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800975 )
976 .context("Failed to create index keyparameter_keyentryid_index.")?;
977
978 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800979 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
980 keyentryid INTEGER,
981 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000982 data ANY,
983 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000984 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800985 )
986 .context("Failed to initialize \"keymetadata\" table.")?;
987
Janis Danisevskis66784c42021-01-27 08:40:25 -0800988 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800989 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
990 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000991 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800992 )
993 .context("Failed to create index keymetadata_keyentryid_index.")?;
994
995 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800996 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700997 id INTEGER UNIQUE,
998 grantee INTEGER,
999 keyentryid INTEGER,
1000 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001001 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001002 )
1003 .context("Failed to initialize \"grant\" table.")?;
1004
Joel Galenson0891bc12020-07-20 10:37:03 -07001005 Ok(())
1006 }
1007
Seth Moore472fcbb2021-05-12 10:07:51 -07001008 fn make_persistent_path(db_root: &Path) -> Result<String> {
1009 // Build the path to the sqlite file.
1010 let mut persistent_path = db_root.to_path_buf();
1011 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1012
1013 // Now convert them to strings prefixed with "file:"
1014 let mut persistent_path_str = "file:".to_owned();
1015 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1016
1017 Ok(persistent_path_str)
1018 }
1019
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001020 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001021 let conn =
1022 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1023
Janis Danisevskis66784c42021-01-27 08:40:25 -08001024 loop {
1025 if let Err(e) = conn
1026 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1027 .context("Failed to attach database persistent.")
1028 {
1029 if Self::is_locked_error(&e) {
1030 std::thread::sleep(std::time::Duration::from_micros(500));
1031 continue;
1032 } else {
1033 return Err(e);
1034 }
1035 }
1036 break;
1037 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001038
Shaquille Johnson7f5a8152023-09-27 18:46:27 +01001039 if keystore2_flags::wal_db_journalmode() {
1040 // Update journal mode to WAL
1041 conn.pragma_update(None, "journal_mode", "WAL")
1042 .context("Failed to connect in WAL mode for persistent db")?;
1043 }
Matthew Maurer4fb19112021-05-06 15:40:44 -07001044 // Drop the cache size from default (2M) to 0.5M
1045 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1046 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001047
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001048 Ok(conn)
1049 }
1050
Seth Moore78c091f2021-04-09 21:38:30 +00001051 fn do_table_size_query(
1052 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001053 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001054 query: &str,
1055 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001056 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001057 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001058 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001059 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001060 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001061 })
1062 .no_gc()
1063 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001064 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001065 }
1066
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001067 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001068 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001069 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001070 "SELECT page_count * page_size, freelist_count * page_size
1071 FROM pragma_page_count('persistent'),
1072 pragma_page_size('persistent'),
1073 persistent.pragma_freelist_count();",
1074 &[],
1075 )
1076 }
1077
1078 fn get_table_size(
1079 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001080 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001081 schema: &str,
1082 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001083 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001084 self.do_table_size_query(
1085 storage_type,
1086 "SELECT pgsize,unused FROM dbstat(?1)
1087 WHERE name=?2 AND aggregate=TRUE;",
1088 &[schema, table],
1089 )
1090 }
1091
1092 /// Fetches a storage statisitics atom for a given storage type. For storage
1093 /// types that map to a table, information about the table's storage is
1094 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001095 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001096 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1097
Seth Moore78c091f2021-04-09 21:38:30 +00001098 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001099 MetricsStorage::DATABASE => self.get_total_size(),
1100 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001101 self.get_table_size(storage_type, "persistent", "keyentry")
1102 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001103 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001104 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1105 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001106 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001107 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1108 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001109 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001110 self.get_table_size(storage_type, "persistent", "blobentry")
1111 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001112 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001113 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1114 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001115 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001116 self.get_table_size(storage_type, "persistent", "keyparameter")
1117 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001118 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001119 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1120 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001121 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001122 self.get_table_size(storage_type, "persistent", "keymetadata")
1123 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001124 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001125 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1126 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001127 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1128 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001129 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1130 // reportable
1131 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001132 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001133 storage_type,
1134 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001135 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001136 unused_size: 0,
1137 })
Seth Moore78c091f2021-04-09 21:38:30 +00001138 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001140 self.get_table_size(storage_type, "persistent", "blobmetadata")
1141 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001142 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001143 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1144 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001145 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001146 }
1147 }
1148
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001149 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001150 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1151 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001152 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1153 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001155 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001156 blob_ids_to_delete: &[i64],
1157 max_blobs: usize,
1158 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001159 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001160 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001161 // Delete the given blobs.
1162 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001163 tx.execute(
1164 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001166 )
1167 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001168 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1169 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001170 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001171
1172 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1173
Janis Danisevskis3395f862021-05-06 10:54:17 -07001174 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1175 let result: Vec<(i64, Vec<u8>)> = {
1176 let mut stmt = tx
1177 .prepare(
1178 "SELECT id, blob FROM persistent.blobentry
1179 WHERE subcomponent_type = ?
1180 AND (
1181 id NOT IN (
1182 SELECT MAX(id) FROM persistent.blobentry
1183 WHERE subcomponent_type = ?
1184 GROUP BY keyentryid, subcomponent_type
1185 )
1186 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1187 ) LIMIT ?;",
1188 )
1189 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001190
Janis Danisevskis3395f862021-05-06 10:54:17 -07001191 let rows = stmt
1192 .query_map(
1193 params![
1194 SubComponentType::KEY_BLOB,
1195 SubComponentType::KEY_BLOB,
1196 max_blobs as i64,
1197 ],
1198 |row| Ok((row.get(0)?, row.get(1)?)),
1199 )
1200 .context("Trying to query superseded blob.")?;
1201
1202 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1203 .context("Trying to extract superseded blobs.")?
1204 };
1205
1206 let result = result
1207 .into_iter()
1208 .map(|(blob_id, blob)| {
1209 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1210 })
1211 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1212 .context("Trying to load blob metadata.")?;
1213 if !result.is_empty() {
1214 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001215 }
1216
1217 // We did not find any superseded key blob, so let's remove other superseded blob in
1218 // one transaction.
1219 tx.execute(
1220 "DELETE FROM persistent.blobentry
1221 WHERE NOT subcomponent_type = ?
1222 AND (
1223 id NOT IN (
1224 SELECT MAX(id) FROM persistent.blobentry
1225 WHERE NOT subcomponent_type = ?
1226 GROUP BY keyentryid, subcomponent_type
1227 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1228 );",
1229 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1230 )
1231 .context("Trying to purge superseded blobs.")?;
1232
Janis Danisevskis3395f862021-05-06 10:54:17 -07001233 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001234 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001235 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001236 }
1237
1238 /// This maintenance function should be called only once before the database is used for the
1239 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1240 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1241 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1242 /// Keystore crashed at some point during key generation. Callers may want to log such
1243 /// occurrences.
1244 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1245 /// it to `KeyLifeCycle::Live` may have grants.
1246 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001247 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1248
Janis Danisevskis66784c42021-01-27 08:40:25 -08001249 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1250 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001251 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1252 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1253 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001254 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001255 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001256 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001257 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001258 }
1259
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001260 /// Checks if a key exists with given key type and key descriptor properties.
1261 pub fn key_exists(
1262 &mut self,
1263 domain: Domain,
1264 nspace: i64,
1265 alias: &str,
1266 key_type: KeyType,
1267 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001268 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1269
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001270 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1271 let key_descriptor =
1272 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001273 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001274 match result {
1275 Ok(_) => Ok(true),
1276 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1277 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001278 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001279 },
1280 }
1281 .no_gc()
1282 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001283 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001284 }
1285
Hasini Gunasingheda895552021-01-27 19:34:37 +00001286 /// Stores a super key in the database.
1287 pub fn store_super_key(
1288 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001289 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001290 key_type: &SuperKeyType,
1291 blob: &[u8],
1292 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001293 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001294 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001295 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1296
Hasini Gunasingheda895552021-01-27 19:34:37 +00001297 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1298 let key_id = Self::insert_with_retry(|id| {
1299 tx.execute(
1300 "INSERT into persistent.keyentry
1301 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001302 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001303 params![
1304 id,
1305 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001306 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001307 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001308 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001309 KeyLifeCycle::Live,
1310 &KEYSTORE_UUID,
1311 ],
1312 )
1313 })
1314 .context("Failed to insert into keyentry table.")?;
1315
Paul Crowley8d5b2532021-03-19 10:53:07 -07001316 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1317
Hasini Gunasingheda895552021-01-27 19:34:37 +00001318 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001319 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001320 key_id,
1321 SubComponentType::KEY_BLOB,
1322 Some(blob),
1323 Some(blob_metadata),
1324 )
1325 .context("Failed to store key blob.")?;
1326
1327 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1328 .context("Trying to load key components.")
1329 .no_gc()
1330 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001331 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001332 }
1333
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001334 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001335 pub fn load_super_key(
1336 &mut self,
1337 key_type: &SuperKeyType,
1338 user_id: u32,
1339 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001340 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1341
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001342 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1343 let key_descriptor = KeyDescriptor {
1344 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001345 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001346 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001347 blob: None,
1348 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001349 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001350 match id {
1351 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001352 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001353 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001354 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1355 }
1356 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1357 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001358 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001359 },
1360 }
1361 .no_gc()
1362 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001363 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001364 }
1365
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001366 /// Atomically loads a key entry and associated metadata or creates it using the
1367 /// callback create_new_key callback. The callback is called during a database
1368 /// transaction. This means that implementers should be mindful about using
1369 /// blocking operations such as IPC or grabbing mutexes.
1370 pub fn get_or_create_key_with<F>(
1371 &mut self,
1372 domain: Domain,
1373 namespace: i64,
1374 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001375 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001376 create_new_key: F,
1377 ) -> Result<(KeyIdGuard, KeyEntry)>
1378 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001379 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001380 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001381 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1382
Janis Danisevskis66784c42021-01-27 08:40:25 -08001383 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1384 let id = {
1385 let mut stmt = tx
1386 .prepare(
1387 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001388 WHERE
1389 key_type = ?
1390 AND domain = ?
1391 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001392 AND alias = ?
1393 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001394 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001395 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001396 let mut rows = stmt
1397 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001398 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001399
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 db_utils::with_rows_extract_one(&mut rows, |row| {
1401 Ok(match row {
1402 Some(r) => r.get(0).context("Failed to unpack id.")?,
1403 None => None,
1404 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001405 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001406 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001408
Janis Danisevskis66784c42021-01-27 08:40:25 -08001409 let (id, entry) = match id {
1410 Some(id) => (
1411 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001412 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001414
Janis Danisevskis66784c42021-01-27 08:40:25 -08001415 None => {
1416 let id = Self::insert_with_retry(|id| {
1417 tx.execute(
1418 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001419 (id, key_type, domain, namespace, alias, state, km_uuid)
1420 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001421 params![
1422 id,
1423 KeyType::Super,
1424 domain.0,
1425 namespace,
1426 alias,
1427 KeyLifeCycle::Live,
1428 km_uuid,
1429 ],
1430 )
1431 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001432 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001433
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001434 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001435 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001436 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001437 id,
1438 SubComponentType::KEY_BLOB,
1439 Some(&blob),
1440 Some(&metadata),
1441 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001442 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001443 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001444 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001445 KeyEntry {
1446 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001447 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001448 pure_cert: false,
1449 ..Default::default()
1450 },
1451 )
1452 }
1453 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001454 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001455 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001456 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001457 }
1458
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001459 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001460 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1461 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001462 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1463 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001464 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001465 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001466 loop {
1467 match self
1468 .conn
1469 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001470 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001471 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1472 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001473 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001474 Ok(result)
1475 }) {
1476 Ok(result) => break Ok(result),
1477 Err(e) => {
1478 if Self::is_locked_error(&e) {
1479 std::thread::sleep(std::time::Duration::from_micros(500));
1480 continue;
1481 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001482 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001483 }
1484 }
1485 }
1486 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001487 .map(|(need_gc, result)| {
1488 if need_gc {
1489 if let Some(ref gc) = self.gc {
1490 gc.notify_gc();
1491 }
1492 }
1493 result
1494 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001495 }
1496
1497 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001498 matches!(
1499 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1500 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1501 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1502 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001503 }
1504
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001505 /// Creates a new key entry and allocates a new randomized id for the new key.
1506 /// The key id gets associated with a domain and namespace but not with an alias.
1507 /// To complete key generation `rebind_alias` should be called after all of the
1508 /// key artifacts, i.e., blobs and parameters have been associated with the new
1509 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1510 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001511 pub fn create_key_entry(
1512 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001513 domain: &Domain,
1514 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001515 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001516 km_uuid: &Uuid,
1517 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001518 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1519
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001520 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001521 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001522 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001523 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001524 }
1525
1526 fn create_key_entry_internal(
1527 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001528 domain: &Domain,
1529 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001530 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001531 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001532 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001533 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001534 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001535 _ => {
1536 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001537 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001538 }
1539 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001540 Ok(KEY_ID_LOCK.get(
1541 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001542 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001543 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001544 (id, key_type, domain, namespace, alias, state, km_uuid)
1545 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001546 params![
1547 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001548 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001549 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001550 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001551 KeyLifeCycle::Existing,
1552 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001553 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001554 )
1555 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001556 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001557 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001558 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001559
Janis Danisevskis377d1002021-01-27 19:07:48 -08001560 /// Set a new blob and associates it with the given key id. Each blob
1561 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001562 /// Each key can have one of each sub component type associated. If more
1563 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001564 /// will get garbage collected.
1565 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1566 /// removed by setting blob to None.
1567 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001568 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001569 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001570 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001571 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001572 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001573 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001574 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1575
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001576 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001577 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001578 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001579 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001580 }
1581
Janis Danisevskiseed69842021-02-18 20:04:10 -08001582 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1583 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1584 /// We use this to insert key blobs into the database which can then be garbage collected
1585 /// lazily by the key garbage collector.
1586 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001587 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1588
Janis Danisevskiseed69842021-02-18 20:04:10 -08001589 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1590 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001591 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001592 Self::UNASSIGNED_KEY_ID,
1593 SubComponentType::KEY_BLOB,
1594 Some(blob),
1595 Some(blob_metadata),
1596 )
1597 .need_gc()
1598 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001599 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001600 }
1601
Janis Danisevskis377d1002021-01-27 19:07:48 -08001602 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001603 tx: &Transaction,
1604 key_id: i64,
1605 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001606 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001607 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001608 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001609 match (blob, sc_type) {
1610 (Some(blob), _) => {
1611 tx.execute(
1612 "INSERT INTO persistent.blobentry
1613 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1614 params![sc_type, key_id, blob],
1615 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001616 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001617 if let Some(blob_metadata) = blob_metadata {
1618 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001619 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001620 row.get(0)
1621 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001622 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001623 blob_metadata
1624 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001625 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001626 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001627 }
1628 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1629 tx.execute(
1630 "DELETE FROM persistent.blobentry
1631 WHERE subcomponent_type = ? AND keyentryid = ?;",
1632 params![sc_type, key_id],
1633 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001634 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001635 }
1636 (None, _) => {
1637 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001638 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001639 }
1640 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001641 Ok(())
1642 }
1643
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001644 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1645 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001646 #[cfg(test)]
1647 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001648 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001649 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001650 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001651 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001652 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001653
Janis Danisevskis66784c42021-01-27 08:40:25 -08001654 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001655 tx: &Transaction,
1656 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001657 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001658 ) -> Result<()> {
1659 let mut stmt = tx
1660 .prepare(
1661 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1662 VALUES (?, ?, ?, ?);",
1663 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001664 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001665
Janis Danisevskis66784c42021-01-27 08:40:25 -08001666 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001667 stmt.insert(params![
1668 key_id.0,
1669 p.get_tag().0,
1670 p.key_parameter_value(),
1671 p.security_level().0
1672 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001673 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001674 }
1675 Ok(())
1676 }
1677
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001678 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001679 #[cfg(test)]
1680 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001681 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001682 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001683 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001684 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001685 }
1686
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001687 /// Updates the alias column of the given key id `newid` with the given alias,
1688 /// and atomically, removes the alias, domain, and namespace from another row
1689 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001690 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1691 /// collector.
1692 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001693 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001694 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001695 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001696 domain: &Domain,
1697 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001698 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001699 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001700 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001701 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001702 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001703 return Err(KsError::sys())
1704 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001705 }
1706 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001707 let updated = tx
1708 .execute(
1709 "UPDATE persistent.keyentry
1710 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001711 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1712 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001713 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001714 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001715 let result = tx
1716 .execute(
1717 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001718 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001719 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001720 params![
1721 alias,
1722 KeyLifeCycle::Live,
1723 newid.0,
1724 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001725 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001726 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001727 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001728 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001729 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001730 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001731 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001732 return Err(KsError::sys()).context(ks_err!(
1733 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001734 result
1735 ));
1736 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001737 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001738 }
1739
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001740 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1741 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1742 pub fn migrate_key_namespace(
1743 &mut self,
1744 key_id_guard: KeyIdGuard,
1745 destination: &KeyDescriptor,
1746 caller_uid: u32,
1747 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1748 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001749 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1750
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001751 let destination = match destination.domain {
1752 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1753 Domain::SELINUX => (*destination).clone(),
1754 domain => {
1755 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1756 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1757 }
1758 };
1759
1760 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001761 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001762
1763 let alias = destination
1764 .alias
1765 .as_ref()
1766 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001767 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001768
1769 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1770 // Query the destination location. If there is a key, the migration request fails.
1771 if tx
1772 .query_row(
1773 "SELECT id FROM persistent.keyentry
1774 WHERE alias = ? AND domain = ? AND namespace = ?;",
1775 params![alias, destination.domain.0, destination.nspace],
1776 |_| Ok(()),
1777 )
1778 .optional()
1779 .context("Failed to query destination.")?
1780 .is_some()
1781 {
1782 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1783 .context("Target already exists.");
1784 }
1785
1786 let updated = tx
1787 .execute(
1788 "UPDATE persistent.keyentry
1789 SET alias = ?, domain = ?, namespace = ?
1790 WHERE id = ?;",
1791 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1792 )
1793 .context("Failed to update key entry.")?;
1794
1795 if updated != 1 {
1796 return Err(KsError::sys())
1797 .context(format!("Update succeeded, but {} rows were updated.", updated));
1798 }
1799 Ok(()).no_gc()
1800 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001801 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001802 }
1803
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001804 /// Store a new key in a single transaction.
1805 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1806 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001807 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1808 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001809 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001810 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001811 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001812 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001813 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001814 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001815 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001816 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001817 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001818 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001819 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001820 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1821
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001822 let (alias, domain, namespace) = match key {
1823 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1824 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1825 (alias, key.domain, nspace)
1826 }
1827 _ => {
1828 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001829 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001830 }
1831 };
1832 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001833 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001834 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001835 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1836
1837 // In some occasions the key blob is already upgraded during the import.
1838 // In order to make sure it gets properly deleted it is inserted into the
1839 // database here and then immediately replaced by the superseding blob.
1840 // The garbage collector will then subject the blob to deleteKey of the
1841 // KM back end to permanently invalidate the key.
1842 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1843 Self::set_blob_internal(
1844 tx,
1845 key_id.id(),
1846 SubComponentType::KEY_BLOB,
1847 Some(blob),
1848 Some(blob_metadata),
1849 )
1850 .context("Trying to insert superseded key blob.")?;
1851 true
1852 } else {
1853 false
1854 };
1855
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001856 Self::set_blob_internal(
1857 tx,
1858 key_id.id(),
1859 SubComponentType::KEY_BLOB,
1860 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001861 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001862 )
1863 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001864 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001865 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001866 .context("Trying to insert the certificate.")?;
1867 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001868 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001869 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001870 tx,
1871 key_id.id(),
1872 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001873 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001874 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001875 )
1876 .context("Trying to insert the certificate chain.")?;
1877 }
1878 Self::insert_keyparameter_internal(tx, &key_id, params)
1879 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001880 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001881 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001882 .context("Trying to rebind alias.")?
1883 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001884 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001885 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001886 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001887 }
1888
Janis Danisevskis377d1002021-01-27 19:07:48 -08001889 /// Store a new certificate
1890 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1891 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001892 pub fn store_new_certificate(
1893 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001894 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001895 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001896 cert: &[u8],
1897 km_uuid: &Uuid,
1898 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001899 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1900
Janis Danisevskis377d1002021-01-27 19:07:48 -08001901 let (alias, domain, namespace) = match key {
1902 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1903 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1904 (alias, key.domain, nspace)
1905 }
1906 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001907 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1908 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001909 }
1910 };
1911 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001912 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001913 .context("Trying to create new key entry.")?;
1914
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001915 Self::set_blob_internal(
1916 tx,
1917 key_id.id(),
1918 SubComponentType::CERT_CHAIN,
1919 Some(cert),
1920 None,
1921 )
1922 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001923
1924 let mut metadata = KeyMetaData::new();
1925 metadata.add(KeyMetaEntry::CreationDate(
1926 DateTime::now().context("Trying to make creation time.")?,
1927 ));
1928
1929 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1930
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001931 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001932 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001933 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001934 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001935 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001936 }
1937
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001938 // Helper function loading the key_id given the key descriptor
1939 // tuple comprising domain, namespace, and alias.
1940 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001941 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001942 let alias = key
1943 .alias
1944 .as_ref()
1945 .map_or_else(|| Err(KsError::sys()), Ok)
1946 .context("In load_key_entry_id: Alias must be specified.")?;
1947 let mut stmt = tx
1948 .prepare(
1949 "SELECT id FROM persistent.keyentry
1950 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001951 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001952 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001953 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001954 AND alias = ?
1955 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001956 )
1957 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1958 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001959 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001960 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001961 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001962 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001963 .get(0)
1964 .context("Failed to unpack id.")
1965 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001966 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001967 }
1968
1969 /// This helper function completes the access tuple of a key, which is required
1970 /// to perform access control. The strategy depends on the `domain` field in the
1971 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001972 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001973 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001974 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001975 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001976 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001977 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001978 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001979 /// `namespace`.
1980 /// In each case the information returned is sufficient to perform the access
1981 /// check and the key id can be used to load further key artifacts.
1982 fn load_access_tuple(
1983 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001984 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001985 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001986 caller_uid: u32,
1987 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1988 match key.domain {
1989 // Domain App or SELinux. In this case we load the key_id from
1990 // the keyentry database for further loading of key components.
1991 // We already have the full access tuple to perform access control.
1992 // The only distinction is that we use the caller_uid instead
1993 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001994 // Domain::APP.
1995 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001996 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001997 if access_key.domain == Domain::APP {
1998 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001999 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002000 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002001 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002002
2003 Ok((key_id, access_key, None))
2004 }
2005
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002006 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002007 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002008 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002009 let mut stmt = tx
2010 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002011 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002012 WHERE grantee = ? AND id = ? AND
2013 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002014 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002015 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002016 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002017 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002018 .context("Domain:Grant: query failed.")?;
2019 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002020 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002021 let r =
2022 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002023 Ok((
2024 r.get(0).context("Failed to unpack key_id.")?,
2025 r.get(1).context("Failed to unpack access_vector.")?,
2026 ))
2027 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002028 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002029 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002030 }
2031
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002032 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002033 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002034 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002035 let (domain, namespace): (Domain, i64) = {
2036 let mut stmt = tx
2037 .prepare(
2038 "SELECT domain, namespace FROM persistent.keyentry
2039 WHERE
2040 id = ?
2041 AND state = ?;",
2042 )
2043 .context("Domain::KEY_ID: prepare statement failed")?;
2044 let mut rows = stmt
2045 .query(params![key.nspace, KeyLifeCycle::Live])
2046 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002047 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002048 let r =
2049 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002050 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002051 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002052 r.get(1).context("Failed to unpack namespace.")?,
2053 ))
2054 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002055 .context("Domain::KEY_ID.")?
2056 };
2057
2058 // We may use a key by id after loading it by grant.
2059 // In this case we have to check if the caller has a grant for this particular
2060 // key. We can skip this if we already know that the caller is the owner.
2061 // But we cannot know this if domain is anything but App. E.g. in the case
2062 // of Domain::SELINUX we have to speculatively check for grants because we have to
2063 // consult the SEPolicy before we know if the caller is the owner.
2064 let access_vector: Option<KeyPermSet> =
2065 if domain != Domain::APP || namespace != caller_uid as i64 {
2066 let access_vector: Option<i32> = tx
2067 .query_row(
2068 "SELECT access_vector FROM persistent.grant
2069 WHERE grantee = ? AND keyentryid = ?;",
2070 params![caller_uid as i64, key.nspace],
2071 |row| row.get(0),
2072 )
2073 .optional()
2074 .context("Domain::KEY_ID: query grant failed.")?;
2075 access_vector.map(|p| p.into())
2076 } else {
2077 None
2078 };
2079
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002080 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002081 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002082 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002083 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002084
Janis Danisevskis45760022021-01-19 16:34:10 -08002085 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002086 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002087 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002088 }
2089 }
2090
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002091 fn load_blob_components(
2092 key_id: i64,
2093 load_bits: KeyEntryLoadBits,
2094 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002095 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002096 let mut stmt = tx
2097 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002098 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002099 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2100 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002101 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002102
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002103 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002104
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002105 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002106 let mut cert_blob: Option<Vec<u8>> = None;
2107 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002108 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002109 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002110 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002111 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002112 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002113 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2114 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002115 key_blob = Some((
2116 row.get(0).context("Failed to extract key blob id.")?,
2117 row.get(2).context("Failed to extract key blob.")?,
2118 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002119 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002120 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002121 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002122 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002123 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002124 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002125 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002126 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002127 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002128 (SubComponentType::CERT, _, _)
2129 | (SubComponentType::CERT_CHAIN, _, _)
2130 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002131 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2132 }
2133 Ok(())
2134 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002135 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002136
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002137 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2138 Ok(Some((
2139 blob,
2140 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002141 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002142 )))
2143 })?;
2144
2145 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002146 }
2147
2148 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2149 let mut stmt = tx
2150 .prepare(
2151 "SELECT tag, data, security_level from persistent.keyparameter
2152 WHERE keyentryid = ?;",
2153 )
2154 .context("In load_key_parameters: prepare statement failed.")?;
2155
2156 let mut parameters: Vec<KeyParameter> = Vec::new();
2157
2158 let mut rows =
2159 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002160 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002161 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2162 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002163 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002164 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002165 .context("Failed to read KeyParameter.")?,
2166 );
2167 Ok(())
2168 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002169 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002170
2171 Ok(parameters)
2172 }
2173
Qi Wub9433b52020-12-01 14:52:46 +08002174 /// Decrements the usage count of a limited use key. This function first checks whether the
2175 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2176 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2177 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002178 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002179 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2180
Qi Wub9433b52020-12-01 14:52:46 +08002181 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2182 let limit: Option<i32> = tx
2183 .query_row(
2184 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2185 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2186 |row| row.get(0),
2187 )
2188 .optional()
2189 .context("Trying to load usage count")?;
2190
2191 let limit = limit
2192 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2193 .context("The Key no longer exists. Key is exhausted.")?;
2194
2195 tx.execute(
2196 "UPDATE persistent.keyparameter
2197 SET data = data - 1
2198 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2199 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2200 )
2201 .context("Failed to update key usage count.")?;
2202
2203 match limit {
2204 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002205 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002206 .context("Trying to mark limited use key for deletion."),
2207 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002208 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002209 }
2210 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002211 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002212 }
2213
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002214 /// Load a key entry by the given key descriptor.
2215 /// It uses the `check_permission` callback to verify if the access is allowed
2216 /// given the key access tuple read from the database using `load_access_tuple`.
2217 /// With `load_bits` the caller may specify which blobs shall be loaded from
2218 /// the blob database.
2219 pub fn load_key_entry(
2220 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002221 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002222 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002223 load_bits: KeyEntryLoadBits,
2224 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002225 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2226 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002227 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2228
Janis Danisevskis66784c42021-01-27 08:40:25 -08002229 loop {
2230 match self.load_key_entry_internal(
2231 key,
2232 key_type,
2233 load_bits,
2234 caller_uid,
2235 &check_permission,
2236 ) {
2237 Ok(result) => break Ok(result),
2238 Err(e) => {
2239 if Self::is_locked_error(&e) {
2240 std::thread::sleep(std::time::Duration::from_micros(500));
2241 continue;
2242 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002243 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002244 }
2245 }
2246 }
2247 }
2248 }
2249
2250 fn load_key_entry_internal(
2251 &mut self,
2252 key: &KeyDescriptor,
2253 key_type: KeyType,
2254 load_bits: KeyEntryLoadBits,
2255 caller_uid: u32,
2256 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002257 ) -> Result<(KeyIdGuard, KeyEntry)> {
2258 // KEY ID LOCK 1/2
2259 // If we got a key descriptor with a key id we can get the lock right away.
2260 // Otherwise we have to defer it until we know the key id.
2261 let key_id_guard = match key.domain {
2262 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2263 _ => None,
2264 };
2265
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002266 let tx = self
2267 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002268 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002269 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002270
2271 // Load the key_id and complete the access control tuple.
2272 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002273 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002274
2275 // Perform access control. It is vital that we return here if the permission is denied.
2276 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002277 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002278
Janis Danisevskisaec14592020-11-12 09:41:49 -08002279 // KEY ID LOCK 2/2
2280 // If we did not get a key id lock by now, it was because we got a key descriptor
2281 // without a key id. At this point we got the key id, so we can try and get a lock.
2282 // However, we cannot block here, because we are in the middle of the transaction.
2283 // So first we try to get the lock non blocking. If that fails, we roll back the
2284 // transaction and block until we get the lock. After we successfully got the lock,
2285 // we start a new transaction and load the access tuple again.
2286 //
2287 // We don't need to perform access control again, because we already established
2288 // that the caller had access to the given key. But we need to make sure that the
2289 // key id still exists. So we have to load the key entry by key id this time.
2290 let (key_id_guard, tx) = match key_id_guard {
2291 None => match KEY_ID_LOCK.try_get(key_id) {
2292 None => {
2293 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002294 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002295
Janis Danisevskisaec14592020-11-12 09:41:49 -08002296 // Block until we have a key id lock.
2297 let key_id_guard = KEY_ID_LOCK.get(key_id);
2298
2299 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002300 let tx = self
2301 .conn
2302 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002303 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002304
2305 Self::load_access_tuple(
2306 &tx,
2307 // This time we have to load the key by the retrieved key id, because the
2308 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002309 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002310 domain: Domain::KEY_ID,
2311 nspace: key_id,
2312 ..Default::default()
2313 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002314 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002315 caller_uid,
2316 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002317 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002318 (key_id_guard, tx)
2319 }
2320 Some(l) => (l, tx),
2321 },
2322 Some(key_id_guard) => (key_id_guard, tx),
2323 };
2324
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002325 let key_entry =
2326 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002327
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002328 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002329
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002330 Ok((key_id_guard, key_entry))
2331 }
2332
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002333 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002334 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002335 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2336 .context("Trying to delete keyentry.")?;
2337 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2338 .context("Trying to delete keymetadata.")?;
2339 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2340 .context("Trying to delete keyparameters.")?;
2341 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2342 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002343 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002344 }
2345
2346 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002347 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002348 pub fn unbind_key(
2349 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002350 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002351 key_type: KeyType,
2352 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002353 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002354 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002355 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2356
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002357 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2358 let (key_id, access_key_descriptor, access_vector) =
2359 Self::load_access_tuple(tx, key, key_type, caller_uid)
2360 .context("Trying to get access tuple.")?;
2361
2362 // Perform access control. It is vital that we return here if the permission is denied.
2363 // So do not touch that '?' at the end.
2364 check_permission(&access_key_descriptor, access_vector)
2365 .context("While checking permission.")?;
2366
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002367 Self::mark_unreferenced(tx, key_id)
2368 .map(|need_gc| (need_gc, ()))
2369 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002370 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002371 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002372 }
2373
Max Bires8e93d2b2021-01-14 13:17:59 -08002374 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2375 tx.query_row(
2376 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2377 params![key_id],
2378 |row| row.get(0),
2379 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002380 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002381 }
2382
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002383 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2384 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2385 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002386 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2387
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002388 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002389 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002390 }
2391 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2392 tx.execute(
2393 "DELETE FROM persistent.keymetadata
2394 WHERE keyentryid IN (
2395 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002396 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002397 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002398 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002399 )
2400 .context("Trying to delete keymetadata.")?;
2401 tx.execute(
2402 "DELETE FROM persistent.keyparameter
2403 WHERE keyentryid IN (
2404 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002405 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002406 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002407 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002408 )
2409 .context("Trying to delete keyparameters.")?;
2410 tx.execute(
2411 "DELETE FROM persistent.grant
2412 WHERE keyentryid IN (
2413 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002414 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002415 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002416 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002417 )
2418 .context("Trying to delete grants.")?;
2419 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002420 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002421 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2422 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002423 )
2424 .context("Trying to delete keyentry.")?;
2425 Ok(()).need_gc()
2426 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002427 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002428 }
2429
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002430 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2431 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2432 {
2433 tx.execute(
2434 "DELETE FROM persistent.keymetadata
2435 WHERE keyentryid IN (
2436 SELECT id FROM persistent.keyentry
2437 WHERE state = ?
2438 );",
2439 params![KeyLifeCycle::Unreferenced],
2440 )
2441 .context("Trying to delete keymetadata.")?;
2442 tx.execute(
2443 "DELETE FROM persistent.keyparameter
2444 WHERE keyentryid IN (
2445 SELECT id FROM persistent.keyentry
2446 WHERE state = ?
2447 );",
2448 params![KeyLifeCycle::Unreferenced],
2449 )
2450 .context("Trying to delete keyparameters.")?;
2451 tx.execute(
2452 "DELETE FROM persistent.grant
2453 WHERE keyentryid IN (
2454 SELECT id FROM persistent.keyentry
2455 WHERE state = ?
2456 );",
2457 params![KeyLifeCycle::Unreferenced],
2458 )
2459 .context("Trying to delete grants.")?;
2460 tx.execute(
2461 "DELETE FROM persistent.keyentry
2462 WHERE state = ?;",
2463 params![KeyLifeCycle::Unreferenced],
2464 )
2465 .context("Trying to delete keyentry.")?;
2466 Result::<()>::Ok(())
2467 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002468 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002469 }
2470
Hasini Gunasingheda895552021-01-27 19:34:37 +00002471 /// Delete the keys created on behalf of the user, denoted by the user id.
2472 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2473 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2474 /// The caller of this function should notify the gc if the returned value is true.
2475 pub fn unbind_keys_for_user(
2476 &mut self,
2477 user_id: u32,
2478 keep_non_super_encrypted_keys: bool,
2479 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002480 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2481
Hasini Gunasingheda895552021-01-27 19:34:37 +00002482 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2483 let mut stmt = tx
2484 .prepare(&format!(
2485 "SELECT id from persistent.keyentry
2486 WHERE (
2487 key_type = ?
2488 AND domain = ?
2489 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2490 AND state = ?
2491 ) OR (
2492 key_type = ?
2493 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002494 AND state = ?
2495 );",
2496 aid_user_offset = AID_USER_OFFSET
2497 ))
2498 .context(concat!(
2499 "In unbind_keys_for_user. ",
2500 "Failed to prepare the query to find the keys created by apps."
2501 ))?;
2502
2503 let mut rows = stmt
2504 .query(params![
2505 // WHERE client key:
2506 KeyType::Client,
2507 Domain::APP.0 as u32,
2508 user_id,
2509 KeyLifeCycle::Live,
2510 // OR super key:
2511 KeyType::Super,
2512 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002513 KeyLifeCycle::Live
2514 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002515 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002516
2517 let mut key_ids: Vec<i64> = Vec::new();
2518 db_utils::with_rows_extract_all(&mut rows, |row| {
2519 key_ids
2520 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2521 Ok(())
2522 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002523 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002524
2525 let mut notify_gc = false;
2526 for key_id in key_ids {
2527 if keep_non_super_encrypted_keys {
2528 // Load metadata and filter out non-super-encrypted keys.
2529 if let (_, Some((_, blob_metadata)), _, _) =
2530 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002531 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002532 {
2533 if blob_metadata.encrypted_by().is_none() {
2534 continue;
2535 }
2536 }
2537 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002538 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002539 .context("In unbind_keys_for_user.")?
2540 || notify_gc;
2541 }
2542 Ok(()).do_gc(notify_gc)
2543 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002544 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002545 }
2546
Eric Biggersb0478cf2023-10-27 03:55:29 +00002547 /// Deletes all auth-bound keys, i.e. keys that require user authentication, for the given user.
2548 /// This runs when the user's lock screen is being changed to Swipe or None.
2549 ///
2550 /// This intentionally does *not* delete keys that require that the device be unlocked, unless
2551 /// such keys also require user authentication. Keystore's concept of user authentication is
2552 /// fairly strong, and it requires that keys that require authentication be deleted as soon as
2553 /// authentication is no longer possible. In contrast, keys that just require that the device
2554 /// be unlocked should remain usable when the lock screen is set to Swipe or None, as the device
2555 /// is always considered "unlocked" in that case.
2556 pub fn unbind_auth_bound_keys_for_user(&mut self, user_id: u32) -> Result<()> {
2557 let _wp = wd::watch_millis("KeystoreDB::unbind_auth_bound_keys_for_user", 500);
2558
2559 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2560 let mut stmt = tx
2561 .prepare(&format!(
2562 "SELECT id from persistent.keyentry
2563 WHERE key_type = ?
2564 AND domain = ?
2565 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2566 AND state = ?;",
2567 aid_user_offset = AID_USER_OFFSET
2568 ))
2569 .context(concat!(
2570 "In unbind_auth_bound_keys_for_user. ",
2571 "Failed to prepare the query to find the keys created by apps."
2572 ))?;
2573
2574 let mut rows = stmt
2575 .query(params![KeyType::Client, Domain::APP.0 as u32, user_id, KeyLifeCycle::Live,])
2576 .context(ks_err!("Failed to query the keys created by apps."))?;
2577
2578 let mut key_ids: Vec<i64> = Vec::new();
2579 db_utils::with_rows_extract_all(&mut rows, |row| {
2580 key_ids
2581 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2582 Ok(())
2583 })
2584 .context(ks_err!())?;
2585
2586 let mut notify_gc = false;
2587 let mut num_unbound = 0;
2588 for key_id in key_ids {
2589 // Load the key parameters and filter out non-auth-bound keys. To identify
2590 // auth-bound keys, use the presence of UserSecureID. The absence of NoAuthRequired
2591 // could also be used, but UserSecureID is what Keystore treats as authoritative
2592 // when actually enforcing the key parameters (it might not matter, though).
2593 let params = Self::load_key_parameters(key_id, tx)
2594 .context("Failed to load key parameters.")?;
2595 let is_auth_bound_key = params.iter().any(|kp| {
2596 matches!(kp.key_parameter_value(), KeyParameterValue::UserSecureID(_))
2597 });
2598 if is_auth_bound_key {
2599 notify_gc = Self::mark_unreferenced(tx, key_id)
2600 .context("In unbind_auth_bound_keys_for_user.")?
2601 || notify_gc;
2602 num_unbound += 1;
2603 }
2604 }
2605 log::info!("Deleting {num_unbound} auth-bound keys for user {user_id}");
2606 Ok(()).do_gc(notify_gc)
2607 })
2608 .context(ks_err!())
2609 }
2610
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002611 fn load_key_components(
2612 tx: &Transaction,
2613 load_bits: KeyEntryLoadBits,
2614 key_id: i64,
2615 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002616 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002617
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002618 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002619 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002620
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002621 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002622 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002623
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002624 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002625 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002626
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002627 Ok(KeyEntry {
2628 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002629 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002630 cert: cert_blob,
2631 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002632 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002633 parameters,
2634 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002635 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002636 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002637 }
2638
Eran Messeri24f31972023-01-25 17:00:33 +00002639 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2640 /// aliases are greater than the specified 'start_past_alias'. If no value
2641 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002642 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002643 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002644 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002645 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002646 &mut self,
2647 domain: Domain,
2648 namespace: i64,
2649 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002650 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002651 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002652 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002653
Eran Messeri24f31972023-01-25 17:00:33 +00002654 let query = format!(
2655 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002656 WHERE domain = ?
2657 AND namespace = ?
2658 AND alias IS NOT NULL
2659 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002660 AND key_type = ?
2661 {}
2662 ORDER BY alias ASC;",
2663 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2664 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002665
Eran Messeri24f31972023-01-25 17:00:33 +00002666 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2667 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2668
2669 let mut rows = match start_past_alias {
2670 Some(past_alias) => stmt
2671 .query(params![
2672 domain.0 as u32,
2673 namespace,
2674 KeyLifeCycle::Live,
2675 key_type,
2676 past_alias
2677 ])
2678 .context(ks_err!("Failed to query."))?,
2679 None => stmt
2680 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2681 .context(ks_err!("Failed to query."))?,
2682 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002683
Janis Danisevskis66784c42021-01-27 08:40:25 -08002684 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2685 db_utils::with_rows_extract_all(&mut rows, |row| {
2686 descriptors.push(KeyDescriptor {
2687 domain,
2688 nspace: namespace,
2689 alias: Some(row.get(0).context("Trying to extract alias.")?),
2690 blob: None,
2691 });
2692 Ok(())
2693 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002694 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002695 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002696 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002697 }
2698
Eran Messeri24f31972023-01-25 17:00:33 +00002699 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2700 /// Domain must be APP or SELINUX, the caller must make sure of that.
2701 pub fn count_keys(
2702 &mut self,
2703 domain: Domain,
2704 namespace: i64,
2705 key_type: KeyType,
2706 ) -> Result<usize> {
2707 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2708
2709 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2710 tx.query_row(
2711 "SELECT COUNT(alias) FROM persistent.keyentry
2712 WHERE domain = ?
2713 AND namespace = ?
2714 AND alias IS NOT NULL
2715 AND state = ?
2716 AND key_type = ?;",
2717 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2718 |row| row.get(0),
2719 )
2720 .context(ks_err!("Failed to count number of keys."))
2721 .no_gc()
2722 })?;
2723 Ok(num_keys)
2724 }
2725
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002726 /// Adds a grant to the grant table.
2727 /// Like `load_key_entry` this function loads the access tuple before
2728 /// it uses the callback for a permission check. Upon success,
2729 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2730 /// grant table. The new row will have a randomized id, which is used as
2731 /// grant id in the namespace field of the resulting KeyDescriptor.
2732 pub fn grant(
2733 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002734 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002735 caller_uid: u32,
2736 grantee_uid: u32,
2737 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002738 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002739 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002740 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2741
Janis Danisevskis66784c42021-01-27 08:40:25 -08002742 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2743 // Load the key_id and complete the access control tuple.
2744 // We ignore the access vector here because grants cannot be granted.
2745 // The access vector returned here expresses the permissions the
2746 // grantee has if key.domain == Domain::GRANT. But this vector
2747 // cannot include the grant permission by design, so there is no way the
2748 // subsequent permission check can pass.
2749 // We could check key.domain == Domain::GRANT and fail early.
2750 // But even if we load the access tuple by grant here, the permission
2751 // check denies the attempt to create a grant by grant descriptor.
2752 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002753 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002754
Janis Danisevskis66784c42021-01-27 08:40:25 -08002755 // Perform access control. It is vital that we return here if the permission
2756 // was denied. So do not touch that '?' at the end of the line.
2757 // This permission check checks if the caller has the grant permission
2758 // for the given key and in addition to all of the permissions
2759 // expressed in `access_vector`.
2760 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002761 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002762
Janis Danisevskis66784c42021-01-27 08:40:25 -08002763 let grant_id = if let Some(grant_id) = tx
2764 .query_row(
2765 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002766 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002767 params![key_id, grantee_uid],
2768 |row| row.get(0),
2769 )
2770 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002771 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002772 {
2773 tx.execute(
2774 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002775 SET access_vector = ?
2776 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002777 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002778 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002779 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002780 grant_id
2781 } else {
2782 Self::insert_with_retry(|id| {
2783 tx.execute(
2784 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2785 VALUES (?, ?, ?, ?);",
2786 params![id, grantee_uid, key_id, i32::from(access_vector)],
2787 )
2788 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002789 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002790 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002791
Janis Danisevskis66784c42021-01-27 08:40:25 -08002792 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002793 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002794 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002795 }
2796
2797 /// This function checks permissions like `grant` and `load_key_entry`
2798 /// before removing a grant from the grant table.
2799 pub fn ungrant(
2800 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002801 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002802 caller_uid: u32,
2803 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002804 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002805 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002806 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2807
Janis Danisevskis66784c42021-01-27 08:40:25 -08002808 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2809 // Load the key_id and complete the access control tuple.
2810 // We ignore the access vector here because grants cannot be granted.
2811 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002812 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002813
Janis Danisevskis66784c42021-01-27 08:40:25 -08002814 // Perform access control. We must return here if the permission
2815 // was denied. So do not touch the '?' at the end of this line.
2816 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002817 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002818
Janis Danisevskis66784c42021-01-27 08:40:25 -08002819 tx.execute(
2820 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002821 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002822 params![key_id, grantee_uid],
2823 )
2824 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002825
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002826 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002827 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002828 }
2829
Joel Galenson845f74b2020-09-09 14:11:55 -07002830 // Generates a random id and passes it to the given function, which will
2831 // try to insert it into a database. If that insertion fails, retry;
2832 // otherwise return the id.
2833 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2834 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002835 let newid: i64 = match random() {
2836 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2837 i => i,
2838 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002839 match inserter(newid) {
2840 // If the id already existed, try again.
2841 Err(rusqlite::Error::SqliteFailure(
2842 libsqlite3_sys::Error {
2843 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2844 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2845 },
2846 _,
2847 )) => (),
2848 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002849 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002850 }
2851 _ => return Ok(newid),
2852 }
2853 }
2854 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002855
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002856 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2857 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
2858 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
2859 auth_token.clone(),
2860 MonotonicRawTime::now(),
2861 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002862 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002863
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002864 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002865 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002866 where
2867 F: Fn(&AuthTokenEntry) -> bool,
2868 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002869 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002870 }
2871
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002872 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002873 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
2874 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002875 }
2876
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002877 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002878 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
2879 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002880 }
2881
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002882 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002883 fn get_last_off_body(&self) -> MonotonicRawTime {
2884 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002885 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002886
2887 /// Load descriptor of a key by key id
2888 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2889 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2890
2891 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2892 tx.query_row(
2893 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2894 params![key_id],
2895 |row| {
2896 Ok(KeyDescriptor {
2897 domain: Domain(row.get(0)?),
2898 nspace: row.get(1)?,
2899 alias: row.get(2)?,
2900 blob: None,
2901 })
2902 },
2903 )
2904 .optional()
2905 .context("Trying to load key descriptor")
2906 .no_gc()
2907 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002908 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002909 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002910}
2911
2912#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002913pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002914
2915 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002916 use crate::key_parameter::{
2917 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2918 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2919 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002920 use crate::key_perm_set;
2921 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002922 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002923 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002924 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2925 HardwareAuthToken::HardwareAuthToken,
2926 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002927 };
2928 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002929 Timestamp::Timestamp,
2930 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002931 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07002932 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002933 use std::collections::BTreeMap;
2934 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002935 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002936 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002937 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002938 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002939 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002940 #[cfg(disabled)]
2941 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002942
Seth Moore7ee79f92021-12-07 11:42:49 -08002943 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002944 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002945
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002946 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002947 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002948 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002949 })?;
2950 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002951 }
2952
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002953 fn rebind_alias(
2954 db: &mut KeystoreDB,
2955 newid: &KeyIdGuard,
2956 alias: &str,
2957 domain: Domain,
2958 namespace: i64,
2959 ) -> Result<bool> {
2960 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002961 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002962 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002963 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002964 }
2965
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002966 #[test]
2967 fn datetime() -> Result<()> {
2968 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002969 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002970 let now = SystemTime::now();
2971 let duration = Duration::from_secs(1000);
2972 let then = now.checked_sub(duration).unwrap();
2973 let soon = now.checked_add(duration).unwrap();
2974 conn.execute(
2975 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2976 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2977 )?;
2978 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002979 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002980 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2981 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2982 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2983 assert!(rows.next()?.is_none());
2984 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2985 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2986 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2987 Ok(())
2988 }
2989
Joel Galenson0891bc12020-07-20 10:37:03 -07002990 // Ensure that we're using the "injected" random function, not the real one.
2991 #[test]
2992 fn test_mocked_random() {
2993 let rand1 = random();
2994 let rand2 = random();
2995 let rand3 = random();
2996 if rand1 == rand2 {
2997 assert_eq!(rand2 + 1, rand3);
2998 } else {
2999 assert_eq!(rand1 + 1, rand2);
3000 assert_eq!(rand2, rand3);
3001 }
3002 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003003
Joel Galenson26f4d012020-07-17 14:57:21 -07003004 // Test that we have the correct tables.
3005 #[test]
3006 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003007 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003008 let tables = db
3009 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003010 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003011 .query_map(params![], |row| row.get(0))?
3012 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003013 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003014 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003015 assert_eq!(tables[1], "blobmetadata");
3016 assert_eq!(tables[2], "grant");
3017 assert_eq!(tables[3], "keyentry");
3018 assert_eq!(tables[4], "keymetadata");
3019 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003020 Ok(())
3021 }
3022
3023 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003024 fn test_auth_token_table_invariant() -> Result<()> {
3025 let mut db = new_test_db()?;
3026 let auth_token1 = HardwareAuthToken {
3027 challenge: i64::MAX,
3028 userId: 200,
3029 authenticatorId: 200,
3030 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3031 timestamp: Timestamp { milliSeconds: 500 },
3032 mac: String::from("mac").into_bytes(),
3033 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003034 db.insert_auth_token(&auth_token1);
3035 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003036 assert_eq!(auth_tokens_returned.len(), 1);
3037
3038 // insert another auth token with the same values for the columns in the UNIQUE constraint
3039 // of the auth token table and different value for timestamp
3040 let auth_token2 = HardwareAuthToken {
3041 challenge: i64::MAX,
3042 userId: 200,
3043 authenticatorId: 200,
3044 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3045 timestamp: Timestamp { milliSeconds: 600 },
3046 mac: String::from("mac").into_bytes(),
3047 };
3048
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003049 db.insert_auth_token(&auth_token2);
3050 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003051 assert_eq!(auth_tokens_returned.len(), 1);
3052
3053 if let Some(auth_token) = auth_tokens_returned.pop() {
3054 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3055 }
3056
3057 // insert another auth token with the different values for the columns in the UNIQUE
3058 // constraint of the auth token table
3059 let auth_token3 = HardwareAuthToken {
3060 challenge: i64::MAX,
3061 userId: 201,
3062 authenticatorId: 200,
3063 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3064 timestamp: Timestamp { milliSeconds: 600 },
3065 mac: String::from("mac").into_bytes(),
3066 };
3067
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003068 db.insert_auth_token(&auth_token3);
3069 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003070 assert_eq!(auth_tokens_returned.len(), 2);
3071
3072 Ok(())
3073 }
3074
3075 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003076 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3077 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003078 }
3079
3080 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003081 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003082 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003083 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003084
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003085 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003086 let entries = get_keyentry(&db)?;
3087 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003088
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003089 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003090
3091 let entries_new = get_keyentry(&db)?;
3092 assert_eq!(entries, entries_new);
3093 Ok(())
3094 }
3095
3096 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003097 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003098 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3099 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003100 }
3101
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003102 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003103
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003104 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3105 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003106
3107 let entries = get_keyentry(&db)?;
3108 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003109 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3110 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003111
3112 // Test that we must pass in a valid Domain.
3113 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003114 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003115 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003116 );
3117 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003118 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003119 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003120 );
3121 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003122 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003123 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003124 );
3125
3126 Ok(())
3127 }
3128
Joel Galenson33c04ad2020-08-03 11:04:38 -07003129 #[test]
3130 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003131 fn extractor(
3132 ke: &KeyEntryRow,
3133 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3134 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003135 }
3136
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003137 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003138 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3139 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003140 let entries = get_keyentry(&db)?;
3141 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003142 assert_eq!(
3143 extractor(&entries[0]),
3144 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3145 );
3146 assert_eq!(
3147 extractor(&entries[1]),
3148 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3149 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003150
3151 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003152 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003153 let entries = get_keyentry(&db)?;
3154 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003155 assert_eq!(
3156 extractor(&entries[0]),
3157 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3158 );
3159 assert_eq!(
3160 extractor(&entries[1]),
3161 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3162 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003163
3164 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003165 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003166 let entries = get_keyentry(&db)?;
3167 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003168 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3169 assert_eq!(
3170 extractor(&entries[1]),
3171 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3172 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003173
3174 // Test that we must pass in a valid Domain.
3175 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003176 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003177 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003178 );
3179 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003180 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003181 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003182 );
3183 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003184 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003185 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003186 );
3187
3188 // Test that we correctly handle setting an alias for something that does not exist.
3189 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003190 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003191 "Expected to update a single entry but instead updated 0",
3192 );
3193 // Test that we correctly abort the transaction in this case.
3194 let entries = get_keyentry(&db)?;
3195 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003196 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3197 assert_eq!(
3198 extractor(&entries[1]),
3199 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3200 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003201
3202 Ok(())
3203 }
3204
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003205 #[test]
3206 fn test_grant_ungrant() -> Result<()> {
3207 const CALLER_UID: u32 = 15;
3208 const GRANTEE_UID: u32 = 12;
3209 const SELINUX_NAMESPACE: i64 = 7;
3210
3211 let mut db = new_test_db()?;
3212 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003213 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3214 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3215 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003216 )?;
3217 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003218 domain: super::Domain::APP,
3219 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003220 alias: Some("key".to_string()),
3221 blob: None,
3222 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003223 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3224 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003225
3226 // Reset totally predictable random number generator in case we
3227 // are not the first test running on this thread.
3228 reset_random();
3229 let next_random = 0i64;
3230
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003231 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003232 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003233 assert_eq!(*a, PVEC1);
3234 assert_eq!(
3235 *k,
3236 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003237 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003238 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003239 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003240 alias: Some("key".to_string()),
3241 blob: None,
3242 }
3243 );
3244 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003245 })
3246 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003247
3248 assert_eq!(
3249 app_granted_key,
3250 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003251 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003252 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003253 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003254 alias: None,
3255 blob: None,
3256 }
3257 );
3258
3259 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003260 domain: super::Domain::SELINUX,
3261 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003262 alias: Some("yek".to_string()),
3263 blob: None,
3264 };
3265
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003266 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003267 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003268 assert_eq!(*a, PVEC1);
3269 assert_eq!(
3270 *k,
3271 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003272 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003273 // namespace must be the supplied SELinux
3274 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003275 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003276 alias: Some("yek".to_string()),
3277 blob: None,
3278 }
3279 );
3280 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003281 })
3282 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003283
3284 assert_eq!(
3285 selinux_granted_key,
3286 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003287 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003288 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003289 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003290 alias: None,
3291 blob: None,
3292 }
3293 );
3294
3295 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003296 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003297 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003298 assert_eq!(*a, PVEC2);
3299 assert_eq!(
3300 *k,
3301 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003302 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003303 // namespace must be the supplied SELinux
3304 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003305 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003306 alias: Some("yek".to_string()),
3307 blob: None,
3308 }
3309 );
3310 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003311 })
3312 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003313
3314 assert_eq!(
3315 selinux_granted_key,
3316 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003317 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003318 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003319 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003320 alias: None,
3321 blob: None,
3322 }
3323 );
3324
3325 {
3326 // Limiting scope of stmt, because it borrows db.
3327 let mut stmt = db
3328 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003329 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003330 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3331 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3332 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003333
3334 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003335 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003336 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003337 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003338 assert!(rows.next().is_none());
3339 }
3340
3341 debug_dump_keyentry_table(&mut db)?;
3342 println!("app_key {:?}", app_key);
3343 println!("selinux_key {:?}", selinux_key);
3344
Janis Danisevskis66784c42021-01-27 08:40:25 -08003345 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3346 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003347
3348 Ok(())
3349 }
3350
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003351 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003352 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3353 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3354
3355 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003356 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003357 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003358 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003359 let mut blob_metadata = BlobMetaData::new();
3360 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3361 db.set_blob(
3362 &key_id,
3363 SubComponentType::KEY_BLOB,
3364 Some(TEST_KEY_BLOB),
3365 Some(&blob_metadata),
3366 )?;
3367 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3368 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003369 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003370
3371 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003372 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003373 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003374 )?;
3375 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003376 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003377 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003378 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003379 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003380 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003381 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003382 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003383 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003384 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003385
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003386 drop(rows);
3387 drop(stmt);
3388
3389 assert_eq!(
3390 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3391 BlobMetaData::load_from_db(id, tx).no_gc()
3392 })
3393 .expect("Should find blob metadata."),
3394 blob_metadata
3395 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003396 Ok(())
3397 }
3398
3399 static TEST_ALIAS: &str = "my super duper key";
3400
3401 #[test]
3402 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3403 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003404 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003405 .context("test_insert_and_load_full_keyentry_domain_app")?
3406 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003407 let (_key_guard, key_entry) = db
3408 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003409 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003410 domain: Domain::APP,
3411 nspace: 0,
3412 alias: Some(TEST_ALIAS.to_string()),
3413 blob: None,
3414 },
3415 KeyType::Client,
3416 KeyEntryLoadBits::BOTH,
3417 1,
3418 |_k, _av| Ok(()),
3419 )
3420 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003421 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003422
3423 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003424 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003425 domain: Domain::APP,
3426 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003427 alias: Some(TEST_ALIAS.to_string()),
3428 blob: None,
3429 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003430 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003431 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003432 |_, _| Ok(()),
3433 )
3434 .unwrap();
3435
3436 assert_eq!(
3437 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3438 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003439 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003440 domain: Domain::APP,
3441 nspace: 0,
3442 alias: Some(TEST_ALIAS.to_string()),
3443 blob: None,
3444 },
3445 KeyType::Client,
3446 KeyEntryLoadBits::NONE,
3447 1,
3448 |_k, _av| Ok(()),
3449 )
3450 .unwrap_err()
3451 .root_cause()
3452 .downcast_ref::<KsError>()
3453 );
3454
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003455 Ok(())
3456 }
3457
3458 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003459 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3460 let mut db = new_test_db()?;
3461
3462 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003463 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003464 domain: Domain::APP,
3465 nspace: 1,
3466 alias: Some(TEST_ALIAS.to_string()),
3467 blob: None,
3468 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003469 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003470 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003471 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003472 )
3473 .expect("Trying to insert cert.");
3474
3475 let (_key_guard, mut key_entry) = db
3476 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003477 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003478 domain: Domain::APP,
3479 nspace: 1,
3480 alias: Some(TEST_ALIAS.to_string()),
3481 blob: None,
3482 },
3483 KeyType::Client,
3484 KeyEntryLoadBits::PUBLIC,
3485 1,
3486 |_k, _av| Ok(()),
3487 )
3488 .expect("Trying to read certificate entry.");
3489
3490 assert!(key_entry.pure_cert());
3491 assert!(key_entry.cert().is_none());
3492 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3493
3494 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003495 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003496 domain: Domain::APP,
3497 nspace: 1,
3498 alias: Some(TEST_ALIAS.to_string()),
3499 blob: None,
3500 },
3501 KeyType::Client,
3502 1,
3503 |_, _| Ok(()),
3504 )
3505 .unwrap();
3506
3507 assert_eq!(
3508 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3509 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003510 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003511 domain: Domain::APP,
3512 nspace: 1,
3513 alias: Some(TEST_ALIAS.to_string()),
3514 blob: None,
3515 },
3516 KeyType::Client,
3517 KeyEntryLoadBits::NONE,
3518 1,
3519 |_k, _av| Ok(()),
3520 )
3521 .unwrap_err()
3522 .root_cause()
3523 .downcast_ref::<KsError>()
3524 );
3525
3526 Ok(())
3527 }
3528
3529 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003530 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3531 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003532 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003533 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3534 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003535 let (_key_guard, key_entry) = db
3536 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003537 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003538 domain: Domain::SELINUX,
3539 nspace: 1,
3540 alias: Some(TEST_ALIAS.to_string()),
3541 blob: None,
3542 },
3543 KeyType::Client,
3544 KeyEntryLoadBits::BOTH,
3545 1,
3546 |_k, _av| Ok(()),
3547 )
3548 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003549 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003550
3551 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003552 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003553 domain: Domain::SELINUX,
3554 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003555 alias: Some(TEST_ALIAS.to_string()),
3556 blob: None,
3557 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003558 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003559 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003560 |_, _| Ok(()),
3561 )
3562 .unwrap();
3563
3564 assert_eq!(
3565 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3566 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003567 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003568 domain: Domain::SELINUX,
3569 nspace: 1,
3570 alias: Some(TEST_ALIAS.to_string()),
3571 blob: None,
3572 },
3573 KeyType::Client,
3574 KeyEntryLoadBits::NONE,
3575 1,
3576 |_k, _av| Ok(()),
3577 )
3578 .unwrap_err()
3579 .root_cause()
3580 .downcast_ref::<KsError>()
3581 );
3582
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003583 Ok(())
3584 }
3585
3586 #[test]
3587 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3588 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003589 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003590 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3591 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003592 let (_, key_entry) = db
3593 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003594 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003595 KeyType::Client,
3596 KeyEntryLoadBits::BOTH,
3597 1,
3598 |_k, _av| Ok(()),
3599 )
3600 .unwrap();
3601
Qi Wub9433b52020-12-01 14:52:46 +08003602 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003603
3604 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003605 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003606 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003607 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003608 |_, _| Ok(()),
3609 )
3610 .unwrap();
3611
3612 assert_eq!(
3613 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3614 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003615 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003616 KeyType::Client,
3617 KeyEntryLoadBits::NONE,
3618 1,
3619 |_k, _av| Ok(()),
3620 )
3621 .unwrap_err()
3622 .root_cause()
3623 .downcast_ref::<KsError>()
3624 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003625
3626 Ok(())
3627 }
3628
3629 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003630 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3631 let mut db = new_test_db()?;
3632 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3633 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3634 .0;
3635 // Update the usage count of the limited use key.
3636 db.check_and_update_key_usage_count(key_id)?;
3637
3638 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003639 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003640 KeyType::Client,
3641 KeyEntryLoadBits::BOTH,
3642 1,
3643 |_k, _av| Ok(()),
3644 )?;
3645
3646 // The usage count is decremented now.
3647 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3648
3649 Ok(())
3650 }
3651
3652 #[test]
3653 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3654 let mut db = new_test_db()?;
3655 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3656 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3657 .0;
3658 // Update the usage count of the limited use key.
3659 db.check_and_update_key_usage_count(key_id).expect(concat!(
3660 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3661 "This should succeed."
3662 ));
3663
3664 // Try to update the exhausted limited use key.
3665 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3666 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3667 "This should fail."
3668 ));
3669 assert_eq!(
3670 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3671 e.root_cause().downcast_ref::<KsError>().unwrap()
3672 );
3673
3674 Ok(())
3675 }
3676
3677 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003678 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3679 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003680 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003681 .context("test_insert_and_load_full_keyentry_from_grant")?
3682 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003683
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003684 let granted_key = db
3685 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003686 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003687 domain: Domain::APP,
3688 nspace: 0,
3689 alias: Some(TEST_ALIAS.to_string()),
3690 blob: None,
3691 },
3692 1,
3693 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003694 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003695 |_k, _av| Ok(()),
3696 )
3697 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003698
3699 debug_dump_grant_table(&mut db)?;
3700
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003701 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003702 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3703 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003704 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003705 Ok(())
3706 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003707 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003708
Qi Wub9433b52020-12-01 14:52:46 +08003709 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003710
Janis Danisevskis66784c42021-01-27 08:40:25 -08003711 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003712
3713 assert_eq!(
3714 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3715 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003716 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003717 KeyType::Client,
3718 KeyEntryLoadBits::NONE,
3719 2,
3720 |_k, _av| Ok(()),
3721 )
3722 .unwrap_err()
3723 .root_cause()
3724 .downcast_ref::<KsError>()
3725 );
3726
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003727 Ok(())
3728 }
3729
Janis Danisevskis45760022021-01-19 16:34:10 -08003730 // This test attempts to load a key by key id while the caller is not the owner
3731 // but a grant exists for the given key and the caller.
3732 #[test]
3733 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3734 let mut db = new_test_db()?;
3735 const OWNER_UID: u32 = 1u32;
3736 const GRANTEE_UID: u32 = 2u32;
3737 const SOMEONE_ELSE_UID: u32 = 3u32;
3738 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3739 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3740 .0;
3741
3742 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003743 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003744 domain: Domain::APP,
3745 nspace: 0,
3746 alias: Some(TEST_ALIAS.to_string()),
3747 blob: None,
3748 },
3749 OWNER_UID,
3750 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003751 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003752 |_k, _av| Ok(()),
3753 )
3754 .unwrap();
3755
3756 debug_dump_grant_table(&mut db)?;
3757
3758 let id_descriptor =
3759 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3760
3761 let (_, key_entry) = db
3762 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003763 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003764 KeyType::Client,
3765 KeyEntryLoadBits::BOTH,
3766 GRANTEE_UID,
3767 |k, av| {
3768 assert_eq!(Domain::APP, k.domain);
3769 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003770 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003771 Ok(())
3772 },
3773 )
3774 .unwrap();
3775
3776 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3777
3778 let (_, key_entry) = db
3779 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003780 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003781 KeyType::Client,
3782 KeyEntryLoadBits::BOTH,
3783 SOMEONE_ELSE_UID,
3784 |k, av| {
3785 assert_eq!(Domain::APP, k.domain);
3786 assert_eq!(OWNER_UID as i64, k.nspace);
3787 assert!(av.is_none());
3788 Ok(())
3789 },
3790 )
3791 .unwrap();
3792
3793 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3794
Janis Danisevskis66784c42021-01-27 08:40:25 -08003795 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003796
3797 assert_eq!(
3798 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3799 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003800 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003801 KeyType::Client,
3802 KeyEntryLoadBits::NONE,
3803 GRANTEE_UID,
3804 |_k, _av| Ok(()),
3805 )
3806 .unwrap_err()
3807 .root_cause()
3808 .downcast_ref::<KsError>()
3809 );
3810
3811 Ok(())
3812 }
3813
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003814 // Creates a key migrates it to a different location and then tries to access it by the old
3815 // and new location.
3816 #[test]
3817 fn test_migrate_key_app_to_app() -> Result<()> {
3818 let mut db = new_test_db()?;
3819 const SOURCE_UID: u32 = 1u32;
3820 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003821 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3822 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003823 let key_id_guard =
3824 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3825 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3826
3827 let source_descriptor: KeyDescriptor = KeyDescriptor {
3828 domain: Domain::APP,
3829 nspace: -1,
3830 alias: Some(SOURCE_ALIAS.to_string()),
3831 blob: None,
3832 };
3833
3834 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3835 domain: Domain::APP,
3836 nspace: -1,
3837 alias: Some(DESTINATION_ALIAS.to_string()),
3838 blob: None,
3839 };
3840
3841 let key_id = key_id_guard.id();
3842
3843 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3844 Ok(())
3845 })
3846 .unwrap();
3847
3848 let (_, key_entry) = db
3849 .load_key_entry(
3850 &destination_descriptor,
3851 KeyType::Client,
3852 KeyEntryLoadBits::BOTH,
3853 DESTINATION_UID,
3854 |k, av| {
3855 assert_eq!(Domain::APP, k.domain);
3856 assert_eq!(DESTINATION_UID as i64, k.nspace);
3857 assert!(av.is_none());
3858 Ok(())
3859 },
3860 )
3861 .unwrap();
3862
3863 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3864
3865 assert_eq!(
3866 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3867 db.load_key_entry(
3868 &source_descriptor,
3869 KeyType::Client,
3870 KeyEntryLoadBits::NONE,
3871 SOURCE_UID,
3872 |_k, _av| Ok(()),
3873 )
3874 .unwrap_err()
3875 .root_cause()
3876 .downcast_ref::<KsError>()
3877 );
3878
3879 Ok(())
3880 }
3881
3882 // Creates a key migrates it to a different location and then tries to access it by the old
3883 // and new location.
3884 #[test]
3885 fn test_migrate_key_app_to_selinux() -> Result<()> {
3886 let mut db = new_test_db()?;
3887 const SOURCE_UID: u32 = 1u32;
3888 const DESTINATION_UID: u32 = 2u32;
3889 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003890 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3891 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003892 let key_id_guard =
3893 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3894 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3895
3896 let source_descriptor: KeyDescriptor = KeyDescriptor {
3897 domain: Domain::APP,
3898 nspace: -1,
3899 alias: Some(SOURCE_ALIAS.to_string()),
3900 blob: None,
3901 };
3902
3903 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3904 domain: Domain::SELINUX,
3905 nspace: DESTINATION_NAMESPACE,
3906 alias: Some(DESTINATION_ALIAS.to_string()),
3907 blob: None,
3908 };
3909
3910 let key_id = key_id_guard.id();
3911
3912 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3913 Ok(())
3914 })
3915 .unwrap();
3916
3917 let (_, key_entry) = db
3918 .load_key_entry(
3919 &destination_descriptor,
3920 KeyType::Client,
3921 KeyEntryLoadBits::BOTH,
3922 DESTINATION_UID,
3923 |k, av| {
3924 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003925 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003926 assert!(av.is_none());
3927 Ok(())
3928 },
3929 )
3930 .unwrap();
3931
3932 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3933
3934 assert_eq!(
3935 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3936 db.load_key_entry(
3937 &source_descriptor,
3938 KeyType::Client,
3939 KeyEntryLoadBits::NONE,
3940 SOURCE_UID,
3941 |_k, _av| Ok(()),
3942 )
3943 .unwrap_err()
3944 .root_cause()
3945 .downcast_ref::<KsError>()
3946 );
3947
3948 Ok(())
3949 }
3950
3951 // Creates two keys and tries to migrate the first to the location of the second which
3952 // is expected to fail.
3953 #[test]
3954 fn test_migrate_key_destination_occupied() -> Result<()> {
3955 let mut db = new_test_db()?;
3956 const SOURCE_UID: u32 = 1u32;
3957 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003958 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3959 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003960 let key_id_guard =
3961 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3962 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3963 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
3964 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3965
3966 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3967 domain: Domain::APP,
3968 nspace: -1,
3969 alias: Some(DESTINATION_ALIAS.to_string()),
3970 blob: None,
3971 };
3972
3973 assert_eq!(
3974 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
3975 db.migrate_key_namespace(
3976 key_id_guard,
3977 &destination_descriptor,
3978 DESTINATION_UID,
3979 |_k| Ok(())
3980 )
3981 .unwrap_err()
3982 .root_cause()
3983 .downcast_ref::<KsError>()
3984 );
3985
3986 Ok(())
3987 }
3988
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003989 #[test]
3990 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003991 const ALIAS1: &str = "test_upgrade_0_to_1_1";
3992 const ALIAS2: &str = "test_upgrade_0_to_1_2";
3993 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003994 const UID: u32 = 33;
3995 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
3996 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
3997 let key_id_untouched1 =
3998 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
3999 let key_id_untouched2 =
4000 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4001 let key_id_deleted =
4002 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4003
4004 let (_, key_entry) = db
4005 .load_key_entry(
4006 &KeyDescriptor {
4007 domain: Domain::APP,
4008 nspace: -1,
4009 alias: Some(ALIAS1.to_string()),
4010 blob: None,
4011 },
4012 KeyType::Client,
4013 KeyEntryLoadBits::BOTH,
4014 UID,
4015 |k, av| {
4016 assert_eq!(Domain::APP, k.domain);
4017 assert_eq!(UID as i64, k.nspace);
4018 assert!(av.is_none());
4019 Ok(())
4020 },
4021 )
4022 .unwrap();
4023 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4024 let (_, key_entry) = db
4025 .load_key_entry(
4026 &KeyDescriptor {
4027 domain: Domain::APP,
4028 nspace: -1,
4029 alias: Some(ALIAS2.to_string()),
4030 blob: None,
4031 },
4032 KeyType::Client,
4033 KeyEntryLoadBits::BOTH,
4034 UID,
4035 |k, av| {
4036 assert_eq!(Domain::APP, k.domain);
4037 assert_eq!(UID as i64, k.nspace);
4038 assert!(av.is_none());
4039 Ok(())
4040 },
4041 )
4042 .unwrap();
4043 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4044 let (_, key_entry) = db
4045 .load_key_entry(
4046 &KeyDescriptor {
4047 domain: Domain::APP,
4048 nspace: -1,
4049 alias: Some(ALIAS3.to_string()),
4050 blob: None,
4051 },
4052 KeyType::Client,
4053 KeyEntryLoadBits::BOTH,
4054 UID,
4055 |k, av| {
4056 assert_eq!(Domain::APP, k.domain);
4057 assert_eq!(UID as i64, k.nspace);
4058 assert!(av.is_none());
4059 Ok(())
4060 },
4061 )
4062 .unwrap();
4063 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4064
4065 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4066 KeystoreDB::from_0_to_1(tx).no_gc()
4067 })
4068 .unwrap();
4069
4070 let (_, key_entry) = db
4071 .load_key_entry(
4072 &KeyDescriptor {
4073 domain: Domain::APP,
4074 nspace: -1,
4075 alias: Some(ALIAS1.to_string()),
4076 blob: None,
4077 },
4078 KeyType::Client,
4079 KeyEntryLoadBits::BOTH,
4080 UID,
4081 |k, av| {
4082 assert_eq!(Domain::APP, k.domain);
4083 assert_eq!(UID as i64, k.nspace);
4084 assert!(av.is_none());
4085 Ok(())
4086 },
4087 )
4088 .unwrap();
4089 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4090 let (_, key_entry) = db
4091 .load_key_entry(
4092 &KeyDescriptor {
4093 domain: Domain::APP,
4094 nspace: -1,
4095 alias: Some(ALIAS2.to_string()),
4096 blob: None,
4097 },
4098 KeyType::Client,
4099 KeyEntryLoadBits::BOTH,
4100 UID,
4101 |k, av| {
4102 assert_eq!(Domain::APP, k.domain);
4103 assert_eq!(UID as i64, k.nspace);
4104 assert!(av.is_none());
4105 Ok(())
4106 },
4107 )
4108 .unwrap();
4109 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4110 assert_eq!(
4111 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4112 db.load_key_entry(
4113 &KeyDescriptor {
4114 domain: Domain::APP,
4115 nspace: -1,
4116 alias: Some(ALIAS3.to_string()),
4117 blob: None,
4118 },
4119 KeyType::Client,
4120 KeyEntryLoadBits::BOTH,
4121 UID,
4122 |k, av| {
4123 assert_eq!(Domain::APP, k.domain);
4124 assert_eq!(UID as i64, k.nspace);
4125 assert!(av.is_none());
4126 Ok(())
4127 },
4128 )
4129 .unwrap_err()
4130 .root_cause()
4131 .downcast_ref::<KsError>()
4132 );
4133 }
4134
Janis Danisevskisaec14592020-11-12 09:41:49 -08004135 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4136
Janis Danisevskisaec14592020-11-12 09:41:49 -08004137 #[test]
4138 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4139 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004140 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4141 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004142 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004143 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004144 .context("test_insert_and_load_full_keyentry_domain_app")?
4145 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004146 let (_key_guard, key_entry) = db
4147 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004148 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004149 domain: Domain::APP,
4150 nspace: 0,
4151 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4152 blob: None,
4153 },
4154 KeyType::Client,
4155 KeyEntryLoadBits::BOTH,
4156 33,
4157 |_k, _av| Ok(()),
4158 )
4159 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004160 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004161 let state = Arc::new(AtomicU8::new(1));
4162 let state2 = state.clone();
4163
4164 // Spawning a second thread that attempts to acquire the key id lock
4165 // for the same key as the primary thread. The primary thread then
4166 // waits, thereby forcing the secondary thread into the second stage
4167 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4168 // The test succeeds if the secondary thread observes the transition
4169 // of `state` from 1 to 2, despite having a whole second to overtake
4170 // the primary thread.
4171 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004172 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004173 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004174 assert!(db
4175 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004176 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004177 domain: Domain::APP,
4178 nspace: 0,
4179 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4180 blob: None,
4181 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004182 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004183 KeyEntryLoadBits::BOTH,
4184 33,
4185 |_k, _av| Ok(()),
4186 )
4187 .is_ok());
4188 // We should only see a 2 here because we can only return
4189 // from load_key_entry when the `_key_guard` expires,
4190 // which happens at the end of the scope.
4191 assert_eq!(2, state2.load(Ordering::Relaxed));
4192 });
4193
4194 thread::sleep(std::time::Duration::from_millis(1000));
4195
4196 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4197
4198 // Return the handle from this scope so we can join with the
4199 // secondary thread after the key id lock has expired.
4200 handle
4201 // This is where the `_key_guard` goes out of scope,
4202 // which is the reason for concurrent load_key_entry on the same key
4203 // to unblock.
4204 };
4205 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4206 // main test thread. We will not see failing asserts in secondary threads otherwise.
4207 handle.join().unwrap();
4208 Ok(())
4209 }
4210
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004211 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004212 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004213 let temp_dir =
4214 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4215
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004216 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4217 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004218
4219 let _tx1 = db1
4220 .conn
4221 .transaction_with_behavior(TransactionBehavior::Immediate)
4222 .expect("Failed to create first transaction.");
4223
4224 let error = db2
4225 .conn
4226 .transaction_with_behavior(TransactionBehavior::Immediate)
4227 .context("Transaction begin failed.")
4228 .expect_err("This should fail.");
4229 let root_cause = error.root_cause();
4230 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4231 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4232 {
4233 return;
4234 }
4235 panic!(
4236 "Unexpected error {:?} \n{:?} \n{:?}",
4237 error,
4238 root_cause,
4239 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4240 )
4241 }
4242
4243 #[cfg(disabled)]
4244 #[test]
4245 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4246 let temp_dir = Arc::new(
4247 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4248 .expect("Failed to create temp dir."),
4249 );
4250
4251 let test_begin = Instant::now();
4252
Janis Danisevskis66784c42021-01-27 08:40:25 -08004253 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004254 let mut db =
4255 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004256 const OPEN_DB_COUNT: u32 = 50u32;
4257
4258 let mut actual_key_count = KEY_COUNT;
4259 // First insert KEY_COUNT keys.
4260 for count in 0..KEY_COUNT {
4261 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4262 actual_key_count = count;
4263 break;
4264 }
4265 let alias = format!("test_alias_{}", count);
4266 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4267 .expect("Failed to make key entry.");
4268 }
4269
4270 // Insert more keys from a different thread and into a different namespace.
4271 let temp_dir1 = temp_dir.clone();
4272 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004273 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4274 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004275
4276 for count in 0..actual_key_count {
4277 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4278 return;
4279 }
4280 let alias = format!("test_alias_{}", count);
4281 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4282 .expect("Failed to make key entry.");
4283 }
4284
4285 // then unbind them again.
4286 for count in 0..actual_key_count {
4287 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4288 return;
4289 }
4290 let key = KeyDescriptor {
4291 domain: Domain::APP,
4292 nspace: -1,
4293 alias: Some(format!("test_alias_{}", count)),
4294 blob: None,
4295 };
4296 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4297 }
4298 });
4299
4300 // And start unbinding the first set of keys.
4301 let temp_dir2 = temp_dir.clone();
4302 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004303 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4304 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004305
4306 for count in 0..actual_key_count {
4307 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4308 return;
4309 }
4310 let key = KeyDescriptor {
4311 domain: Domain::APP,
4312 nspace: -1,
4313 alias: Some(format!("test_alias_{}", count)),
4314 blob: None,
4315 };
4316 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4317 }
4318 });
4319
Janis Danisevskis66784c42021-01-27 08:40:25 -08004320 // While a lot of inserting and deleting is going on we have to open database connections
4321 // successfully and use them.
4322 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4323 // out of scope.
4324 #[allow(clippy::redundant_clone)]
4325 let temp_dir4 = temp_dir.clone();
4326 let handle4 = thread::spawn(move || {
4327 for count in 0..OPEN_DB_COUNT {
4328 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4329 return;
4330 }
Seth Moore444b51a2021-06-11 09:49:49 -07004331 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4332 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004333
4334 let alias = format!("test_alias_{}", count);
4335 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4336 .expect("Failed to make key entry.");
4337 let key = KeyDescriptor {
4338 domain: Domain::APP,
4339 nspace: -1,
4340 alias: Some(alias),
4341 blob: None,
4342 };
4343 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4344 }
4345 });
4346
4347 handle1.join().expect("Thread 1 panicked.");
4348 handle2.join().expect("Thread 2 panicked.");
4349 handle4.join().expect("Thread 4 panicked.");
4350
Janis Danisevskis66784c42021-01-27 08:40:25 -08004351 Ok(())
4352 }
4353
4354 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004355 fn list() -> Result<()> {
4356 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004357 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004358 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4359 (Domain::APP, 1, "test1"),
4360 (Domain::APP, 1, "test2"),
4361 (Domain::APP, 1, "test3"),
4362 (Domain::APP, 1, "test4"),
4363 (Domain::APP, 1, "test5"),
4364 (Domain::APP, 1, "test6"),
4365 (Domain::APP, 1, "test7"),
4366 (Domain::APP, 2, "test1"),
4367 (Domain::APP, 2, "test2"),
4368 (Domain::APP, 2, "test3"),
4369 (Domain::APP, 2, "test4"),
4370 (Domain::APP, 2, "test5"),
4371 (Domain::APP, 2, "test6"),
4372 (Domain::APP, 2, "test8"),
4373 (Domain::SELINUX, 100, "test1"),
4374 (Domain::SELINUX, 100, "test2"),
4375 (Domain::SELINUX, 100, "test3"),
4376 (Domain::SELINUX, 100, "test4"),
4377 (Domain::SELINUX, 100, "test5"),
4378 (Domain::SELINUX, 100, "test6"),
4379 (Domain::SELINUX, 100, "test9"),
4380 ];
4381
4382 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4383 .iter()
4384 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004385 let entry =
4386 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004387 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4388 });
4389 (entry.id(), *ns)
4390 })
4391 .collect();
4392
4393 for (domain, namespace) in
4394 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4395 {
4396 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4397 .iter()
4398 .filter_map(|(domain, ns, alias)| match ns {
4399 ns if *ns == *namespace => Some(KeyDescriptor {
4400 domain: *domain,
4401 nspace: *ns,
4402 alias: Some(alias.to_string()),
4403 blob: None,
4404 }),
4405 _ => None,
4406 })
4407 .collect();
4408 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004409 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004410 list_result.sort();
4411 assert_eq!(list_o_descriptors, list_result);
4412
4413 let mut list_o_ids: Vec<i64> = list_o_descriptors
4414 .into_iter()
4415 .map(|d| {
4416 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004417 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004418 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004419 KeyType::Client,
4420 KeyEntryLoadBits::NONE,
4421 *namespace as u32,
4422 |_, _| Ok(()),
4423 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004424 .unwrap();
4425 entry.id()
4426 })
4427 .collect();
4428 list_o_ids.sort_unstable();
4429 let mut loaded_entries: Vec<i64> = list_o_keys
4430 .iter()
4431 .filter_map(|(id, ns)| match ns {
4432 ns if *ns == *namespace => Some(*id),
4433 _ => None,
4434 })
4435 .collect();
4436 loaded_entries.sort_unstable();
4437 assert_eq!(list_o_ids, loaded_entries);
4438 }
Eran Messeri24f31972023-01-25 17:00:33 +00004439 assert_eq!(
4440 Vec::<KeyDescriptor>::new(),
4441 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4442 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004443
4444 Ok(())
4445 }
4446
Joel Galenson0891bc12020-07-20 10:37:03 -07004447 // Helpers
4448
4449 // Checks that the given result is an error containing the given string.
4450 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4451 let error_str = format!(
4452 "{:#?}",
4453 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4454 );
4455 assert!(
4456 error_str.contains(target),
4457 "The string \"{}\" should contain \"{}\"",
4458 error_str,
4459 target
4460 );
4461 }
4462
Joel Galenson2aab4432020-07-22 15:27:57 -07004463 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004464 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004465 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004466 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004467 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004468 namespace: Option<i64>,
4469 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004470 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004471 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004472 }
4473
4474 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4475 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004476 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004477 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004478 Ok(KeyEntryRow {
4479 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004480 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004481 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004482 namespace: row.get(3)?,
4483 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004484 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004485 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004486 })
4487 })?
4488 .map(|r| r.context("Could not read keyentry row."))
4489 .collect::<Result<Vec<_>>>()
4490 }
4491
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004492 // Note: The parameters and SecurityLevel associations are nonsensical. This
4493 // collection is only used to check if the parameters are preserved as expected by the
4494 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004495 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4496 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004497 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4498 KeyParameter::new(
4499 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4500 SecurityLevel::TRUSTED_ENVIRONMENT,
4501 ),
4502 KeyParameter::new(
4503 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4504 SecurityLevel::TRUSTED_ENVIRONMENT,
4505 ),
4506 KeyParameter::new(
4507 KeyParameterValue::Algorithm(Algorithm::RSA),
4508 SecurityLevel::TRUSTED_ENVIRONMENT,
4509 ),
4510 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4511 KeyParameter::new(
4512 KeyParameterValue::BlockMode(BlockMode::ECB),
4513 SecurityLevel::TRUSTED_ENVIRONMENT,
4514 ),
4515 KeyParameter::new(
4516 KeyParameterValue::BlockMode(BlockMode::GCM),
4517 SecurityLevel::TRUSTED_ENVIRONMENT,
4518 ),
4519 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4520 KeyParameter::new(
4521 KeyParameterValue::Digest(Digest::MD5),
4522 SecurityLevel::TRUSTED_ENVIRONMENT,
4523 ),
4524 KeyParameter::new(
4525 KeyParameterValue::Digest(Digest::SHA_2_224),
4526 SecurityLevel::TRUSTED_ENVIRONMENT,
4527 ),
4528 KeyParameter::new(
4529 KeyParameterValue::Digest(Digest::SHA_2_256),
4530 SecurityLevel::STRONGBOX,
4531 ),
4532 KeyParameter::new(
4533 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4534 SecurityLevel::TRUSTED_ENVIRONMENT,
4535 ),
4536 KeyParameter::new(
4537 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4538 SecurityLevel::TRUSTED_ENVIRONMENT,
4539 ),
4540 KeyParameter::new(
4541 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4542 SecurityLevel::STRONGBOX,
4543 ),
4544 KeyParameter::new(
4545 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4546 SecurityLevel::TRUSTED_ENVIRONMENT,
4547 ),
4548 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4549 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4550 KeyParameter::new(
4551 KeyParameterValue::EcCurve(EcCurve::P_224),
4552 SecurityLevel::TRUSTED_ENVIRONMENT,
4553 ),
4554 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4555 KeyParameter::new(
4556 KeyParameterValue::EcCurve(EcCurve::P_384),
4557 SecurityLevel::TRUSTED_ENVIRONMENT,
4558 ),
4559 KeyParameter::new(
4560 KeyParameterValue::EcCurve(EcCurve::P_521),
4561 SecurityLevel::TRUSTED_ENVIRONMENT,
4562 ),
4563 KeyParameter::new(
4564 KeyParameterValue::RSAPublicExponent(3),
4565 SecurityLevel::TRUSTED_ENVIRONMENT,
4566 ),
4567 KeyParameter::new(
4568 KeyParameterValue::IncludeUniqueID,
4569 SecurityLevel::TRUSTED_ENVIRONMENT,
4570 ),
4571 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4572 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4573 KeyParameter::new(
4574 KeyParameterValue::ActiveDateTime(1234567890),
4575 SecurityLevel::STRONGBOX,
4576 ),
4577 KeyParameter::new(
4578 KeyParameterValue::OriginationExpireDateTime(1234567890),
4579 SecurityLevel::TRUSTED_ENVIRONMENT,
4580 ),
4581 KeyParameter::new(
4582 KeyParameterValue::UsageExpireDateTime(1234567890),
4583 SecurityLevel::TRUSTED_ENVIRONMENT,
4584 ),
4585 KeyParameter::new(
4586 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4587 SecurityLevel::TRUSTED_ENVIRONMENT,
4588 ),
4589 KeyParameter::new(
4590 KeyParameterValue::MaxUsesPerBoot(1234567890),
4591 SecurityLevel::TRUSTED_ENVIRONMENT,
4592 ),
4593 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4594 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4595 KeyParameter::new(
4596 KeyParameterValue::NoAuthRequired,
4597 SecurityLevel::TRUSTED_ENVIRONMENT,
4598 ),
4599 KeyParameter::new(
4600 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4601 SecurityLevel::TRUSTED_ENVIRONMENT,
4602 ),
4603 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4604 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4605 KeyParameter::new(
4606 KeyParameterValue::TrustedUserPresenceRequired,
4607 SecurityLevel::TRUSTED_ENVIRONMENT,
4608 ),
4609 KeyParameter::new(
4610 KeyParameterValue::TrustedConfirmationRequired,
4611 SecurityLevel::TRUSTED_ENVIRONMENT,
4612 ),
4613 KeyParameter::new(
4614 KeyParameterValue::UnlockedDeviceRequired,
4615 SecurityLevel::TRUSTED_ENVIRONMENT,
4616 ),
4617 KeyParameter::new(
4618 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4619 SecurityLevel::SOFTWARE,
4620 ),
4621 KeyParameter::new(
4622 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4623 SecurityLevel::SOFTWARE,
4624 ),
4625 KeyParameter::new(
4626 KeyParameterValue::CreationDateTime(12345677890),
4627 SecurityLevel::SOFTWARE,
4628 ),
4629 KeyParameter::new(
4630 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4631 SecurityLevel::TRUSTED_ENVIRONMENT,
4632 ),
4633 KeyParameter::new(
4634 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4635 SecurityLevel::TRUSTED_ENVIRONMENT,
4636 ),
4637 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4638 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4639 KeyParameter::new(
4640 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4641 SecurityLevel::SOFTWARE,
4642 ),
4643 KeyParameter::new(
4644 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4645 SecurityLevel::TRUSTED_ENVIRONMENT,
4646 ),
4647 KeyParameter::new(
4648 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4649 SecurityLevel::TRUSTED_ENVIRONMENT,
4650 ),
4651 KeyParameter::new(
4652 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4653 SecurityLevel::TRUSTED_ENVIRONMENT,
4654 ),
4655 KeyParameter::new(
4656 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4657 SecurityLevel::TRUSTED_ENVIRONMENT,
4658 ),
4659 KeyParameter::new(
4660 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4661 SecurityLevel::TRUSTED_ENVIRONMENT,
4662 ),
4663 KeyParameter::new(
4664 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4665 SecurityLevel::TRUSTED_ENVIRONMENT,
4666 ),
4667 KeyParameter::new(
4668 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4669 SecurityLevel::TRUSTED_ENVIRONMENT,
4670 ),
4671 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004672 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4673 SecurityLevel::TRUSTED_ENVIRONMENT,
4674 ),
4675 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004676 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4677 SecurityLevel::TRUSTED_ENVIRONMENT,
4678 ),
4679 KeyParameter::new(
4680 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4681 SecurityLevel::TRUSTED_ENVIRONMENT,
4682 ),
4683 KeyParameter::new(
4684 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4685 SecurityLevel::TRUSTED_ENVIRONMENT,
4686 ),
4687 KeyParameter::new(
4688 KeyParameterValue::VendorPatchLevel(3),
4689 SecurityLevel::TRUSTED_ENVIRONMENT,
4690 ),
4691 KeyParameter::new(
4692 KeyParameterValue::BootPatchLevel(4),
4693 SecurityLevel::TRUSTED_ENVIRONMENT,
4694 ),
4695 KeyParameter::new(
4696 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4697 SecurityLevel::TRUSTED_ENVIRONMENT,
4698 ),
4699 KeyParameter::new(
4700 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4701 SecurityLevel::TRUSTED_ENVIRONMENT,
4702 ),
4703 KeyParameter::new(
4704 KeyParameterValue::MacLength(256),
4705 SecurityLevel::TRUSTED_ENVIRONMENT,
4706 ),
4707 KeyParameter::new(
4708 KeyParameterValue::ResetSinceIdRotation,
4709 SecurityLevel::TRUSTED_ENVIRONMENT,
4710 ),
4711 KeyParameter::new(
4712 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4713 SecurityLevel::TRUSTED_ENVIRONMENT,
4714 ),
Qi Wub9433b52020-12-01 14:52:46 +08004715 ];
4716 if let Some(value) = max_usage_count {
4717 params.push(KeyParameter::new(
4718 KeyParameterValue::UsageCountLimit(value),
4719 SecurityLevel::SOFTWARE,
4720 ));
4721 }
4722 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004723 }
4724
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004725 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004726 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004727 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004728 namespace: i64,
4729 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004730 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004731 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004732 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004733 let mut blob_metadata = BlobMetaData::new();
4734 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4735 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4736 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4737 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4738 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4739
4740 db.set_blob(
4741 &key_id,
4742 SubComponentType::KEY_BLOB,
4743 Some(TEST_KEY_BLOB),
4744 Some(&blob_metadata),
4745 )?;
4746 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4747 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004748
4749 let params = make_test_params(max_usage_count);
4750 db.insert_keyparameter(&key_id, &params)?;
4751
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004752 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004753 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004754 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004755 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004756 Ok(key_id)
4757 }
4758
Qi Wub9433b52020-12-01 14:52:46 +08004759 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4760 let params = make_test_params(max_usage_count);
4761
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004762 let mut blob_metadata = BlobMetaData::new();
4763 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4764 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4765 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4766 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4767 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4768
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004769 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004770 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004771
4772 KeyEntry {
4773 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004774 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004775 cert: Some(TEST_CERT_BLOB.to_vec()),
4776 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004777 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004778 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004779 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004780 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004781 }
4782 }
4783
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004784 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004785 db: &mut KeystoreDB,
4786 domain: Domain,
4787 namespace: i64,
4788 alias: &str,
4789 logical_only: bool,
4790 ) -> Result<KeyIdGuard> {
4791 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4792 let mut blob_metadata = BlobMetaData::new();
4793 if !logical_only {
4794 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4795 }
4796 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4797
4798 db.set_blob(
4799 &key_id,
4800 SubComponentType::KEY_BLOB,
4801 Some(TEST_KEY_BLOB),
4802 Some(&blob_metadata),
4803 )?;
4804 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4805 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4806
4807 let mut params = make_test_params(None);
4808 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4809
4810 db.insert_keyparameter(&key_id, &params)?;
4811
4812 let mut metadata = KeyMetaData::new();
4813 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4814 db.insert_key_metadata(&key_id, &metadata)?;
4815 rebind_alias(db, &key_id, alias, domain, namespace)?;
4816 Ok(key_id)
4817 }
4818
Eric Biggersb0478cf2023-10-27 03:55:29 +00004819 // Creates an app key that is marked as being superencrypted by the given
4820 // super key ID and that has the given authentication and unlocked device
4821 // parameters. This does not actually superencrypt the key blob.
4822 fn make_superencrypted_key_entry(
4823 db: &mut KeystoreDB,
4824 namespace: i64,
4825 alias: &str,
4826 requires_authentication: bool,
4827 requires_unlocked_device: bool,
4828 super_key_id: i64,
4829 ) -> Result<KeyIdGuard> {
4830 let domain = Domain::APP;
4831 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4832
4833 let mut blob_metadata = BlobMetaData::new();
4834 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4835 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::KeyId(super_key_id)));
4836 db.set_blob(
4837 &key_id,
4838 SubComponentType::KEY_BLOB,
4839 Some(TEST_KEY_BLOB),
4840 Some(&blob_metadata),
4841 )?;
4842
4843 let mut params = vec![];
4844 if requires_unlocked_device {
4845 params.push(KeyParameter::new(
4846 KeyParameterValue::UnlockedDeviceRequired,
4847 SecurityLevel::TRUSTED_ENVIRONMENT,
4848 ));
4849 }
4850 if requires_authentication {
4851 params.push(KeyParameter::new(
4852 KeyParameterValue::UserSecureID(42),
4853 SecurityLevel::TRUSTED_ENVIRONMENT,
4854 ));
4855 }
4856 db.insert_keyparameter(&key_id, &params)?;
4857
4858 let mut metadata = KeyMetaData::new();
4859 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4860 db.insert_key_metadata(&key_id, &metadata)?;
4861
4862 rebind_alias(db, &key_id, alias, domain, namespace)?;
4863 Ok(key_id)
4864 }
4865
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004866 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4867 let mut params = make_test_params(None);
4868 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4869
4870 let mut blob_metadata = BlobMetaData::new();
4871 if !logical_only {
4872 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4873 }
4874 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4875
4876 let mut metadata = KeyMetaData::new();
4877 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4878
4879 KeyEntry {
4880 id: key_id,
4881 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4882 cert: Some(TEST_CERT_BLOB.to_vec()),
4883 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4884 km_uuid: KEYSTORE_UUID,
4885 parameters: params,
4886 metadata,
4887 pure_cert: false,
4888 }
4889 }
4890
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004891 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004892 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004893 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004894 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004895 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004896 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004897 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004898 Ok((
4899 row.get(0)?,
4900 row.get(1)?,
4901 row.get(2)?,
4902 row.get(3)?,
4903 row.get(4)?,
4904 row.get(5)?,
4905 row.get(6)?,
4906 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004907 },
4908 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004909
4910 println!("Key entry table rows:");
4911 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004912 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004913 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004914 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4915 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004916 );
4917 }
4918 Ok(())
4919 }
4920
4921 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004922 let mut stmt = db
4923 .conn
4924 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004925 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004926 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4927 })?;
4928
4929 println!("Grant table rows:");
4930 for r in rows {
4931 let (id, gt, ki, av) = r.unwrap();
4932 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4933 }
4934 Ok(())
4935 }
4936
Joel Galenson0891bc12020-07-20 10:37:03 -07004937 // Use a custom random number generator that repeats each number once.
4938 // This allows us to test repeated elements.
4939
4940 thread_local! {
4941 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4942 }
4943
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004944 fn reset_random() {
4945 RANDOM_COUNTER.with(|counter| {
4946 *counter.borrow_mut() = 0;
4947 })
4948 }
4949
Joel Galenson0891bc12020-07-20 10:37:03 -07004950 pub fn random() -> i64 {
4951 RANDOM_COUNTER.with(|counter| {
4952 let result = *counter.borrow() / 2;
4953 *counter.borrow_mut() += 1;
4954 result
4955 })
4956 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004957
4958 #[test]
4959 fn test_last_off_body() -> Result<()> {
4960 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004961 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004962 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004963 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004964 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004965 let one_second = Duration::from_secs(1);
4966 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004967 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004968 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004969 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004970 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00004971 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004972 Ok(())
4973 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00004974
4975 #[test]
4976 fn test_unbind_keys_for_user() -> Result<()> {
4977 let mut db = new_test_db()?;
4978 db.unbind_keys_for_user(1, false)?;
4979
4980 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4981 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4982 db.unbind_keys_for_user(2, false)?;
4983
Eran Messeri24f31972023-01-25 17:00:33 +00004984 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4985 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004986
4987 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00004988 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004989
4990 Ok(())
4991 }
4992
4993 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004994 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
4995 let mut db = new_test_db()?;
4996 let super_key = keystore2_crypto::generate_aes256_key()?;
4997 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
4998 let (encrypted_super_key, metadata) =
4999 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5000
5001 let key_name_enc = SuperKeyType {
5002 alias: "test_super_key_1",
5003 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005004 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005005 };
5006
5007 let key_name_nonenc = SuperKeyType {
5008 alias: "test_super_key_2",
5009 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00005010 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005011 };
5012
5013 // Install two super keys.
5014 db.store_super_key(
5015 1,
5016 &key_name_nonenc,
5017 &super_key,
5018 &BlobMetaData::new(),
5019 &KeyMetaData::new(),
5020 )?;
5021 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5022
5023 // Check that both can be found in the database.
5024 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5025 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5026
5027 // Install the same keys for a different user.
5028 db.store_super_key(
5029 2,
5030 &key_name_nonenc,
5031 &super_key,
5032 &BlobMetaData::new(),
5033 &KeyMetaData::new(),
5034 )?;
5035 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5036
5037 // Check that the second pair of keys can be found in the database.
5038 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5039 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5040
5041 // Delete only encrypted keys.
5042 db.unbind_keys_for_user(1, true)?;
5043
5044 // The encrypted superkey should be gone now.
5045 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5046 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5047
5048 // Reinsert the encrypted key.
5049 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5050
5051 // Check that both can be found in the database, again..
5052 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5053 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5054
5055 // Delete all even unencrypted keys.
5056 db.unbind_keys_for_user(1, false)?;
5057
5058 // Both should be gone now.
5059 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5060 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5061
5062 // Check that the second pair of keys was untouched.
5063 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5064 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5065
5066 Ok(())
5067 }
5068
Eric Biggersb0478cf2023-10-27 03:55:29 +00005069 fn app_key_exists(db: &mut KeystoreDB, nspace: i64, alias: &str) -> Result<bool> {
5070 db.key_exists(Domain::APP, nspace, alias, KeyType::Client)
5071 }
5072
5073 // Tests the unbind_auth_bound_keys_for_user() function.
5074 #[test]
5075 fn test_unbind_auth_bound_keys_for_user() -> Result<()> {
5076 let mut db = new_test_db()?;
5077 let user_id = 1;
5078 let nspace: i64 = (user_id * AID_USER_OFFSET).into();
5079 let other_user_id = 2;
5080 let other_user_nspace: i64 = (other_user_id * AID_USER_OFFSET).into();
5081 let super_key_type = &USER_AFTER_FIRST_UNLOCK_SUPER_KEY;
5082
5083 // Create a superencryption key.
5084 let super_key = keystore2_crypto::generate_aes256_key()?;
5085 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5086 let (encrypted_super_key, blob_metadata) =
5087 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5088 db.store_super_key(
5089 user_id,
5090 super_key_type,
5091 &encrypted_super_key,
5092 &blob_metadata,
5093 &KeyMetaData::new(),
5094 )?;
5095 let super_key_id = db.load_super_key(super_key_type, user_id)?.unwrap().0 .0;
5096
5097 // Store 4 superencrypted app keys, one for each possible combination of
5098 // (authentication required, unlocked device required).
5099 make_superencrypted_key_entry(&mut db, nspace, "noauth_noud", false, false, super_key_id)?;
5100 make_superencrypted_key_entry(&mut db, nspace, "noauth_ud", false, true, super_key_id)?;
5101 make_superencrypted_key_entry(&mut db, nspace, "auth_noud", true, false, super_key_id)?;
5102 make_superencrypted_key_entry(&mut db, nspace, "auth_ud", true, true, super_key_id)?;
5103 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5104 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5105 assert!(app_key_exists(&mut db, nspace, "auth_noud")?);
5106 assert!(app_key_exists(&mut db, nspace, "auth_ud")?);
5107
5108 // Also store a key for a different user that requires authentication.
5109 make_superencrypted_key_entry(
5110 &mut db,
5111 other_user_nspace,
5112 "auth_ud",
5113 true,
5114 true,
5115 super_key_id,
5116 )?;
5117
5118 db.unbind_auth_bound_keys_for_user(user_id)?;
5119
5120 // Verify that only the user's app keys that require authentication were
5121 // deleted. Keys that require an unlocked device but not authentication
5122 // should *not* have been deleted, nor should the super key have been
5123 // deleted, nor should other users' keys have been deleted.
5124 assert!(db.load_super_key(super_key_type, user_id)?.is_some());
5125 assert!(app_key_exists(&mut db, nspace, "noauth_noud")?);
5126 assert!(app_key_exists(&mut db, nspace, "noauth_ud")?);
5127 assert!(!app_key_exists(&mut db, nspace, "auth_noud")?);
5128 assert!(!app_key_exists(&mut db, nspace, "auth_ud")?);
5129 assert!(app_key_exists(&mut db, other_user_nspace, "auth_ud")?);
5130
5131 Ok(())
5132 }
5133
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005134 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005135 fn test_store_super_key() -> Result<()> {
5136 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005137 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005138 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005139 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005140 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005141 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005142
5143 let (encrypted_super_key, metadata) =
5144 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005145 db.store_super_key(
5146 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00005147 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005148 &encrypted_super_key,
5149 &metadata,
5150 &KeyMetaData::new(),
5151 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005152
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005153 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00005154 assert!(db.key_exists(
5155 Domain::APP,
5156 1,
5157 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
5158 KeyType::Super
5159 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005160
Eric Biggers673d34a2023-10-18 01:54:18 +00005161 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005162 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00005163 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07005164 key_entry,
5165 &pw,
5166 None,
5167 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005168
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005169 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005170 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005171
Hasini Gunasingheda895552021-01-27 19:34:37 +00005172 Ok(())
5173 }
Seth Moore78c091f2021-04-09 21:38:30 +00005174
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005175 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005176 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005177 MetricsStorage::KEY_ENTRY,
5178 MetricsStorage::KEY_ENTRY_ID_INDEX,
5179 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5180 MetricsStorage::BLOB_ENTRY,
5181 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5182 MetricsStorage::KEY_PARAMETER,
5183 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5184 MetricsStorage::KEY_METADATA,
5185 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5186 MetricsStorage::GRANT,
5187 MetricsStorage::AUTH_TOKEN,
5188 MetricsStorage::BLOB_METADATA,
5189 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005190 ]
5191 }
5192
5193 /// Perform a simple check to ensure that we can query all the storage types
5194 /// that are supported by the DB. Check for reasonable values.
5195 #[test]
5196 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005197 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005198
5199 let mut db = new_test_db()?;
5200
5201 for t in get_valid_statsd_storage_types() {
5202 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005203 // AuthToken can be less than a page since it's in a btree, not sqlite
5204 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005205 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005206 } else {
5207 assert!(stat.size >= PAGE_SIZE);
5208 }
Seth Moore78c091f2021-04-09 21:38:30 +00005209 assert!(stat.size >= stat.unused_size);
5210 }
5211
5212 Ok(())
5213 }
5214
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005215 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005216 get_valid_statsd_storage_types()
5217 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005218 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005219 .collect()
5220 }
5221
5222 fn assert_storage_increased(
5223 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005224 increased_storage_types: Vec<MetricsStorage>,
5225 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005226 ) {
5227 for storage in increased_storage_types {
5228 // Verify the expected storage increased.
5229 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005230 let old = &baseline[&storage.0];
5231 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005232 assert!(
5233 new.unused_size <= old.unused_size,
5234 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005235 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005236 new.unused_size,
5237 old.unused_size
5238 );
5239
5240 // Update the baseline with the new value so that it succeeds in the
5241 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005242 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005243 }
5244
5245 // Get an updated map of the storage and verify there were no unexpected changes.
5246 let updated_stats = get_storage_stats_map(db);
5247 assert_eq!(updated_stats.len(), baseline.len());
5248
5249 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005250 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005251 let mut s = String::new();
5252 for &k in map.keys() {
5253 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5254 .expect("string concat failed");
5255 }
5256 s
5257 };
5258
5259 assert!(
5260 updated_stats[&k].size == baseline[&k].size
5261 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5262 "updated_stats:\n{}\nbaseline:\n{}",
5263 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005264 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005265 );
5266 }
5267 }
5268
5269 #[test]
5270 fn test_verify_key_table_size_reporting() -> Result<()> {
5271 let mut db = new_test_db()?;
5272 let mut working_stats = get_storage_stats_map(&mut db);
5273
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005274 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005275 assert_storage_increased(
5276 &mut db,
5277 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005278 MetricsStorage::KEY_ENTRY,
5279 MetricsStorage::KEY_ENTRY_ID_INDEX,
5280 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005281 ],
5282 &mut working_stats,
5283 );
5284
5285 let mut blob_metadata = BlobMetaData::new();
5286 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5287 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5288 assert_storage_increased(
5289 &mut db,
5290 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005291 MetricsStorage::BLOB_ENTRY,
5292 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5293 MetricsStorage::BLOB_METADATA,
5294 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005295 ],
5296 &mut working_stats,
5297 );
5298
5299 let params = make_test_params(None);
5300 db.insert_keyparameter(&key_id, &params)?;
5301 assert_storage_increased(
5302 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005303 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005304 &mut working_stats,
5305 );
5306
5307 let mut metadata = KeyMetaData::new();
5308 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5309 db.insert_key_metadata(&key_id, &metadata)?;
5310 assert_storage_increased(
5311 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005312 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005313 &mut working_stats,
5314 );
5315
5316 let mut sum = 0;
5317 for stat in working_stats.values() {
5318 sum += stat.size;
5319 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005320 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005321 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5322
5323 Ok(())
5324 }
5325
5326 #[test]
5327 fn test_verify_auth_table_size_reporting() -> Result<()> {
5328 let mut db = new_test_db()?;
5329 let mut working_stats = get_storage_stats_map(&mut db);
5330 db.insert_auth_token(&HardwareAuthToken {
5331 challenge: 123,
5332 userId: 456,
5333 authenticatorId: 789,
5334 authenticatorType: kmhw_authenticator_type::ANY,
5335 timestamp: Timestamp { milliSeconds: 10 },
5336 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005337 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005338 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005339 Ok(())
5340 }
5341
5342 #[test]
5343 fn test_verify_grant_table_size_reporting() -> Result<()> {
5344 const OWNER: i64 = 1;
5345 let mut db = new_test_db()?;
5346 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5347
5348 let mut working_stats = get_storage_stats_map(&mut db);
5349 db.grant(
5350 &KeyDescriptor {
5351 domain: Domain::APP,
5352 nspace: 0,
5353 alias: Some(TEST_ALIAS.to_string()),
5354 blob: None,
5355 },
5356 OWNER as u32,
5357 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005358 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005359 |_, _| Ok(()),
5360 )?;
5361
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005362 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005363
5364 Ok(())
5365 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005366
5367 #[test]
5368 fn find_auth_token_entry_returns_latest() -> Result<()> {
5369 let mut db = new_test_db()?;
5370 db.insert_auth_token(&HardwareAuthToken {
5371 challenge: 123,
5372 userId: 456,
5373 authenticatorId: 789,
5374 authenticatorType: kmhw_authenticator_type::ANY,
5375 timestamp: Timestamp { milliSeconds: 10 },
5376 mac: b"mac0".to_vec(),
5377 });
5378 std::thread::sleep(std::time::Duration::from_millis(1));
5379 db.insert_auth_token(&HardwareAuthToken {
5380 challenge: 123,
5381 userId: 457,
5382 authenticatorId: 789,
5383 authenticatorType: kmhw_authenticator_type::ANY,
5384 timestamp: Timestamp { milliSeconds: 12 },
5385 mac: b"mac1".to_vec(),
5386 });
5387 std::thread::sleep(std::time::Duration::from_millis(1));
5388 db.insert_auth_token(&HardwareAuthToken {
5389 challenge: 123,
5390 userId: 458,
5391 authenticatorId: 789,
5392 authenticatorType: kmhw_authenticator_type::ANY,
5393 timestamp: Timestamp { milliSeconds: 3 },
5394 mac: b"mac2".to_vec(),
5395 });
5396 // All three entries are in the database
5397 assert_eq!(db.perboot.auth_tokens_len(), 3);
5398 // It selected the most recent timestamp
5399 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5400 Ok(())
5401 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005402
5403 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005404 fn test_load_key_descriptor() -> Result<()> {
5405 let mut db = new_test_db()?;
5406 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5407
5408 let key = db.load_key_descriptor(key_id)?.unwrap();
5409
5410 assert_eq!(key.domain, Domain::APP);
5411 assert_eq!(key.nspace, 1);
5412 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5413
5414 // No such id
5415 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5416 Ok(())
5417 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005418}