blob: 7b90fd508d0ed9030c46c83e24d2793ad17cdb22 [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;
Hasini Gunasinghe1a8524b2022-05-10 08:49:53 +000049use crate::globals::get_keymint_dev_by_uuid;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080050use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080051use crate::key_parameter::{KeyParameter, Tag};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000052use crate::ks_err;
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000053use crate::metrics_store::log_rkp_error_stats;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070054use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000055use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080056use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070057 error::{Error as KsError, ErrorCode, ResponseCode},
58 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080059};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080060use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080061use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis030ba022021-05-26 11:15:30 -070062use utils as db_utils;
63use utils::SqlField;
Janis Danisevskis60400fe2020-08-26 15:24:42 -070064
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000065use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Tri Voa1634bb2022-12-01 15:54:19 -080066 HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
67 SecurityLevel::SecurityLevel,
68};
69use android_security_metrics::aidl::android::security::metrics::{
70 RkpError::RkpError as MetricsRkpError, Storage::Storage as MetricsStorage,
71 StorageStats::StorageStats,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080072};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070073use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070074 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070075};
Max Bires2b2e6562020-09-22 11:22:36 -070076
77use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080078use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000079use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070080#[cfg(not(test))]
81use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070082use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070083 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080084 types::FromSql,
85 types::FromSqlResult,
86 types::ToSqlOutput,
87 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080088 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070089};
Max Bires2b2e6562020-09-22 11:22:36 -070090
Janis Danisevskisaec14592020-11-12 09:41:49 -080091use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080093 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070094 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080095 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080096};
Max Bires2b2e6562020-09-22 11:22:36 -070097
Joel Galenson0891bc12020-07-20 10:37:03 -070098#[cfg(test)]
99use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -0700100
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800101impl_metadata!(
102 /// A set of metadata for key entries.
103 #[derive(Debug, Default, Eq, PartialEq)]
104 pub struct KeyMetaData;
105 /// A metadata entry for key entries.
106 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
107 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800108 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800109 CreationDate(DateTime) with accessor creation_date,
110 /// Expiration date for attestation keys.
111 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700112 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
113 /// provisioning
114 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
115 /// Vector representing the raw public key so results from the server can be matched
116 /// to the right entry
117 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700118 /// SEC1 public key for ECDH encryption
119 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800120 // --- ADD NEW META DATA FIELDS HERE ---
121 // For backwards compatibility add new entries only to
122 // end of this list and above this comment.
123 };
124);
125
126impl KeyMetaData {
127 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
128 let mut stmt = tx
129 .prepare(
130 "SELECT tag, data from persistent.keymetadata
131 WHERE keyentryid = ?;",
132 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000133 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800134
135 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
136
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000137 let mut rows = stmt
138 .query(params![key_id])
139 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800140 db_utils::with_rows_extract_all(&mut rows, |row| {
141 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
142 metadata.insert(
143 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700144 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800145 .context("Failed to read KeyMetaEntry.")?,
146 );
147 Ok(())
148 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000149 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800150
151 Ok(Self { data: metadata })
152 }
153
154 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
155 let mut stmt = tx
156 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000157 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800158 VALUES (?, ?, ?);",
159 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000160 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800161
162 let iter = self.data.iter();
163 for (tag, entry) in iter {
164 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000165 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800166 })?;
167 }
168 Ok(())
169 }
170}
171
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800172impl_metadata!(
173 /// A set of metadata for key blobs.
174 #[derive(Debug, Default, Eq, PartialEq)]
175 pub struct BlobMetaData;
176 /// A metadata entry for key blobs.
177 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
178 pub enum BlobMetaEntry {
179 /// If present, indicates that the blob is encrypted with another key or a key derived
180 /// from a password.
181 EncryptedBy(EncryptedBy) with accessor encrypted_by,
182 /// If the blob is password encrypted this field is set to the
183 /// salt used for the key derivation.
184 Salt(Vec<u8>) with accessor salt,
185 /// If the blob is encrypted, this field is set to the initialization vector.
186 Iv(Vec<u8>) with accessor iv,
187 /// If the blob is encrypted, this field holds the AEAD TAG.
188 AeadTag(Vec<u8>) with accessor aead_tag,
189 /// The uuid of the owning KeyMint instance.
190 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700191 /// If the key is ECDH encrypted, this is the ephemeral public key
192 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000193 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
194 /// of that key
195 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800196 // --- ADD NEW META DATA FIELDS HERE ---
197 // For backwards compatibility add new entries only to
198 // end of this list and above this comment.
199 };
200);
201
202impl BlobMetaData {
203 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
204 let mut stmt = tx
205 .prepare(
206 "SELECT tag, data from persistent.blobmetadata
207 WHERE blobentryid = ?;",
208 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000209 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800210
211 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
212
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000213 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800214 db_utils::with_rows_extract_all(&mut rows, |row| {
215 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
216 metadata.insert(
217 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700218 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800219 .context("Failed to read BlobMetaEntry.")?,
220 );
221 Ok(())
222 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000223 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800224
225 Ok(Self { data: metadata })
226 }
227
228 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
229 let mut stmt = tx
230 .prepare(
231 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
232 VALUES (?, ?, ?);",
233 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000234 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800235
236 let iter = self.data.iter();
237 for (tag, entry) in iter {
238 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000239 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800240 })?;
241 }
242 Ok(())
243 }
244}
245
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800246/// Indicates the type of the keyentry.
247#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
248pub enum KeyType {
249 /// This is a client key type. These keys are created or imported through the Keystore 2.0
250 /// AIDL interface android.system.keystore2.
251 Client,
252 /// This is a super key type. These keys are created by keystore itself and used to encrypt
253 /// other key blobs to provide LSKF binding.
254 Super,
255 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
256 Attestation,
257}
258
259impl ToSql for KeyType {
260 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
261 Ok(ToSqlOutput::Owned(Value::Integer(match self {
262 KeyType::Client => 0,
263 KeyType::Super => 1,
264 KeyType::Attestation => 2,
265 })))
266 }
267}
268
269impl FromSql for KeyType {
270 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
271 match i64::column_result(value)? {
272 0 => Ok(KeyType::Client),
273 1 => Ok(KeyType::Super),
274 2 => Ok(KeyType::Attestation),
275 v => Err(FromSqlError::OutOfRange(v)),
276 }
277 }
278}
279
Max Bires8e93d2b2021-01-14 13:17:59 -0800280/// Uuid representation that can be stored in the database.
281/// Right now it can only be initialized from SecurityLevel.
282/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
284pub struct Uuid([u8; 16]);
285
286impl Deref for Uuid {
287 type Target = [u8; 16];
288
289 fn deref(&self) -> &Self::Target {
290 &self.0
291 }
292}
293
294impl From<SecurityLevel> for Uuid {
295 fn from(sec_level: SecurityLevel) -> Self {
296 Self((sec_level.0 as u128).to_be_bytes())
297 }
298}
299
300impl ToSql for Uuid {
301 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
302 self.0.to_sql()
303 }
304}
305
306impl FromSql for Uuid {
307 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
308 let blob = Vec::<u8>::column_result(value)?;
309 if blob.len() != 16 {
310 return Err(FromSqlError::OutOfRange(blob.len() as i64));
311 }
312 let mut arr = [0u8; 16];
313 arr.copy_from_slice(&blob);
314 Ok(Self(arr))
315 }
316}
317
318/// Key entries that are not associated with any KeyMint instance, such as pure certificate
319/// entries are associated with this UUID.
320pub static KEYSTORE_UUID: Uuid = Uuid([
321 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
322]);
323
Seth Moore056106f2022-07-07 09:53:51 -0700324static EXPIRATION_BUFFER_MS: i64 = 12 * 60 * 60 * 1000;
Max Birescd7f7412022-02-11 13:47:36 -0800325
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800326/// Indicates how the sensitive part of this key blob is encrypted.
327#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
328pub enum EncryptedBy {
329 /// The keyblob is encrypted by a user password.
330 /// In the database this variant is represented as NULL.
331 Password,
332 /// The keyblob is encrypted by another key with wrapped key id.
333 /// In the database this variant is represented as non NULL value
334 /// that is convertible to i64, typically NUMERIC.
335 KeyId(i64),
336}
337
338impl ToSql for EncryptedBy {
339 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
340 match self {
341 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
342 Self::KeyId(id) => id.to_sql(),
343 }
344 }
345}
346
347impl FromSql for EncryptedBy {
348 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
349 match value {
350 ValueRef::Null => Ok(Self::Password),
351 _ => Ok(Self::KeyId(i64::column_result(value)?)),
352 }
353 }
354}
355
356/// A database representation of wall clock time. DateTime stores unix epoch time as
357/// i64 in milliseconds.
358#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
359pub struct DateTime(i64);
360
361/// Error type returned when creating DateTime or converting it from and to
362/// SystemTime.
363#[derive(thiserror::Error, Debug)]
364pub enum DateTimeError {
365 /// This is returned when SystemTime and Duration computations fail.
366 #[error(transparent)]
367 SystemTimeError(#[from] SystemTimeError),
368
369 /// This is returned when type conversions fail.
370 #[error(transparent)]
371 TypeConversion(#[from] std::num::TryFromIntError),
372
373 /// This is returned when checked time arithmetic failed.
374 #[error("Time arithmetic failed.")]
375 TimeArithmetic,
376}
377
378impl DateTime {
379 /// Constructs a new DateTime object denoting the current time. This may fail during
380 /// conversion to unix epoch time and during conversion to the internal i64 representation.
381 pub fn now() -> Result<Self, DateTimeError> {
382 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
383 }
384
385 /// Constructs a new DateTime object from milliseconds.
386 pub fn from_millis_epoch(millis: i64) -> Self {
387 Self(millis)
388 }
389
390 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700391 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800392 self.0
393 }
394
395 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700396 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800397 self.0 / 1000
398 }
399}
400
401impl ToSql for DateTime {
402 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
403 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
404 }
405}
406
407impl FromSql for DateTime {
408 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
409 Ok(Self(i64::column_result(value)?))
410 }
411}
412
413impl TryInto<SystemTime> for DateTime {
414 type Error = DateTimeError;
415
416 fn try_into(self) -> Result<SystemTime, Self::Error> {
417 // We want to construct a SystemTime representation equivalent to self, denoting
418 // a point in time THEN, but we cannot set the time directly. We can only construct
419 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
420 // and between EPOCH and THEN. With this common reference we can construct the
421 // duration between NOW and THEN which we can add to our SystemTime representation
422 // of NOW to get a SystemTime representation of THEN.
423 // Durations can only be positive, thus the if statement below.
424 let now = SystemTime::now();
425 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
426 let then_epoch = Duration::from_millis(self.0.try_into()?);
427 Ok(if now_epoch > then_epoch {
428 // then = now - (now_epoch - then_epoch)
429 now_epoch
430 .checked_sub(then_epoch)
431 .and_then(|d| now.checked_sub(d))
432 .ok_or(DateTimeError::TimeArithmetic)?
433 } else {
434 // then = now + (then_epoch - now_epoch)
435 then_epoch
436 .checked_sub(now_epoch)
437 .and_then(|d| now.checked_add(d))
438 .ok_or(DateTimeError::TimeArithmetic)?
439 })
440 }
441}
442
443impl TryFrom<SystemTime> for DateTime {
444 type Error = DateTimeError;
445
446 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
447 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
448 }
449}
450
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800451#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
452enum KeyLifeCycle {
453 /// Existing keys have a key ID but are not fully populated yet.
454 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
455 /// them to Unreferenced for garbage collection.
456 Existing,
457 /// A live key is fully populated and usable by clients.
458 Live,
459 /// An unreferenced key is scheduled for garbage collection.
460 Unreferenced,
461}
462
463impl ToSql for KeyLifeCycle {
464 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
465 match self {
466 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
467 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
468 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
469 }
470 }
471}
472
473impl FromSql for KeyLifeCycle {
474 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
475 match i64::column_result(value)? {
476 0 => Ok(KeyLifeCycle::Existing),
477 1 => Ok(KeyLifeCycle::Live),
478 2 => Ok(KeyLifeCycle::Unreferenced),
479 v => Err(FromSqlError::OutOfRange(v)),
480 }
481 }
482}
483
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700484/// Keys have a KeyMint blob component and optional public certificate and
485/// certificate chain components.
486/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
487/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800488#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700489pub struct KeyEntryLoadBits(u32);
490
491impl KeyEntryLoadBits {
492 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
493 pub const NONE: KeyEntryLoadBits = Self(0);
494 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
495 pub const KM: KeyEntryLoadBits = Self(1);
496 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
497 pub const PUBLIC: KeyEntryLoadBits = Self(2);
498 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
499 pub const BOTH: KeyEntryLoadBits = Self(3);
500
501 /// Returns true if this object indicates that the public components shall be loaded.
502 pub const fn load_public(&self) -> bool {
503 self.0 & Self::PUBLIC.0 != 0
504 }
505
506 /// Returns true if the object indicates that the KeyMint component shall be loaded.
507 pub const fn load_km(&self) -> bool {
508 self.0 & Self::KM.0 != 0
509 }
510}
511
Janis Danisevskisaec14592020-11-12 09:41:49 -0800512lazy_static! {
513 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
514}
515
516struct KeyIdLockDb {
517 locked_keys: Mutex<HashSet<i64>>,
518 cond_var: Condvar,
519}
520
521/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
522/// from the database a second time. Most functions manipulating the key blob database
523/// require a KeyIdGuard.
524#[derive(Debug)]
525pub struct KeyIdGuard(i64);
526
527impl KeyIdLockDb {
528 fn new() -> Self {
529 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
530 }
531
532 /// This function blocks until an exclusive lock for the given key entry id can
533 /// be acquired. It returns a guard object, that represents the lifecycle of the
534 /// acquired lock.
535 pub fn get(&self, key_id: i64) -> KeyIdGuard {
536 let mut locked_keys = self.locked_keys.lock().unwrap();
537 while locked_keys.contains(&key_id) {
538 locked_keys = self.cond_var.wait(locked_keys).unwrap();
539 }
540 locked_keys.insert(key_id);
541 KeyIdGuard(key_id)
542 }
543
544 /// This function attempts to acquire an exclusive lock on a given key id. If the
545 /// given key id is already taken the function returns None immediately. If a lock
546 /// can be acquired this function returns a guard object, that represents the
547 /// lifecycle of the acquired lock.
548 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
549 let mut locked_keys = self.locked_keys.lock().unwrap();
550 if locked_keys.insert(key_id) {
551 Some(KeyIdGuard(key_id))
552 } else {
553 None
554 }
555 }
556}
557
558impl KeyIdGuard {
559 /// Get the numeric key id of the locked key.
560 pub fn id(&self) -> i64 {
561 self.0
562 }
563}
564
565impl Drop for KeyIdGuard {
566 fn drop(&mut self) {
567 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
568 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800569 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800570 KEY_ID_LOCK.cond_var.notify_all();
571 }
572}
573
Max Bires8e93d2b2021-01-14 13:17:59 -0800574/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700575#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800576pub struct CertificateInfo {
577 cert: Option<Vec<u8>>,
578 cert_chain: Option<Vec<u8>>,
579}
580
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800581/// This type represents a Blob with its metadata and an optional superseded blob.
582#[derive(Debug)]
583pub struct BlobInfo<'a> {
584 blob: &'a [u8],
585 metadata: &'a BlobMetaData,
586 /// Superseded blobs are an artifact of legacy import. In some rare occasions
587 /// the key blob needs to be upgraded during import. In that case two
588 /// blob are imported, the superseded one will have to be imported first,
589 /// so that the garbage collector can reap it.
590 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
591}
592
593impl<'a> BlobInfo<'a> {
594 /// Create a new instance of blob info with blob and corresponding metadata
595 /// and no superseded blob info.
596 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
597 Self { blob, metadata, superseded_blob: None }
598 }
599
600 /// Create a new instance of blob info with blob and corresponding metadata
601 /// as well as superseded blob info.
602 pub fn new_with_superseded(
603 blob: &'a [u8],
604 metadata: &'a BlobMetaData,
605 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
606 ) -> Self {
607 Self { blob, metadata, superseded_blob }
608 }
609}
610
Max Bires8e93d2b2021-01-14 13:17:59 -0800611impl CertificateInfo {
612 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
613 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
614 Self { cert, cert_chain }
615 }
616
617 /// Take the cert
618 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
619 self.cert.take()
620 }
621
622 /// Take the cert chain
623 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
624 self.cert_chain.take()
625 }
626}
627
Max Bires2b2e6562020-09-22 11:22:36 -0700628/// This type represents a certificate chain with a private key corresponding to the leaf
629/// 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 -0700630pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800631 /// A KM key blob
632 pub private_key: ZVec,
633 /// A batch cert for private_key
634 pub batch_cert: Vec<u8>,
635 /// A full certificate chain from root signing authority to private_key, including batch_cert
636 /// for convenience.
637 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700638}
639
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700640/// This type represents a Keystore 2.0 key entry.
641/// An entry has a unique `id` by which it can be found in the database.
642/// It has a security level field, key parameters, and three optional fields
643/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800644#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700645pub struct KeyEntry {
646 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800647 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700648 cert: Option<Vec<u8>>,
649 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800650 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700651 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800652 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800653 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700654}
655
656impl KeyEntry {
657 /// Returns the unique id of the Key entry.
658 pub fn id(&self) -> i64 {
659 self.id
660 }
661 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800662 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
663 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700664 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800665 /// Extracts the Optional KeyMint blob including its metadata.
666 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
667 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700668 }
669 /// Exposes the optional public certificate.
670 pub fn cert(&self) -> &Option<Vec<u8>> {
671 &self.cert
672 }
673 /// Extracts the optional public certificate.
674 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
675 self.cert.take()
676 }
677 /// Exposes the optional public certificate chain.
678 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
679 &self.cert_chain
680 }
681 /// Extracts the optional public certificate_chain.
682 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
683 self.cert_chain.take()
684 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800685 /// Returns the uuid of the owning KeyMint instance.
686 pub fn km_uuid(&self) -> &Uuid {
687 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700688 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700689 /// Exposes the key parameters of this key entry.
690 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
691 &self.parameters
692 }
693 /// Consumes this key entry and extracts the keyparameters from it.
694 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
695 self.parameters
696 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800697 /// Exposes the key metadata of this key entry.
698 pub fn metadata(&self) -> &KeyMetaData {
699 &self.metadata
700 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800701 /// This returns true if the entry is a pure certificate entry with no
702 /// private key component.
703 pub fn pure_cert(&self) -> bool {
704 self.pure_cert
705 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000706 /// Consumes this key entry and extracts the keyparameters and metadata from it.
707 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
708 (self.parameters, self.metadata)
709 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700710}
711
712/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800713#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700714pub struct SubComponentType(u32);
715impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800716 /// Persistent identifier for a key blob.
717 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700718 /// Persistent identifier for a certificate blob.
719 pub const CERT: SubComponentType = Self(1);
720 /// Persistent identifier for a certificate chain blob.
721 pub const CERT_CHAIN: SubComponentType = Self(2);
722}
723
724impl ToSql for SubComponentType {
725 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
726 self.0.to_sql()
727 }
728}
729
730impl FromSql for SubComponentType {
731 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
732 Ok(Self(u32::column_result(value)?))
733 }
734}
735
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800736/// This trait is private to the database module. It is used to convey whether or not the garbage
737/// collector shall be invoked after a database access. All closures passed to
738/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
739/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
740/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
741/// `.need_gc()`.
742trait DoGc<T> {
743 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
744
745 fn no_gc(self) -> Result<(bool, T)>;
746
747 fn need_gc(self) -> Result<(bool, T)>;
748}
749
750impl<T> DoGc<T> for Result<T> {
751 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
752 self.map(|r| (need_gc, r))
753 }
754
755 fn no_gc(self) -> Result<(bool, T)> {
756 self.do_gc(false)
757 }
758
759 fn need_gc(self) -> Result<(bool, T)> {
760 self.do_gc(true)
761 }
762}
763
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700764/// KeystoreDB wraps a connection to an SQLite database and tracks its
765/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700766pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700767 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700768 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700769 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700770}
771
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000772/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000773/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000774#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
775pub struct MonotonicRawTime(i64);
776
777impl MonotonicRawTime {
778 /// Constructs a new MonotonicRawTime
779 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000780 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000781 }
782
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000783 /// Returns the value of MonotonicRawTime in milliseconds as i64
784 pub fn milliseconds(&self) -> i64 {
785 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000786 }
787
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 /// Returns the integer value of MonotonicRawTime as i64
789 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000790 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000791 }
792
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800793 /// Like i64::checked_sub.
794 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
795 self.0.checked_sub(other.0).map(Self)
796 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000797}
798
799impl ToSql for MonotonicRawTime {
800 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
801 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
802 }
803}
804
805impl FromSql for MonotonicRawTime {
806 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
807 Ok(Self(i64::column_result(value)?))
808 }
809}
810
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000811/// This struct encapsulates the information to be stored in the database about the auth tokens
812/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700813#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000814pub struct AuthTokenEntry {
815 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000816 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000817 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818}
819
820impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000821 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822 AuthTokenEntry { auth_token, time_received }
823 }
824
825 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800826 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000827 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800828 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000829 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000830 })
831 }
832
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000833 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800834 pub fn auth_token(&self) -> &HardwareAuthToken {
835 &self.auth_token
836 }
837
838 /// Returns the auth token wrapped by the AuthTokenEntry
839 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000840 self.auth_token
841 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800842
843 /// Returns the time that this auth token was received.
844 pub fn time_received(&self) -> MonotonicRawTime {
845 self.time_received
846 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000847
848 /// Returns the challenge value of the auth token.
849 pub fn challenge(&self) -> i64 {
850 self.auth_token.challenge
851 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000852}
853
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
855/// This object does not allow access to the database connection. But it keeps a database
856/// connection alive in order to keep the in memory per boot database alive.
857pub struct PerBootDbKeepAlive(Connection);
858
Joel Galenson26f4d012020-07-17 14:57:21 -0700859impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800860 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700861 const CURRENT_DB_VERSION: u32 = 1;
862 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800863
Seth Moore78c091f2021-04-09 21:38:30 +0000864 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700865 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000866
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700867 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800868 /// files persistent.sqlite and perboot.sqlite in the given directory.
869 /// It also attempts to initialize all of the tables.
870 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700871 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700872 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700873 let _wp = wd::watch_millis("KeystoreDB::new", 500);
874
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700875 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700876 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800877
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700878 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800879 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700880 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000881 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800882 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800883 })?;
884 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700885 }
886
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700887 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
888 // cryptographic binding to the boot level keys was implemented.
889 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
890 tx.execute(
891 "UPDATE persistent.keyentry SET state = ?
892 WHERE
893 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
894 AND
895 id NOT IN (
896 SELECT keyentryid FROM persistent.blobentry
897 WHERE id IN (
898 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
899 )
900 );",
901 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
902 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000903 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700904 Ok(1)
905 }
906
Janis Danisevskis66784c42021-01-27 08:40:25 -0800907 fn init_tables(tx: &Transaction) -> Result<()> {
908 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700910 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800911 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700912 domain INTEGER,
913 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800914 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800915 state INTEGER,
916 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700917 NO_PARAMS,
918 )
919 .context("Failed to initialize \"keyentry\" table.")?;
920
Janis Danisevskis66784c42021-01-27 08:40:25 -0800921 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800922 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
923 ON keyentry(id);",
924 NO_PARAMS,
925 )
926 .context("Failed to create index keyentry_id_index.")?;
927
928 tx.execute(
929 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
930 ON keyentry(domain, namespace, alias);",
931 NO_PARAMS,
932 )
933 .context("Failed to create index keyentry_domain_namespace_index.")?;
934
935 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700936 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
937 id INTEGER PRIMARY KEY,
938 subcomponent_type INTEGER,
939 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800940 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700941 NO_PARAMS,
942 )
943 .context("Failed to initialize \"blobentry\" table.")?;
944
Janis Danisevskis66784c42021-01-27 08:40:25 -0800945 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800946 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
947 ON blobentry(keyentryid);",
948 NO_PARAMS,
949 )
950 .context("Failed to create index blobentry_keyentryid_index.")?;
951
952 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800953 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
954 id INTEGER PRIMARY KEY,
955 blobentryid INTEGER,
956 tag INTEGER,
957 data ANY,
958 UNIQUE (blobentryid, tag));",
959 NO_PARAMS,
960 )
961 .context("Failed to initialize \"blobmetadata\" table.")?;
962
963 tx.execute(
964 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
965 ON blobmetadata(blobentryid);",
966 NO_PARAMS,
967 )
968 .context("Failed to create index blobmetadata_blobentryid_index.")?;
969
970 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700971 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000972 keyentryid INTEGER,
973 tag INTEGER,
974 data ANY,
975 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700976 NO_PARAMS,
977 )
978 .context("Failed to initialize \"keyparameter\" table.")?;
979
Janis Danisevskis66784c42021-01-27 08:40:25 -0800980 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800981 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
982 ON keyparameter(keyentryid);",
983 NO_PARAMS,
984 )
985 .context("Failed to create index keyparameter_keyentryid_index.")?;
986
987 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800988 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
989 keyentryid INTEGER,
990 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000991 data ANY,
992 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800993 NO_PARAMS,
994 )
995 .context("Failed to initialize \"keymetadata\" table.")?;
996
Janis Danisevskis66784c42021-01-27 08:40:25 -0800997 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800998 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
999 ON keymetadata(keyentryid);",
1000 NO_PARAMS,
1001 )
1002 .context("Failed to create index keymetadata_keyentryid_index.")?;
1003
1004 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001005 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001006 id INTEGER UNIQUE,
1007 grantee INTEGER,
1008 keyentryid INTEGER,
1009 access_vector INTEGER);",
1010 NO_PARAMS,
1011 )
1012 .context("Failed to initialize \"grant\" table.")?;
1013
Joel Galenson0891bc12020-07-20 10:37:03 -07001014 Ok(())
1015 }
1016
Seth Moore472fcbb2021-05-12 10:07:51 -07001017 fn make_persistent_path(db_root: &Path) -> Result<String> {
1018 // Build the path to the sqlite file.
1019 let mut persistent_path = db_root.to_path_buf();
1020 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1021
1022 // Now convert them to strings prefixed with "file:"
1023 let mut persistent_path_str = "file:".to_owned();
1024 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1025
1026 Ok(persistent_path_str)
1027 }
1028
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001029 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001030 let conn =
1031 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1032
Janis Danisevskis66784c42021-01-27 08:40:25 -08001033 loop {
1034 if let Err(e) = conn
1035 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1036 .context("Failed to attach database persistent.")
1037 {
1038 if Self::is_locked_error(&e) {
1039 std::thread::sleep(std::time::Duration::from_micros(500));
1040 continue;
1041 } else {
1042 return Err(e);
1043 }
1044 }
1045 break;
1046 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047
Matthew Maurer4fb19112021-05-06 15:40:44 -07001048 // Drop the cache size from default (2M) to 0.5M
1049 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1050 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001051
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001052 Ok(conn)
1053 }
1054
Seth Moore78c091f2021-04-09 21:38:30 +00001055 fn do_table_size_query(
1056 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001057 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001058 query: &str,
1059 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001060 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001061 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001062 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001063 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001064 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001065 })
1066 .no_gc()
1067 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001068 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001069 }
1070
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001071 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001072 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001073 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001074 "SELECT page_count * page_size, freelist_count * page_size
1075 FROM pragma_page_count('persistent'),
1076 pragma_page_size('persistent'),
1077 persistent.pragma_freelist_count();",
1078 &[],
1079 )
1080 }
1081
1082 fn get_table_size(
1083 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001084 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001085 schema: &str,
1086 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001087 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001088 self.do_table_size_query(
1089 storage_type,
1090 "SELECT pgsize,unused FROM dbstat(?1)
1091 WHERE name=?2 AND aggregate=TRUE;",
1092 &[schema, table],
1093 )
1094 }
1095
1096 /// Fetches a storage statisitics atom for a given storage type. For storage
1097 /// types that map to a table, information about the table's storage is
1098 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001099 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001100 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1101
Seth Moore78c091f2021-04-09 21:38:30 +00001102 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001103 MetricsStorage::DATABASE => self.get_total_size(),
1104 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001105 self.get_table_size(storage_type, "persistent", "keyentry")
1106 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001108 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1109 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001110 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001111 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1112 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001113 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001114 self.get_table_size(storage_type, "persistent", "blobentry")
1115 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001116 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001120 self.get_table_size(storage_type, "persistent", "keyparameter")
1121 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001122 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001123 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1124 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001125 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001126 self.get_table_size(storage_type, "persistent", "keymetadata")
1127 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001128 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001129 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1130 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001131 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1132 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001133 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1134 // reportable
1135 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001136 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001137 storage_type,
1138 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001140 unused_size: 0,
1141 })
Seth Moore78c091f2021-04-09 21:38:30 +00001142 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001143 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001144 self.get_table_size(storage_type, "persistent", "blobmetadata")
1145 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001146 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001147 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1148 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001149 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001150 }
1151 }
1152
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1155 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001156 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1157 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001158 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001159 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001160 blob_ids_to_delete: &[i64],
1161 max_blobs: usize,
1162 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001163 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001164 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 // Delete the given blobs.
1166 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167 tx.execute(
1168 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001169 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001170 )
1171 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1173 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001174 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001175
1176 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1177
Janis Danisevskis3395f862021-05-06 10:54:17 -07001178 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1179 let result: Vec<(i64, Vec<u8>)> = {
1180 let mut stmt = tx
1181 .prepare(
1182 "SELECT id, blob FROM persistent.blobentry
1183 WHERE subcomponent_type = ?
1184 AND (
1185 id NOT IN (
1186 SELECT MAX(id) FROM persistent.blobentry
1187 WHERE subcomponent_type = ?
1188 GROUP BY keyentryid, subcomponent_type
1189 )
1190 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1191 ) LIMIT ?;",
1192 )
1193 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001194
Janis Danisevskis3395f862021-05-06 10:54:17 -07001195 let rows = stmt
1196 .query_map(
1197 params![
1198 SubComponentType::KEY_BLOB,
1199 SubComponentType::KEY_BLOB,
1200 max_blobs as i64,
1201 ],
1202 |row| Ok((row.get(0)?, row.get(1)?)),
1203 )
1204 .context("Trying to query superseded blob.")?;
1205
1206 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1207 .context("Trying to extract superseded blobs.")?
1208 };
1209
1210 let result = result
1211 .into_iter()
1212 .map(|(blob_id, blob)| {
1213 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1214 })
1215 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1216 .context("Trying to load blob metadata.")?;
1217 if !result.is_empty() {
1218 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001219 }
1220
1221 // We did not find any superseded key blob, so let's remove other superseded blob in
1222 // one transaction.
1223 tx.execute(
1224 "DELETE FROM persistent.blobentry
1225 WHERE NOT subcomponent_type = ?
1226 AND (
1227 id NOT IN (
1228 SELECT MAX(id) FROM persistent.blobentry
1229 WHERE NOT subcomponent_type = ?
1230 GROUP BY keyentryid, subcomponent_type
1231 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1232 );",
1233 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1234 )
1235 .context("Trying to purge superseded blobs.")?;
1236
Janis Danisevskis3395f862021-05-06 10:54:17 -07001237 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001238 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001239 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001240 }
1241
1242 /// This maintenance function should be called only once before the database is used for the
1243 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1244 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1245 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1246 /// Keystore crashed at some point during key generation. Callers may want to log such
1247 /// occurrences.
1248 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1249 /// it to `KeyLifeCycle::Live` may have grants.
1250 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001251 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1252
Janis Danisevskis66784c42021-01-27 08:40:25 -08001253 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1254 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001255 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1256 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1257 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001258 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001259 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001260 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001261 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001262 }
1263
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001264 /// Checks if a key exists with given key type and key descriptor properties.
1265 pub fn key_exists(
1266 &mut self,
1267 domain: Domain,
1268 nspace: i64,
1269 alias: &str,
1270 key_type: KeyType,
1271 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001272 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1273
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001274 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1275 let key_descriptor =
1276 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001277 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001278 match result {
1279 Ok(_) => Ok(true),
1280 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1281 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001282 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001283 },
1284 }
1285 .no_gc()
1286 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001287 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001288 }
1289
Hasini Gunasingheda895552021-01-27 19:34:37 +00001290 /// Stores a super key in the database.
1291 pub fn store_super_key(
1292 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001293 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001294 key_type: &SuperKeyType,
1295 blob: &[u8],
1296 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001297 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001299 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1300
Hasini Gunasingheda895552021-01-27 19:34:37 +00001301 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1302 let key_id = Self::insert_with_retry(|id| {
1303 tx.execute(
1304 "INSERT into persistent.keyentry
1305 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001306 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001307 params![
1308 id,
1309 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001310 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001311 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001312 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 KeyLifeCycle::Live,
1314 &KEYSTORE_UUID,
1315 ],
1316 )
1317 })
1318 .context("Failed to insert into keyentry table.")?;
1319
Paul Crowley8d5b2532021-03-19 10:53:07 -07001320 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1321
Hasini Gunasingheda895552021-01-27 19:34:37 +00001322 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001323 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001324 key_id,
1325 SubComponentType::KEY_BLOB,
1326 Some(blob),
1327 Some(blob_metadata),
1328 )
1329 .context("Failed to store key blob.")?;
1330
1331 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1332 .context("Trying to load key components.")
1333 .no_gc()
1334 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001335 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001336 }
1337
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001338 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001339 pub fn load_super_key(
1340 &mut self,
1341 key_type: &SuperKeyType,
1342 user_id: u32,
1343 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001344 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1345
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001346 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1347 let key_descriptor = KeyDescriptor {
1348 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001349 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001350 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001351 blob: None,
1352 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001353 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001354 match id {
1355 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001356 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001357 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001358 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1359 }
1360 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1361 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001362 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001363 },
1364 }
1365 .no_gc()
1366 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001367 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001368 }
1369
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001370 /// Atomically loads a key entry and associated metadata or creates it using the
1371 /// callback create_new_key callback. The callback is called during a database
1372 /// transaction. This means that implementers should be mindful about using
1373 /// blocking operations such as IPC or grabbing mutexes.
1374 pub fn get_or_create_key_with<F>(
1375 &mut self,
1376 domain: Domain,
1377 namespace: i64,
1378 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001379 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001380 create_new_key: F,
1381 ) -> Result<(KeyIdGuard, KeyEntry)>
1382 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001383 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001384 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001385 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1386
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1388 let id = {
1389 let mut stmt = tx
1390 .prepare(
1391 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001392 WHERE
1393 key_type = ?
1394 AND domain = ?
1395 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001396 AND alias = ?
1397 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001399 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 let mut rows = stmt
1401 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001402 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 db_utils::with_rows_extract_one(&mut rows, |row| {
1405 Ok(match row {
1406 Some(r) => r.get(0).context("Failed to unpack id.")?,
1407 None => None,
1408 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001409 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001410 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001411 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001412
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 let (id, entry) = match id {
1414 Some(id) => (
1415 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001416 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001418
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 None => {
1420 let id = Self::insert_with_retry(|id| {
1421 tx.execute(
1422 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001423 (id, key_type, domain, namespace, alias, state, km_uuid)
1424 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001425 params![
1426 id,
1427 KeyType::Super,
1428 domain.0,
1429 namespace,
1430 alias,
1431 KeyLifeCycle::Live,
1432 km_uuid,
1433 ],
1434 )
1435 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001436 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001437
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001438 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001439 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001440 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001441 id,
1442 SubComponentType::KEY_BLOB,
1443 Some(&blob),
1444 Some(&metadata),
1445 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001446 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001447 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001448 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001449 KeyEntry {
1450 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001451 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001452 pure_cert: false,
1453 ..Default::default()
1454 },
1455 )
1456 }
1457 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001458 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001459 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001460 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001461 }
1462
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001463 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001464 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1465 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001466 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1467 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001468 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001469 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001470 loop {
1471 match self
1472 .conn
1473 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001474 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001475 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1476 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001477 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001478 Ok(result)
1479 }) {
1480 Ok(result) => break Ok(result),
1481 Err(e) => {
1482 if Self::is_locked_error(&e) {
1483 std::thread::sleep(std::time::Duration::from_micros(500));
1484 continue;
1485 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001486 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001487 }
1488 }
1489 }
1490 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001491 .map(|(need_gc, result)| {
1492 if need_gc {
1493 if let Some(ref gc) = self.gc {
1494 gc.notify_gc();
1495 }
1496 }
1497 result
1498 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001499 }
1500
1501 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001502 matches!(
1503 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1504 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1505 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1506 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001507 }
1508
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001509 /// Creates a new key entry and allocates a new randomized id for the new key.
1510 /// The key id gets associated with a domain and namespace but not with an alias.
1511 /// To complete key generation `rebind_alias` should be called after all of the
1512 /// key artifacts, i.e., blobs and parameters have been associated with the new
1513 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1514 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001515 pub fn create_key_entry(
1516 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001517 domain: &Domain,
1518 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001519 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001520 km_uuid: &Uuid,
1521 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001522 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1523
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001524 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001525 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001526 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001527 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 }
1529
1530 fn create_key_entry_internal(
1531 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001532 domain: &Domain,
1533 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001534 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001535 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001536 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001537 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001538 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001539 _ => {
1540 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001541 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001542 }
1543 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001544 Ok(KEY_ID_LOCK.get(
1545 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001546 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001547 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001548 (id, key_type, domain, namespace, alias, state, km_uuid)
1549 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001550 params![
1551 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001552 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001553 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001554 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001555 KeyLifeCycle::Existing,
1556 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001557 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001558 )
1559 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001560 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001561 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001562 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001563
Max Bires2b2e6562020-09-22 11:22:36 -07001564 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1565 /// The key id gets associated with a domain and namespace later but not with an alias. The
1566 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1567 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1568 /// a key.
1569 pub fn create_attestation_key_entry(
1570 &mut self,
1571 maced_public_key: &[u8],
1572 raw_public_key: &[u8],
1573 private_key: &[u8],
1574 km_uuid: &Uuid,
1575 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001576 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1577
Max Bires2b2e6562020-09-22 11:22:36 -07001578 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1579 let key_id = KEY_ID_LOCK.get(
1580 Self::insert_with_retry(|id| {
1581 tx.execute(
1582 "INSERT into persistent.keyentry
1583 (id, key_type, domain, namespace, alias, state, km_uuid)
1584 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1585 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1586 )
1587 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001588 .context(ks_err!())?,
Max Bires2b2e6562020-09-22 11:22:36 -07001589 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001590 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001591 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001592 key_id.0,
1593 SubComponentType::KEY_BLOB,
1594 Some(private_key),
1595 None,
1596 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001597 let mut metadata = KeyMetaData::new();
1598 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1599 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001600 metadata.store_in_db(key_id.0, tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001601 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001602 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001603 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001604 }
1605
Janis Danisevskis377d1002021-01-27 19:07:48 -08001606 /// Set a new blob and associates it with the given key id. Each blob
1607 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001608 /// Each key can have one of each sub component type associated. If more
1609 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001610 /// will get garbage collected.
1611 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1612 /// removed by setting blob to None.
1613 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001614 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001615 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001616 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001617 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001618 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001619 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001620 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1621
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001622 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001623 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001624 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001625 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001626 }
1627
Janis Danisevskiseed69842021-02-18 20:04:10 -08001628 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1629 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1630 /// We use this to insert key blobs into the database which can then be garbage collected
1631 /// lazily by the key garbage collector.
1632 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001633 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1634
Janis Danisevskiseed69842021-02-18 20:04:10 -08001635 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1636 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001637 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001638 Self::UNASSIGNED_KEY_ID,
1639 SubComponentType::KEY_BLOB,
1640 Some(blob),
1641 Some(blob_metadata),
1642 )
1643 .need_gc()
1644 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001645 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001646 }
1647
Janis Danisevskis377d1002021-01-27 19:07:48 -08001648 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001649 tx: &Transaction,
1650 key_id: i64,
1651 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001652 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001653 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001654 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001655 match (blob, sc_type) {
1656 (Some(blob), _) => {
1657 tx.execute(
1658 "INSERT INTO persistent.blobentry
1659 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1660 params![sc_type, key_id, blob],
1661 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001662 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001663 if let Some(blob_metadata) = blob_metadata {
1664 let blob_id = tx
1665 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1666 row.get(0)
1667 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001668 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001669 blob_metadata
1670 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001671 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001672 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001673 }
1674 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1675 tx.execute(
1676 "DELETE FROM persistent.blobentry
1677 WHERE subcomponent_type = ? AND keyentryid = ?;",
1678 params![sc_type, key_id],
1679 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001680 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001681 }
1682 (None, _) => {
1683 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001684 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001685 }
1686 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001687 Ok(())
1688 }
1689
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001690 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1691 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001692 #[cfg(test)]
1693 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001694 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001695 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001696 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001697 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001698 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001699
Janis Danisevskis66784c42021-01-27 08:40:25 -08001700 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001701 tx: &Transaction,
1702 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001703 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001704 ) -> Result<()> {
1705 let mut stmt = tx
1706 .prepare(
1707 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1708 VALUES (?, ?, ?, ?);",
1709 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001710 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001711
Janis Danisevskis66784c42021-01-27 08:40:25 -08001712 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001713 stmt.insert(params![
1714 key_id.0,
1715 p.get_tag().0,
1716 p.key_parameter_value(),
1717 p.security_level().0
1718 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001719 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001720 }
1721 Ok(())
1722 }
1723
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001724 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001725 #[cfg(test)]
1726 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001727 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001728 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001729 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001730 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001731 }
1732
Max Bires2b2e6562020-09-22 11:22:36 -07001733 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1734 /// on the public key.
1735 pub fn store_signed_attestation_certificate_chain(
1736 &mut self,
1737 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001738 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001739 cert_chain: &[u8],
1740 expiration_date: i64,
1741 km_uuid: &Uuid,
1742 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001743 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1744
Max Bires2b2e6562020-09-22 11:22:36 -07001745 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1746 let mut stmt = tx
1747 .prepare(
1748 "SELECT keyentryid
1749 FROM persistent.keymetadata
1750 WHERE tag = ? AND data = ? AND keyentryid IN
1751 (SELECT id
1752 FROM persistent.keyentry
1753 WHERE
1754 alias IS NULL AND
1755 domain IS NULL AND
1756 namespace IS NULL AND
1757 key_type = ? AND
1758 km_uuid = ?);",
1759 )
1760 .context("Failed to store attestation certificate chain.")?;
1761 let mut rows = stmt
1762 .query(params![
1763 KeyMetaData::AttestationRawPubKey,
1764 raw_public_key,
1765 KeyType::Attestation,
1766 km_uuid
1767 ])
1768 .context("Failed to fetch keyid")?;
1769 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1770 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1771 .get(0)
1772 .context("Failed to unpack id.")
1773 })
1774 .context("Failed to get key_id.")?;
1775 let num_updated = tx
1776 .execute(
1777 "UPDATE persistent.keyentry
1778 SET alias = ?
1779 WHERE id = ?;",
1780 params!["signed", key_id],
1781 )
1782 .context("Failed to update alias.")?;
1783 if num_updated != 1 {
1784 return Err(KsError::sys()).context("Alias not updated for the key.");
1785 }
1786 let mut metadata = KeyMetaData::new();
1787 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1788 expiration_date,
1789 )));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001790 metadata.store_in_db(key_id, tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001791 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001792 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001793 key_id,
1794 SubComponentType::CERT_CHAIN,
1795 Some(cert_chain),
1796 None,
1797 )
1798 .context("Failed to insert cert chain")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001799 Self::set_blob_internal(tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
Max Biresb2e1d032021-02-08 21:35:05 -08001800 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001801 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001802 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001803 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001804 }
1805
1806 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1807 /// currently have a key assigned to it.
1808 pub fn assign_attestation_key(
1809 &mut self,
1810 domain: Domain,
1811 namespace: i64,
1812 km_uuid: &Uuid,
1813 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001814 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1815
Max Bires2b2e6562020-09-22 11:22:36 -07001816 match domain {
1817 Domain::APP | Domain::SELINUX => {}
1818 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001819 return Err(KsError::sys())
1820 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Max Bires2b2e6562020-09-22 11:22:36 -07001821 }
1822 }
1823 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1824 let result = tx
1825 .execute(
1826 "UPDATE persistent.keyentry
1827 SET domain=?1, namespace=?2
1828 WHERE
1829 id =
1830 (SELECT MIN(id)
1831 FROM persistent.keyentry
1832 WHERE ALIAS IS NOT NULL
1833 AND domain IS NULL
1834 AND key_type IS ?3
1835 AND state IS ?4
1836 AND km_uuid IS ?5)
1837 AND
1838 (SELECT COUNT(*)
1839 FROM persistent.keyentry
1840 WHERE domain=?1
1841 AND namespace=?2
1842 AND key_type IS ?3
1843 AND state IS ?4
1844 AND km_uuid IS ?5) = 0;",
1845 params![
1846 domain.0 as u32,
1847 namespace,
1848 KeyType::Attestation,
1849 KeyLifeCycle::Live,
1850 km_uuid,
1851 ],
1852 )
1853 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001854 if result == 0 {
Hasini Gunasinghe1a8524b2022-05-10 08:49:53 +00001855 let (_, hw_info) = get_keymint_dev_by_uuid(km_uuid)
1856 .context("Error in retrieving keymint device by UUID.")?;
1857 log_rkp_error_stats(MetricsRkpError::OUT_OF_KEYS, &hw_info.securityLevel);
Seth Moored7ad8562023-01-23 09:28:56 -08001858 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
1859 .context("Out of keys.");
Max Bires01f8af22021-03-02 23:24:50 -08001860 } else if result > 1 {
1861 return Err(KsError::sys())
1862 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001863 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001864 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001865 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001866 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001867 }
1868
1869 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1870 /// provisioning server, or the maximum number available if there are not num_keys number of
1871 /// entries in the table.
1872 pub fn fetch_unsigned_attestation_keys(
1873 &mut self,
1874 num_keys: i32,
1875 km_uuid: &Uuid,
1876 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001877 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1878
Max Bires2b2e6562020-09-22 11:22:36 -07001879 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1880 let mut stmt = tx
1881 .prepare(
1882 "SELECT data
1883 FROM persistent.keymetadata
1884 WHERE tag = ? AND keyentryid IN
1885 (SELECT id
1886 FROM persistent.keyentry
1887 WHERE
1888 alias IS NULL AND
1889 domain IS NULL AND
1890 namespace IS NULL AND
1891 key_type = ? AND
1892 km_uuid = ?
1893 LIMIT ?);",
1894 )
1895 .context("Failed to prepare statement")?;
1896 let rows = stmt
1897 .query_map(
1898 params![
1899 KeyMetaData::AttestationMacedPublicKey,
1900 KeyType::Attestation,
1901 km_uuid,
1902 num_keys
1903 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001904 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001905 )?
1906 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1907 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001908 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001909 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001910 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001911 }
1912
1913 /// Removes any keys that have expired as of the current time. Returns the number of keys
1914 /// marked unreferenced that are bound to be garbage collected.
1915 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001916 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1917
Max Bires2b2e6562020-09-22 11:22:36 -07001918 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1919 let mut stmt = tx
1920 .prepare(
1921 "SELECT keyentryid, data
1922 FROM persistent.keymetadata
1923 WHERE tag = ? AND keyentryid IN
1924 (SELECT id
1925 FROM persistent.keyentry
1926 WHERE key_type = ?);",
1927 )
1928 .context("Failed to prepare query")?;
1929 let key_ids_to_check = stmt
1930 .query_map(
1931 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1932 |row| Ok((row.get(0)?, row.get(1)?)),
1933 )?
1934 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1935 .context("Failed to get date metadata")?;
Max Birescd7f7412022-02-11 13:47:36 -08001936 // Calculate curr_time with a discount factor to avoid a key that's milliseconds away
1937 // from expiration dodging this delete call.
Max Bires2b2e6562020-09-22 11:22:36 -07001938 let curr_time = DateTime::from_millis_epoch(
Max Birescd7f7412022-02-11 13:47:36 -08001939 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
1940 + EXPIRATION_BUFFER_MS,
Max Bires2b2e6562020-09-22 11:22:36 -07001941 );
1942 let mut num_deleted = 0;
1943 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001944 if Self::mark_unreferenced(tx, id)? {
Max Bires2b2e6562020-09-22 11:22:36 -07001945 num_deleted += 1;
1946 }
1947 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001948 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001949 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001950 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001951 }
1952
Max Bires60d7ed12021-03-05 15:59:22 -08001953 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1954 /// they are in. This is useful primarily as a testing mechanism.
1955 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001956 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1957
Max Bires60d7ed12021-03-05 15:59:22 -08001958 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1959 let mut stmt = tx
1960 .prepare(
1961 "SELECT id FROM persistent.keyentry
1962 WHERE key_type IS ?;",
1963 )
1964 .context("Failed to prepare statement")?;
1965 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001966 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001967 .collect::<rusqlite::Result<Vec<i64>>>()
1968 .context("Failed to execute statement")?;
1969 let num_deleted = keys_to_delete
1970 .iter()
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001971 .map(|id| Self::mark_unreferenced(tx, *id))
Max Bires60d7ed12021-03-05 15:59:22 -08001972 .collect::<Result<Vec<bool>>>()
1973 .context("Failed to execute mark_unreferenced on a keyid")?
1974 .into_iter()
1975 .filter(|result| *result)
1976 .count() as i64;
1977 Ok(num_deleted).do_gc(num_deleted != 0)
1978 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001979 .context(ks_err!())
Max Bires60d7ed12021-03-05 15:59:22 -08001980 }
1981
Max Bires55620ff2022-02-11 13:34:15 -08001982 fn query_kid_for_attestation_key_and_cert_chain(
1983 &self,
1984 tx: &Transaction,
1985 domain: Domain,
1986 namespace: i64,
1987 km_uuid: &Uuid,
1988 ) -> Result<Option<i64>> {
1989 let mut stmt = tx.prepare(
1990 "SELECT id
1991 FROM persistent.keyentry
1992 WHERE key_type = ?
1993 AND domain = ?
1994 AND namespace = ?
1995 AND state = ?
1996 AND km_uuid = ?;",
1997 )?;
1998 let rows = stmt
1999 .query_map(
2000 params![
2001 KeyType::Attestation,
2002 domain.0 as u32,
2003 namespace,
2004 KeyLifeCycle::Live,
2005 km_uuid
2006 ],
2007 |row| row.get(0),
2008 )?
2009 .collect::<rusqlite::Result<Vec<i64>>>()
2010 .context("query failed.")?;
2011 if rows.is_empty() {
2012 return Ok(None);
2013 }
2014 Ok(Some(rows[0]))
2015 }
2016
Max Bires2b2e6562020-09-22 11:22:36 -07002017 /// Fetches the private key and corresponding certificate chain assigned to a
2018 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2019 /// not assigned, or one CertificateChain.
2020 pub fn retrieve_attestation_key_and_cert_chain(
2021 &mut self,
2022 domain: Domain,
2023 namespace: i64,
2024 km_uuid: &Uuid,
Max Bires55620ff2022-02-11 13:34:15 -08002025 ) -> Result<Option<(KeyIdGuard, CertificateChain)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002026 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2027
Max Bires2b2e6562020-09-22 11:22:36 -07002028 match domain {
2029 Domain::APP | Domain::SELINUX => {}
2030 _ => {
2031 return Err(KsError::sys())
2032 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2033 }
2034 }
Max Bires55620ff2022-02-11 13:34:15 -08002035
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002036 self.delete_expired_attestation_keys()
2037 .context(ks_err!("Failed to prune expired attestation keys",))?;
2038 let tx = self
2039 .conn
2040 .unchecked_transaction()
2041 .context(ks_err!("Failed to initialize transaction."))?;
Chariseea1e1c482022-02-26 01:26:35 +00002042 let key_id: i64 = match self
2043 .query_kid_for_attestation_key_and_cert_chain(&tx, domain, namespace, km_uuid)?
2044 {
Max Bires55620ff2022-02-11 13:34:15 -08002045 None => return Ok(None),
Chariseea1e1c482022-02-26 01:26:35 +00002046 Some(kid) => kid,
2047 };
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002048 tx.commit().context(ks_err!("Failed to commit keyid query"))?;
Max Bires55620ff2022-02-11 13:34:15 -08002049 let key_id_guard = KEY_ID_LOCK.get(key_id);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002050 let tx = self
2051 .conn
2052 .unchecked_transaction()
2053 .context(ks_err!("Failed to initialize transaction."))?;
Max Bires55620ff2022-02-11 13:34:15 -08002054 let mut stmt = tx.prepare(
2055 "SELECT subcomponent_type, blob
2056 FROM persistent.blobentry
2057 WHERE keyentryid = ?;",
2058 )?;
2059 let rows = stmt
2060 .query_map(params![key_id_guard.id()], |row| Ok((row.get(0)?, row.get(1)?)))?
2061 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
2062 .context("query failed.")?;
2063 if rows.is_empty() {
2064 return Ok(None);
2065 } else if rows.len() != 3 {
2066 return Err(KsError::sys()).context(format!(
2067 concat!(
2068 "Expected to get a single attestation",
2069 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2070 ),
2071 rows.len()
2072 ));
2073 }
2074 let mut km_blob: Vec<u8> = Vec::new();
2075 let mut cert_chain_blob: Vec<u8> = Vec::new();
2076 let mut batch_cert_blob: Vec<u8> = Vec::new();
2077 for row in rows {
2078 let sub_type: SubComponentType = row.0;
2079 match sub_type {
2080 SubComponentType::KEY_BLOB => {
2081 km_blob = row.1;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 }
Max Bires55620ff2022-02-11 13:34:15 -08002083 SubComponentType::CERT_CHAIN => {
2084 cert_chain_blob = row.1;
2085 }
2086 SubComponentType::CERT => {
2087 batch_cert_blob = row.1;
2088 }
2089 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002090 }
Max Bires55620ff2022-02-11 13:34:15 -08002091 }
2092 Ok(Some((
2093 key_id_guard,
2094 CertificateChain {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002095 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002096 batch_cert: batch_cert_blob,
2097 cert_chain: cert_chain_blob,
Max Bires55620ff2022-02-11 13:34:15 -08002098 },
2099 )))
Max Bires2b2e6562020-09-22 11:22:36 -07002100 }
2101
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002102 /// Updates the alias column of the given key id `newid` with the given alias,
2103 /// and atomically, removes the alias, domain, and namespace from another row
2104 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002105 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2106 /// collector.
2107 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002108 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002109 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002110 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002111 domain: &Domain,
2112 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002113 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002114 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002115 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002116 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002117 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002118 return Err(KsError::sys())
2119 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002120 }
2121 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002122 let updated = tx
2123 .execute(
2124 "UPDATE persistent.keyentry
2125 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002126 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2127 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002128 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002129 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002130 let result = tx
2131 .execute(
2132 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002133 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002134 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002135 params![
2136 alias,
2137 KeyLifeCycle::Live,
2138 newid.0,
2139 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002140 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002141 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002142 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002143 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002144 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002145 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002146 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002147 return Err(KsError::sys()).context(ks_err!(
2148 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002149 result
2150 ));
2151 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002152 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002153 }
2154
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002155 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2156 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2157 pub fn migrate_key_namespace(
2158 &mut self,
2159 key_id_guard: KeyIdGuard,
2160 destination: &KeyDescriptor,
2161 caller_uid: u32,
2162 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2163 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002164 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2165
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002166 let destination = match destination.domain {
2167 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2168 Domain::SELINUX => (*destination).clone(),
2169 domain => {
2170 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2171 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2172 }
2173 };
2174
2175 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002176 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002177
2178 let alias = destination
2179 .alias
2180 .as_ref()
2181 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002182 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002183
2184 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2185 // Query the destination location. If there is a key, the migration request fails.
2186 if tx
2187 .query_row(
2188 "SELECT id FROM persistent.keyentry
2189 WHERE alias = ? AND domain = ? AND namespace = ?;",
2190 params![alias, destination.domain.0, destination.nspace],
2191 |_| Ok(()),
2192 )
2193 .optional()
2194 .context("Failed to query destination.")?
2195 .is_some()
2196 {
2197 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2198 .context("Target already exists.");
2199 }
2200
2201 let updated = tx
2202 .execute(
2203 "UPDATE persistent.keyentry
2204 SET alias = ?, domain = ?, namespace = ?
2205 WHERE id = ?;",
2206 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2207 )
2208 .context("Failed to update key entry.")?;
2209
2210 if updated != 1 {
2211 return Err(KsError::sys())
2212 .context(format!("Update succeeded, but {} rows were updated.", updated));
2213 }
2214 Ok(()).no_gc()
2215 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002216 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002217 }
2218
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002219 /// Store a new key in a single transaction.
2220 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2221 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002222 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2223 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07002224 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002225 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002226 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002227 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002228 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002229 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002230 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08002231 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002232 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002233 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002234 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002235 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2236
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002237 let (alias, domain, namespace) = match key {
2238 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2239 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2240 (alias, key.domain, nspace)
2241 }
2242 _ => {
2243 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002244 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002245 }
2246 };
2247 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002248 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002249 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002250 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
2251
2252 // In some occasions the key blob is already upgraded during the import.
2253 // In order to make sure it gets properly deleted it is inserted into the
2254 // database here and then immediately replaced by the superseding blob.
2255 // The garbage collector will then subject the blob to deleteKey of the
2256 // KM back end to permanently invalidate the key.
2257 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
2258 Self::set_blob_internal(
2259 tx,
2260 key_id.id(),
2261 SubComponentType::KEY_BLOB,
2262 Some(blob),
2263 Some(blob_metadata),
2264 )
2265 .context("Trying to insert superseded key blob.")?;
2266 true
2267 } else {
2268 false
2269 };
2270
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002271 Self::set_blob_internal(
2272 tx,
2273 key_id.id(),
2274 SubComponentType::KEY_BLOB,
2275 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002276 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002277 )
2278 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002279 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002280 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002281 .context("Trying to insert the certificate.")?;
2282 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002283 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002284 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002285 tx,
2286 key_id.id(),
2287 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002288 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002289 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002290 )
2291 .context("Trying to insert the certificate chain.")?;
2292 }
2293 Self::insert_keyparameter_internal(tx, &key_id, params)
2294 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002295 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002296 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002297 .context("Trying to rebind alias.")?
2298 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002299 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002300 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002301 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002302 }
2303
Janis Danisevskis377d1002021-01-27 19:07:48 -08002304 /// Store a new certificate
2305 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2306 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002307 pub fn store_new_certificate(
2308 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002309 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002310 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002311 cert: &[u8],
2312 km_uuid: &Uuid,
2313 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002314 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2315
Janis Danisevskis377d1002021-01-27 19:07:48 -08002316 let (alias, domain, namespace) = match key {
2317 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2318 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2319 (alias, key.domain, nspace)
2320 }
2321 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002322 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2323 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08002324 }
2325 };
2326 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002327 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002328 .context("Trying to create new key entry.")?;
2329
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002330 Self::set_blob_internal(
2331 tx,
2332 key_id.id(),
2333 SubComponentType::CERT_CHAIN,
2334 Some(cert),
2335 None,
2336 )
2337 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002338
2339 let mut metadata = KeyMetaData::new();
2340 metadata.add(KeyMetaEntry::CreationDate(
2341 DateTime::now().context("Trying to make creation time.")?,
2342 ));
2343
2344 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2345
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002346 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002347 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002348 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002349 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002350 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08002351 }
2352
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002353 // Helper function loading the key_id given the key descriptor
2354 // tuple comprising domain, namespace, and alias.
2355 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002356 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002357 let alias = key
2358 .alias
2359 .as_ref()
2360 .map_or_else(|| Err(KsError::sys()), Ok)
2361 .context("In load_key_entry_id: Alias must be specified.")?;
2362 let mut stmt = tx
2363 .prepare(
2364 "SELECT id FROM persistent.keyentry
2365 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002366 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002367 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002368 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002369 AND alias = ?
2370 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002371 )
2372 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2373 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002374 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002375 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002376 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002377 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002378 .get(0)
2379 .context("Failed to unpack id.")
2380 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002381 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002382 }
2383
2384 /// This helper function completes the access tuple of a key, which is required
2385 /// to perform access control. The strategy depends on the `domain` field in the
2386 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002387 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002388 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002389 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002390 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002391 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002392 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002393 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002394 /// `namespace`.
2395 /// In each case the information returned is sufficient to perform the access
2396 /// check and the key id can be used to load further key artifacts.
2397 fn load_access_tuple(
2398 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002399 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002400 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002401 caller_uid: u32,
2402 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2403 match key.domain {
2404 // Domain App or SELinux. In this case we load the key_id from
2405 // the keyentry database for further loading of key components.
2406 // We already have the full access tuple to perform access control.
2407 // The only distinction is that we use the caller_uid instead
2408 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002409 // Domain::APP.
2410 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002411 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002412 if access_key.domain == Domain::APP {
2413 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002414 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002415 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002416 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002417
2418 Ok((key_id, access_key, None))
2419 }
2420
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002421 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002422 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002423 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002424 let mut stmt = tx
2425 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002426 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002427 WHERE grantee = ? AND id = ? AND
2428 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002429 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002430 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002431 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002432 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002433 .context("Domain:Grant: query failed.")?;
2434 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002435 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002436 let r =
2437 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 Ok((
2439 r.get(0).context("Failed to unpack key_id.")?,
2440 r.get(1).context("Failed to unpack access_vector.")?,
2441 ))
2442 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002443 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002444 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002445 }
2446
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002447 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002448 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002449 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002450 let (domain, namespace): (Domain, i64) = {
2451 let mut stmt = tx
2452 .prepare(
2453 "SELECT domain, namespace FROM persistent.keyentry
2454 WHERE
2455 id = ?
2456 AND state = ?;",
2457 )
2458 .context("Domain::KEY_ID: prepare statement failed")?;
2459 let mut rows = stmt
2460 .query(params![key.nspace, KeyLifeCycle::Live])
2461 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002462 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002463 let r =
2464 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002465 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002466 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002467 r.get(1).context("Failed to unpack namespace.")?,
2468 ))
2469 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002470 .context("Domain::KEY_ID.")?
2471 };
2472
2473 // We may use a key by id after loading it by grant.
2474 // In this case we have to check if the caller has a grant for this particular
2475 // key. We can skip this if we already know that the caller is the owner.
2476 // But we cannot know this if domain is anything but App. E.g. in the case
2477 // of Domain::SELINUX we have to speculatively check for grants because we have to
2478 // consult the SEPolicy before we know if the caller is the owner.
2479 let access_vector: Option<KeyPermSet> =
2480 if domain != Domain::APP || namespace != caller_uid as i64 {
2481 let access_vector: Option<i32> = tx
2482 .query_row(
2483 "SELECT access_vector FROM persistent.grant
2484 WHERE grantee = ? AND keyentryid = ?;",
2485 params![caller_uid as i64, key.nspace],
2486 |row| row.get(0),
2487 )
2488 .optional()
2489 .context("Domain::KEY_ID: query grant failed.")?;
2490 access_vector.map(|p| p.into())
2491 } else {
2492 None
2493 };
2494
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002495 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002496 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002497 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002498 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002499
Janis Danisevskis45760022021-01-19 16:34:10 -08002500 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002501 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002502 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002503 }
2504 }
2505
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002506 fn load_blob_components(
2507 key_id: i64,
2508 load_bits: KeyEntryLoadBits,
2509 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002510 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002511 let mut stmt = tx
2512 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002513 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002514 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2515 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002516 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002517
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002518 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002519
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002520 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002521 let mut cert_blob: Option<Vec<u8>> = None;
2522 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002523 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002524 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002525 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002526 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002527 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002528 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2529 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002530 key_blob = Some((
2531 row.get(0).context("Failed to extract key blob id.")?,
2532 row.get(2).context("Failed to extract key blob.")?,
2533 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002534 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002535 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002536 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002537 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002538 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002539 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002540 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002541 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002542 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002543 (SubComponentType::CERT, _, _)
2544 | (SubComponentType::CERT_CHAIN, _, _)
2545 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002546 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2547 }
2548 Ok(())
2549 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002550 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002551
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002552 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2553 Ok(Some((
2554 blob,
2555 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002556 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002557 )))
2558 })?;
2559
2560 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002561 }
2562
2563 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2564 let mut stmt = tx
2565 .prepare(
2566 "SELECT tag, data, security_level from persistent.keyparameter
2567 WHERE keyentryid = ?;",
2568 )
2569 .context("In load_key_parameters: prepare statement failed.")?;
2570
2571 let mut parameters: Vec<KeyParameter> = Vec::new();
2572
2573 let mut rows =
2574 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002575 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002576 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2577 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002578 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002579 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002580 .context("Failed to read KeyParameter.")?,
2581 );
2582 Ok(())
2583 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002584 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002585
2586 Ok(parameters)
2587 }
2588
Qi Wub9433b52020-12-01 14:52:46 +08002589 /// Decrements the usage count of a limited use key. This function first checks whether the
2590 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2591 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2592 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002593 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002594 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2595
Qi Wub9433b52020-12-01 14:52:46 +08002596 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2597 let limit: Option<i32> = tx
2598 .query_row(
2599 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2600 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2601 |row| row.get(0),
2602 )
2603 .optional()
2604 .context("Trying to load usage count")?;
2605
2606 let limit = limit
2607 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2608 .context("The Key no longer exists. Key is exhausted.")?;
2609
2610 tx.execute(
2611 "UPDATE persistent.keyparameter
2612 SET data = data - 1
2613 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2614 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2615 )
2616 .context("Failed to update key usage count.")?;
2617
2618 match limit {
2619 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002620 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002621 .context("Trying to mark limited use key for deletion."),
2622 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002623 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002624 }
2625 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002626 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002627 }
2628
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002629 /// Load a key entry by the given key descriptor.
2630 /// It uses the `check_permission` callback to verify if the access is allowed
2631 /// given the key access tuple read from the database using `load_access_tuple`.
2632 /// With `load_bits` the caller may specify which blobs shall be loaded from
2633 /// the blob database.
2634 pub fn load_key_entry(
2635 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002636 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002637 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002638 load_bits: KeyEntryLoadBits,
2639 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002640 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2641 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002642 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2643
Janis Danisevskis66784c42021-01-27 08:40:25 -08002644 loop {
2645 match self.load_key_entry_internal(
2646 key,
2647 key_type,
2648 load_bits,
2649 caller_uid,
2650 &check_permission,
2651 ) {
2652 Ok(result) => break Ok(result),
2653 Err(e) => {
2654 if Self::is_locked_error(&e) {
2655 std::thread::sleep(std::time::Duration::from_micros(500));
2656 continue;
2657 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002658 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002659 }
2660 }
2661 }
2662 }
2663 }
2664
2665 fn load_key_entry_internal(
2666 &mut self,
2667 key: &KeyDescriptor,
2668 key_type: KeyType,
2669 load_bits: KeyEntryLoadBits,
2670 caller_uid: u32,
2671 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002672 ) -> Result<(KeyIdGuard, KeyEntry)> {
2673 // KEY ID LOCK 1/2
2674 // If we got a key descriptor with a key id we can get the lock right away.
2675 // Otherwise we have to defer it until we know the key id.
2676 let key_id_guard = match key.domain {
2677 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2678 _ => None,
2679 };
2680
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002681 let tx = self
2682 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002683 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002684 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002685
2686 // Load the key_id and complete the access control tuple.
2687 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002688 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002689
2690 // Perform access control. It is vital that we return here if the permission is denied.
2691 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002692 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002693
Janis Danisevskisaec14592020-11-12 09:41:49 -08002694 // KEY ID LOCK 2/2
2695 // If we did not get a key id lock by now, it was because we got a key descriptor
2696 // without a key id. At this point we got the key id, so we can try and get a lock.
2697 // However, we cannot block here, because we are in the middle of the transaction.
2698 // So first we try to get the lock non blocking. If that fails, we roll back the
2699 // transaction and block until we get the lock. After we successfully got the lock,
2700 // we start a new transaction and load the access tuple again.
2701 //
2702 // We don't need to perform access control again, because we already established
2703 // that the caller had access to the given key. But we need to make sure that the
2704 // key id still exists. So we have to load the key entry by key id this time.
2705 let (key_id_guard, tx) = match key_id_guard {
2706 None => match KEY_ID_LOCK.try_get(key_id) {
2707 None => {
2708 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002709 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002710
Janis Danisevskisaec14592020-11-12 09:41:49 -08002711 // Block until we have a key id lock.
2712 let key_id_guard = KEY_ID_LOCK.get(key_id);
2713
2714 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002715 let tx = self
2716 .conn
2717 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002718 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002719
2720 Self::load_access_tuple(
2721 &tx,
2722 // This time we have to load the key by the retrieved key id, because the
2723 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002724 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002725 domain: Domain::KEY_ID,
2726 nspace: key_id,
2727 ..Default::default()
2728 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002729 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002730 caller_uid,
2731 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002732 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002733 (key_id_guard, tx)
2734 }
2735 Some(l) => (l, tx),
2736 },
2737 Some(key_id_guard) => (key_id_guard, tx),
2738 };
2739
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002740 let key_entry =
2741 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002742
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002743 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002744
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002745 Ok((key_id_guard, key_entry))
2746 }
2747
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002748 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002749 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002750 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2751 .context("Trying to delete keyentry.")?;
2752 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2753 .context("Trying to delete keymetadata.")?;
2754 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2755 .context("Trying to delete keyparameters.")?;
2756 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2757 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002758 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002759 }
2760
2761 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002762 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002763 pub fn unbind_key(
2764 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002765 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002766 key_type: KeyType,
2767 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002768 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002769 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002770 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2771
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002772 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2773 let (key_id, access_key_descriptor, access_vector) =
2774 Self::load_access_tuple(tx, key, key_type, caller_uid)
2775 .context("Trying to get access tuple.")?;
2776
2777 // Perform access control. It is vital that we return here if the permission is denied.
2778 // So do not touch that '?' at the end.
2779 check_permission(&access_key_descriptor, access_vector)
2780 .context("While checking permission.")?;
2781
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002782 Self::mark_unreferenced(tx, key_id)
2783 .map(|need_gc| (need_gc, ()))
2784 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002785 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002786 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002787 }
2788
Max Bires8e93d2b2021-01-14 13:17:59 -08002789 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2790 tx.query_row(
2791 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2792 params![key_id],
2793 |row| row.get(0),
2794 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002795 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002796 }
2797
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002798 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2799 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2800 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002801 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2802
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002803 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002804 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002805 }
2806 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2807 tx.execute(
2808 "DELETE FROM persistent.keymetadata
2809 WHERE keyentryid IN (
2810 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002811 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002812 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002813 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002814 )
2815 .context("Trying to delete keymetadata.")?;
2816 tx.execute(
2817 "DELETE FROM persistent.keyparameter
2818 WHERE keyentryid IN (
2819 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002820 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002821 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002822 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002823 )
2824 .context("Trying to delete keyparameters.")?;
2825 tx.execute(
2826 "DELETE FROM persistent.grant
2827 WHERE keyentryid IN (
2828 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002829 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002830 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002831 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002832 )
2833 .context("Trying to delete grants.")?;
2834 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002835 "DELETE FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002836 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?);",
2837 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002838 )
2839 .context("Trying to delete keyentry.")?;
2840 Ok(()).need_gc()
2841 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002842 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002843 }
2844
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002845 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2846 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2847 {
2848 tx.execute(
2849 "DELETE FROM persistent.keymetadata
2850 WHERE keyentryid IN (
2851 SELECT id FROM persistent.keyentry
2852 WHERE state = ?
2853 );",
2854 params![KeyLifeCycle::Unreferenced],
2855 )
2856 .context("Trying to delete keymetadata.")?;
2857 tx.execute(
2858 "DELETE FROM persistent.keyparameter
2859 WHERE keyentryid IN (
2860 SELECT id FROM persistent.keyentry
2861 WHERE state = ?
2862 );",
2863 params![KeyLifeCycle::Unreferenced],
2864 )
2865 .context("Trying to delete keyparameters.")?;
2866 tx.execute(
2867 "DELETE FROM persistent.grant
2868 WHERE keyentryid IN (
2869 SELECT id FROM persistent.keyentry
2870 WHERE state = ?
2871 );",
2872 params![KeyLifeCycle::Unreferenced],
2873 )
2874 .context("Trying to delete grants.")?;
2875 tx.execute(
2876 "DELETE FROM persistent.keyentry
2877 WHERE state = ?;",
2878 params![KeyLifeCycle::Unreferenced],
2879 )
2880 .context("Trying to delete keyentry.")?;
2881 Result::<()>::Ok(())
2882 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002883 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002884 }
2885
Hasini Gunasingheda895552021-01-27 19:34:37 +00002886 /// Delete the keys created on behalf of the user, denoted by the user id.
2887 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2888 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2889 /// The caller of this function should notify the gc if the returned value is true.
2890 pub fn unbind_keys_for_user(
2891 &mut self,
2892 user_id: u32,
2893 keep_non_super_encrypted_keys: bool,
2894 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002895 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2896
Hasini Gunasingheda895552021-01-27 19:34:37 +00002897 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2898 let mut stmt = tx
2899 .prepare(&format!(
2900 "SELECT id from persistent.keyentry
2901 WHERE (
2902 key_type = ?
2903 AND domain = ?
2904 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2905 AND state = ?
2906 ) OR (
2907 key_type = ?
2908 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002909 AND state = ?
2910 );",
2911 aid_user_offset = AID_USER_OFFSET
2912 ))
2913 .context(concat!(
2914 "In unbind_keys_for_user. ",
2915 "Failed to prepare the query to find the keys created by apps."
2916 ))?;
2917
2918 let mut rows = stmt
2919 .query(params![
2920 // WHERE client key:
2921 KeyType::Client,
2922 Domain::APP.0 as u32,
2923 user_id,
2924 KeyLifeCycle::Live,
2925 // OR super key:
2926 KeyType::Super,
2927 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002928 KeyLifeCycle::Live
2929 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002930 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002931
2932 let mut key_ids: Vec<i64> = Vec::new();
2933 db_utils::with_rows_extract_all(&mut rows, |row| {
2934 key_ids
2935 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2936 Ok(())
2937 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002938 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002939
2940 let mut notify_gc = false;
2941 for key_id in key_ids {
2942 if keep_non_super_encrypted_keys {
2943 // Load metadata and filter out non-super-encrypted keys.
2944 if let (_, Some((_, blob_metadata)), _, _) =
2945 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002946 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002947 {
2948 if blob_metadata.encrypted_by().is_none() {
2949 continue;
2950 }
2951 }
2952 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002953 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002954 .context("In unbind_keys_for_user.")?
2955 || notify_gc;
2956 }
2957 Ok(()).do_gc(notify_gc)
2958 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002959 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002960 }
2961
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002962 fn load_key_components(
2963 tx: &Transaction,
2964 load_bits: KeyEntryLoadBits,
2965 key_id: i64,
2966 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002967 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002968
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002969 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002970 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002971
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002972 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002973 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002974
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002975 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002976 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002977
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002978 Ok(KeyEntry {
2979 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002980 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002981 cert: cert_blob,
2982 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002983 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002984 parameters,
2985 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002986 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002987 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002988 }
2989
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002990 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2991 /// The key descriptors will have the domain, nspace, and alias field set.
2992 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07002993 pub fn list(
2994 &mut self,
2995 domain: Domain,
2996 namespace: i64,
2997 key_type: KeyType,
2998 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002999 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3000
Janis Danisevskis66784c42021-01-27 08:40:25 -08003001 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3002 let mut stmt = tx
3003 .prepare(
3004 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07003005 WHERE domain = ?
3006 AND namespace = ?
3007 AND alias IS NOT NULL
3008 AND state = ?
3009 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003010 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003011 .context(ks_err!("Failed to prepare."))?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003012
Janis Danisevskis66784c42021-01-27 08:40:25 -08003013 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003014 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003015 .context(ks_err!("Failed to query."))?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003016
Janis Danisevskis66784c42021-01-27 08:40:25 -08003017 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3018 db_utils::with_rows_extract_all(&mut rows, |row| {
3019 descriptors.push(KeyDescriptor {
3020 domain,
3021 nspace: namespace,
3022 alias: Some(row.get(0).context("Trying to extract alias.")?),
3023 blob: None,
3024 });
3025 Ok(())
3026 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003027 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003028 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003029 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003030 }
3031
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003032 /// Adds a grant to the grant table.
3033 /// Like `load_key_entry` this function loads the access tuple before
3034 /// it uses the callback for a permission check. Upon success,
3035 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3036 /// grant table. The new row will have a randomized id, which is used as
3037 /// grant id in the namespace field of the resulting KeyDescriptor.
3038 pub fn grant(
3039 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003040 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003041 caller_uid: u32,
3042 grantee_uid: u32,
3043 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003044 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003045 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003046 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3047
Janis Danisevskis66784c42021-01-27 08:40:25 -08003048 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3049 // Load the key_id and complete the access control tuple.
3050 // We ignore the access vector here because grants cannot be granted.
3051 // The access vector returned here expresses the permissions the
3052 // grantee has if key.domain == Domain::GRANT. But this vector
3053 // cannot include the grant permission by design, so there is no way the
3054 // subsequent permission check can pass.
3055 // We could check key.domain == Domain::GRANT and fail early.
3056 // But even if we load the access tuple by grant here, the permission
3057 // check denies the attempt to create a grant by grant descriptor.
3058 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003059 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003060
Janis Danisevskis66784c42021-01-27 08:40:25 -08003061 // Perform access control. It is vital that we return here if the permission
3062 // was denied. So do not touch that '?' at the end of the line.
3063 // This permission check checks if the caller has the grant permission
3064 // for the given key and in addition to all of the permissions
3065 // expressed in `access_vector`.
3066 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003067 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003068
Janis Danisevskis66784c42021-01-27 08:40:25 -08003069 let grant_id = if let Some(grant_id) = tx
3070 .query_row(
3071 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003072 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003073 params![key_id, grantee_uid],
3074 |row| row.get(0),
3075 )
3076 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003077 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 {
3079 tx.execute(
3080 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003081 SET access_vector = ?
3082 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003084 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003085 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003086 grant_id
3087 } else {
3088 Self::insert_with_retry(|id| {
3089 tx.execute(
3090 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3091 VALUES (?, ?, ?, ?);",
3092 params![id, grantee_uid, key_id, i32::from(access_vector)],
3093 )
3094 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003095 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08003096 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003097
Janis Danisevskis66784c42021-01-27 08:40:25 -08003098 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003099 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003100 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101 }
3102
3103 /// This function checks permissions like `grant` and `load_key_entry`
3104 /// before removing a grant from the grant table.
3105 pub fn ungrant(
3106 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003107 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003108 caller_uid: u32,
3109 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003110 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003111 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003112 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3113
Janis Danisevskis66784c42021-01-27 08:40:25 -08003114 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3115 // Load the key_id and complete the access control tuple.
3116 // We ignore the access vector here because grants cannot be granted.
3117 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003118 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003119
Janis Danisevskis66784c42021-01-27 08:40:25 -08003120 // Perform access control. We must return here if the permission
3121 // was denied. So do not touch the '?' at the end of this line.
3122 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003123 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003124
Janis Danisevskis66784c42021-01-27 08:40:25 -08003125 tx.execute(
3126 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003127 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003128 params![key_id, grantee_uid],
3129 )
3130 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003131
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003132 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003133 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003134 }
3135
Joel Galenson845f74b2020-09-09 14:11:55 -07003136 // Generates a random id and passes it to the given function, which will
3137 // try to insert it into a database. If that insertion fails, retry;
3138 // otherwise return the id.
3139 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3140 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003141 let newid: i64 = match random() {
3142 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3143 i => i,
3144 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003145 match inserter(newid) {
3146 // If the id already existed, try again.
3147 Err(rusqlite::Error::SqliteFailure(
3148 libsqlite3_sys::Error {
3149 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3150 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3151 },
3152 _,
3153 )) => (),
3154 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003155 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07003156 }
3157 _ => return Ok(newid),
3158 }
3159 }
3160 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003161
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003162 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3163 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3164 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3165 auth_token.clone(),
3166 MonotonicRawTime::now(),
3167 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003168 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003169
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003170 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003171 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003172 where
3173 F: Fn(&AuthTokenEntry) -> bool,
3174 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003175 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003176 }
3177
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003178 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003179 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3180 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003181 }
3182
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003183 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003184 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3185 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003186 }
3187
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003188 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003189 fn get_last_off_body(&self) -> MonotonicRawTime {
3190 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003191 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003192
3193 /// Load descriptor of a key by key id
3194 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3195 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3196
3197 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3198 tx.query_row(
3199 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3200 params![key_id],
3201 |row| {
3202 Ok(KeyDescriptor {
3203 domain: Domain(row.get(0)?),
3204 nspace: row.get(1)?,
3205 alias: row.get(2)?,
3206 blob: None,
3207 })
3208 },
3209 )
3210 .optional()
3211 .context("Trying to load key descriptor")
3212 .no_gc()
3213 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003214 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01003215 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003216}
3217
3218#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08003219pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07003220
3221 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003222 use crate::key_parameter::{
3223 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3224 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3225 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003226 use crate::key_perm_set;
3227 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08003228 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003229 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003230 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3231 HardwareAuthToken::HardwareAuthToken,
3232 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003233 };
3234 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003235 Timestamp::Timestamp,
3236 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003237 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003238 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003239 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003240 use std::collections::BTreeMap;
3241 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003242 use std::sync::atomic::{AtomicU8, Ordering};
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003243 use std::sync::{Arc, RwLock};
Janis Danisevskisaec14592020-11-12 09:41:49 -08003244 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003245 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003246 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003247 #[cfg(disabled)]
3248 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003249
Seth Moore7ee79f92021-12-07 11:42:49 -08003250 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003251 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003252
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003253 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003254 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003255 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003256 })?;
3257 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003258 }
3259
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003260 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3261 where
3262 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3263 {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003264 let super_key: Arc<RwLock<SuperKeyManager>> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003265
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003266 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003267 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003268
Janis Danisevskis3395f862021-05-06 10:54:17 -07003269 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003270 }
3271
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003272 fn rebind_alias(
3273 db: &mut KeystoreDB,
3274 newid: &KeyIdGuard,
3275 alias: &str,
3276 domain: Domain,
3277 namespace: i64,
3278 ) -> Result<bool> {
3279 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003280 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003281 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003282 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003283 }
3284
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003285 #[test]
3286 fn datetime() -> Result<()> {
3287 let conn = Connection::open_in_memory()?;
3288 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3289 let now = SystemTime::now();
3290 let duration = Duration::from_secs(1000);
3291 let then = now.checked_sub(duration).unwrap();
3292 let soon = now.checked_add(duration).unwrap();
3293 conn.execute(
3294 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3295 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3296 )?;
3297 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3298 let mut rows = stmt.query(NO_PARAMS)?;
3299 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3300 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3301 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3302 assert!(rows.next()?.is_none());
3303 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3304 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3305 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3306 Ok(())
3307 }
3308
Joel Galenson0891bc12020-07-20 10:37:03 -07003309 // Ensure that we're using the "injected" random function, not the real one.
3310 #[test]
3311 fn test_mocked_random() {
3312 let rand1 = random();
3313 let rand2 = random();
3314 let rand3 = random();
3315 if rand1 == rand2 {
3316 assert_eq!(rand2 + 1, rand3);
3317 } else {
3318 assert_eq!(rand1 + 1, rand2);
3319 assert_eq!(rand2, rand3);
3320 }
3321 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003322
Joel Galenson26f4d012020-07-17 14:57:21 -07003323 // Test that we have the correct tables.
3324 #[test]
3325 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003326 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003327 let tables = db
3328 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003329 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003330 .query_map(params![], |row| row.get(0))?
3331 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003332 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003333 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003334 assert_eq!(tables[1], "blobmetadata");
3335 assert_eq!(tables[2], "grant");
3336 assert_eq!(tables[3], "keyentry");
3337 assert_eq!(tables[4], "keymetadata");
3338 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003339 Ok(())
3340 }
3341
3342 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003343 fn test_auth_token_table_invariant() -> Result<()> {
3344 let mut db = new_test_db()?;
3345 let auth_token1 = HardwareAuthToken {
3346 challenge: i64::MAX,
3347 userId: 200,
3348 authenticatorId: 200,
3349 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3350 timestamp: Timestamp { milliSeconds: 500 },
3351 mac: String::from("mac").into_bytes(),
3352 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003353 db.insert_auth_token(&auth_token1);
3354 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003355 assert_eq!(auth_tokens_returned.len(), 1);
3356
3357 // insert another auth token with the same values for the columns in the UNIQUE constraint
3358 // of the auth token table and different value for timestamp
3359 let auth_token2 = HardwareAuthToken {
3360 challenge: i64::MAX,
3361 userId: 200,
3362 authenticatorId: 200,
3363 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3364 timestamp: Timestamp { milliSeconds: 600 },
3365 mac: String::from("mac").into_bytes(),
3366 };
3367
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003368 db.insert_auth_token(&auth_token2);
3369 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003370 assert_eq!(auth_tokens_returned.len(), 1);
3371
3372 if let Some(auth_token) = auth_tokens_returned.pop() {
3373 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3374 }
3375
3376 // insert another auth token with the different values for the columns in the UNIQUE
3377 // constraint of the auth token table
3378 let auth_token3 = HardwareAuthToken {
3379 challenge: i64::MAX,
3380 userId: 201,
3381 authenticatorId: 200,
3382 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3383 timestamp: Timestamp { milliSeconds: 600 },
3384 mac: String::from("mac").into_bytes(),
3385 };
3386
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003387 db.insert_auth_token(&auth_token3);
3388 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003389 assert_eq!(auth_tokens_returned.len(), 2);
3390
3391 Ok(())
3392 }
3393
3394 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003395 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3396 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003397 }
3398
3399 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003400 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003401 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003402 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003403
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003404 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003405 let entries = get_keyentry(&db)?;
3406 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003407
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003408 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003409
3410 let entries_new = get_keyentry(&db)?;
3411 assert_eq!(entries, entries_new);
3412 Ok(())
3413 }
3414
3415 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003416 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003417 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3418 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003419 }
3420
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003421 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003422
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003423 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3424 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003425
3426 let entries = get_keyentry(&db)?;
3427 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003428 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3429 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003430
3431 // Test that we must pass in a valid Domain.
3432 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003433 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003434 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003435 );
3436 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003437 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003438 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003439 );
3440 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003441 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003442 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003443 );
3444
3445 Ok(())
3446 }
3447
Joel Galenson33c04ad2020-08-03 11:04:38 -07003448 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003449 fn test_add_unsigned_key() -> Result<()> {
3450 let mut db = new_test_db()?;
3451 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3452 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3453 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3454 db.create_attestation_key_entry(
3455 &public_key,
3456 &raw_public_key,
3457 &private_key,
3458 &KEYSTORE_UUID,
3459 )?;
3460 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3461 assert_eq!(keys.len(), 1);
3462 assert_eq!(keys[0], public_key);
3463 Ok(())
3464 }
3465
3466 #[test]
3467 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3468 let mut db = new_test_db()?;
Max Birescd7f7412022-02-11 13:47:36 -08003469 let expiration_date: i64 =
3470 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3471 + EXPIRATION_BUFFER_MS
3472 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003473 let namespace: i64 = 30;
3474 let base_byte: u8 = 1;
3475 let loaded_values =
3476 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3477 let chain =
3478 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Chris Wailes3877f292021-07-26 19:24:18 -07003479 assert!(chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003480 let (_, cert_chain) = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003481 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003482 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3483 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003484 Ok(())
3485 }
3486
3487 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003488 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003489 let temp_dir =
3490 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3491 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003492 let expiration_date: i64 =
Max Birescd7f7412022-02-11 13:47:36 -08003493 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3494 + EXPIRATION_BUFFER_MS
3495 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003496 let namespace: i64 = 30;
3497 let namespace_del1: i64 = 45;
3498 let namespace_del2: i64 = 60;
3499 let entry_values = load_attestation_key_pool(
3500 &mut db,
3501 expiration_date,
3502 namespace,
3503 0x01, /* base_byte */
3504 )?;
3505 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
Max Birescd7f7412022-02-11 13:47:36 -08003506 load_attestation_key_pool(&mut db, expiration_date - 10001, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003507
3508 let blob_entry_row_count: u32 = db
3509 .conn
3510 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3511 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003512 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3513 // one key, one certificate chain, and one certificate.
3514 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003515
Max Bires2b2e6562020-09-22 11:22:36 -07003516 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3517
3518 let mut cert_chain =
3519 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003520 assert!(cert_chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003521 let (_, value) = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003522 assert_eq!(entry_values.batch_cert, value.batch_cert);
3523 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003524 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003525
3526 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3527 Domain::APP,
3528 namespace_del1,
3529 &KEYSTORE_UUID,
3530 )?;
Chariseea1e1c482022-02-26 01:26:35 +00003531 assert!(cert_chain.is_none());
Max Bires2b2e6562020-09-22 11:22:36 -07003532 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3533 Domain::APP,
3534 namespace_del2,
3535 &KEYSTORE_UUID,
3536 )?;
Chariseea1e1c482022-02-26 01:26:35 +00003537 assert!(cert_chain.is_none());
Max Bires2b2e6562020-09-22 11:22:36 -07003538
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003539 // Give the garbage collector half a second to catch up.
3540 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003541
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003542 let blob_entry_row_count: u32 = db
3543 .conn
3544 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3545 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003546 // There shound be 3 blob entries left, because we deleted two of the attestation
3547 // key entries with three blobs each.
3548 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003549
Max Bires2b2e6562020-09-22 11:22:36 -07003550 Ok(())
3551 }
3552
Max Birescd7f7412022-02-11 13:47:36 -08003553 fn compare_rem_prov_values(
3554 expected: &RemoteProvValues,
3555 actual: Option<(KeyIdGuard, CertificateChain)>,
3556 ) {
3557 assert!(actual.is_some());
3558 let (_, value) = actual.unwrap();
3559 assert_eq!(expected.batch_cert, value.batch_cert);
3560 assert_eq!(expected.cert_chain, value.cert_chain);
3561 assert_eq!(expected.priv_key, value.private_key.to_vec());
3562 }
3563
3564 #[test]
3565 fn test_dont_remove_valid_certs() -> Result<()> {
3566 let temp_dir =
3567 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3568 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
3569 let expiration_date: i64 =
3570 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3571 + EXPIRATION_BUFFER_MS
3572 + 10000;
3573 let namespace1: i64 = 30;
3574 let namespace2: i64 = 45;
3575 let namespace3: i64 = 60;
3576 let entry_values1 = load_attestation_key_pool(
3577 &mut db,
3578 expiration_date,
3579 namespace1,
3580 0x01, /* base_byte */
3581 )?;
3582 let entry_values2 =
3583 load_attestation_key_pool(&mut db, expiration_date + 40000, namespace2, 0x02)?;
3584 let entry_values3 =
3585 load_attestation_key_pool(&mut db, expiration_date - 9000, namespace3, 0x03)?;
3586
3587 let blob_entry_row_count: u32 = db
3588 .conn
3589 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3590 .expect("Failed to get blob entry row count.");
3591 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3592 // one key, one certificate chain, and one certificate.
3593 assert_eq!(blob_entry_row_count, 9);
3594
3595 let mut cert_chain =
3596 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace1, &KEYSTORE_UUID)?;
3597 compare_rem_prov_values(&entry_values1, cert_chain);
3598
3599 cert_chain =
3600 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace2, &KEYSTORE_UUID)?;
3601 compare_rem_prov_values(&entry_values2, cert_chain);
3602
3603 cert_chain =
3604 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace3, &KEYSTORE_UUID)?;
3605 compare_rem_prov_values(&entry_values3, cert_chain);
3606
3607 // Give the garbage collector half a second to catch up.
3608 std::thread::sleep(Duration::from_millis(500));
3609
3610 let blob_entry_row_count: u32 = db
3611 .conn
3612 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3613 .expect("Failed to get blob entry row count.");
3614 // There shound be 9 blob entries left, because all three keys are valid with
3615 // three blobs each.
3616 assert_eq!(blob_entry_row_count, 9);
3617
3618 Ok(())
3619 }
Max Bires2b2e6562020-09-22 11:22:36 -07003620 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003621 fn test_delete_all_attestation_keys() -> Result<()> {
3622 let mut db = new_test_db()?;
3623 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3624 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003625 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003626 let result = db.delete_all_attestation_keys()?;
3627
3628 // Give the garbage collector half a second to catch up.
3629 std::thread::sleep(Duration::from_millis(500));
3630
3631 // Attestation keys should be deleted, and the regular key should remain.
3632 assert_eq!(result, 2);
3633
3634 Ok(())
3635 }
3636
3637 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003638 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003639 fn extractor(
3640 ke: &KeyEntryRow,
3641 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3642 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003643 }
3644
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003645 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003646 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3647 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003648 let entries = get_keyentry(&db)?;
3649 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003650 assert_eq!(
3651 extractor(&entries[0]),
3652 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3653 );
3654 assert_eq!(
3655 extractor(&entries[1]),
3656 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3657 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003658
3659 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003660 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003661 let entries = get_keyentry(&db)?;
3662 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003663 assert_eq!(
3664 extractor(&entries[0]),
3665 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3666 );
3667 assert_eq!(
3668 extractor(&entries[1]),
3669 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3670 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003671
3672 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003673 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003674 let entries = get_keyentry(&db)?;
3675 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003676 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3677 assert_eq!(
3678 extractor(&entries[1]),
3679 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3680 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003681
3682 // Test that we must pass in a valid Domain.
3683 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003684 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003685 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003686 );
3687 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003688 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003689 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003690 );
3691 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003692 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003693 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003694 );
3695
3696 // Test that we correctly handle setting an alias for something that does not exist.
3697 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003698 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003699 "Expected to update a single entry but instead updated 0",
3700 );
3701 // Test that we correctly abort the transaction in this case.
3702 let entries = get_keyentry(&db)?;
3703 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003704 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3705 assert_eq!(
3706 extractor(&entries[1]),
3707 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3708 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003709
3710 Ok(())
3711 }
3712
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003713 #[test]
3714 fn test_grant_ungrant() -> Result<()> {
3715 const CALLER_UID: u32 = 15;
3716 const GRANTEE_UID: u32 = 12;
3717 const SELINUX_NAMESPACE: i64 = 7;
3718
3719 let mut db = new_test_db()?;
3720 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003721 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3722 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3723 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003724 )?;
3725 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003726 domain: super::Domain::APP,
3727 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003728 alias: Some("key".to_string()),
3729 blob: None,
3730 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003731 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3732 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003733
3734 // Reset totally predictable random number generator in case we
3735 // are not the first test running on this thread.
3736 reset_random();
3737 let next_random = 0i64;
3738
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003739 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003740 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003741 assert_eq!(*a, PVEC1);
3742 assert_eq!(
3743 *k,
3744 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003745 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003746 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003747 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003748 alias: Some("key".to_string()),
3749 blob: None,
3750 }
3751 );
3752 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003753 })
3754 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755
3756 assert_eq!(
3757 app_granted_key,
3758 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003759 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003760 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003761 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003762 alias: None,
3763 blob: None,
3764 }
3765 );
3766
3767 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003768 domain: super::Domain::SELINUX,
3769 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003770 alias: Some("yek".to_string()),
3771 blob: None,
3772 };
3773
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003774 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003775 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003776 assert_eq!(*a, PVEC1);
3777 assert_eq!(
3778 *k,
3779 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003780 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003781 // namespace must be the supplied SELinux
3782 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003783 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003784 alias: Some("yek".to_string()),
3785 blob: None,
3786 }
3787 );
3788 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003789 })
3790 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003791
3792 assert_eq!(
3793 selinux_granted_key,
3794 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003795 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003796 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003797 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003798 alias: None,
3799 blob: None,
3800 }
3801 );
3802
3803 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003804 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003805 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003806 assert_eq!(*a, PVEC2);
3807 assert_eq!(
3808 *k,
3809 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003810 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003811 // namespace must be the supplied SELinux
3812 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003813 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003814 alias: Some("yek".to_string()),
3815 blob: None,
3816 }
3817 );
3818 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003819 })
3820 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003821
3822 assert_eq!(
3823 selinux_granted_key,
3824 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003825 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003826 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003827 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003828 alias: None,
3829 blob: None,
3830 }
3831 );
3832
3833 {
3834 // Limiting scope of stmt, because it borrows db.
3835 let mut stmt = db
3836 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003837 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003838 let mut rows =
3839 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3840 Ok((
3841 row.get(0)?,
3842 row.get(1)?,
3843 row.get(2)?,
3844 KeyPermSet::from(row.get::<_, i32>(3)?),
3845 ))
3846 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003847
3848 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003849 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003850 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003851 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003852 assert!(rows.next().is_none());
3853 }
3854
3855 debug_dump_keyentry_table(&mut db)?;
3856 println!("app_key {:?}", app_key);
3857 println!("selinux_key {:?}", selinux_key);
3858
Janis Danisevskis66784c42021-01-27 08:40:25 -08003859 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3860 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003861
3862 Ok(())
3863 }
3864
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003865 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003866 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3867 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3868
3869 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003870 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003871 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003872 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003873 let mut blob_metadata = BlobMetaData::new();
3874 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3875 db.set_blob(
3876 &key_id,
3877 SubComponentType::KEY_BLOB,
3878 Some(TEST_KEY_BLOB),
3879 Some(&blob_metadata),
3880 )?;
3881 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3882 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003883 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003884
3885 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003886 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003887 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003888 )?;
3889 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003890 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3891 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003892 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003893 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003894 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003895 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003896 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003897 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003898 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003899
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003900 drop(rows);
3901 drop(stmt);
3902
3903 assert_eq!(
3904 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3905 BlobMetaData::load_from_db(id, tx).no_gc()
3906 })
3907 .expect("Should find blob metadata."),
3908 blob_metadata
3909 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003910 Ok(())
3911 }
3912
3913 static TEST_ALIAS: &str = "my super duper key";
3914
3915 #[test]
3916 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3917 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003918 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003919 .context("test_insert_and_load_full_keyentry_domain_app")?
3920 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003921 let (_key_guard, key_entry) = db
3922 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003923 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003924 domain: Domain::APP,
3925 nspace: 0,
3926 alias: Some(TEST_ALIAS.to_string()),
3927 blob: None,
3928 },
3929 KeyType::Client,
3930 KeyEntryLoadBits::BOTH,
3931 1,
3932 |_k, _av| Ok(()),
3933 )
3934 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003935 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003936
3937 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003938 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003939 domain: Domain::APP,
3940 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003941 alias: Some(TEST_ALIAS.to_string()),
3942 blob: None,
3943 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003944 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003945 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003946 |_, _| Ok(()),
3947 )
3948 .unwrap();
3949
3950 assert_eq!(
3951 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3952 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003953 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003954 domain: Domain::APP,
3955 nspace: 0,
3956 alias: Some(TEST_ALIAS.to_string()),
3957 blob: None,
3958 },
3959 KeyType::Client,
3960 KeyEntryLoadBits::NONE,
3961 1,
3962 |_k, _av| Ok(()),
3963 )
3964 .unwrap_err()
3965 .root_cause()
3966 .downcast_ref::<KsError>()
3967 );
3968
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003969 Ok(())
3970 }
3971
3972 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003973 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3974 let mut db = new_test_db()?;
3975
3976 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003977 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003978 domain: Domain::APP,
3979 nspace: 1,
3980 alias: Some(TEST_ALIAS.to_string()),
3981 blob: None,
3982 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003983 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003984 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003985 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003986 )
3987 .expect("Trying to insert cert.");
3988
3989 let (_key_guard, mut key_entry) = db
3990 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003991 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003992 domain: Domain::APP,
3993 nspace: 1,
3994 alias: Some(TEST_ALIAS.to_string()),
3995 blob: None,
3996 },
3997 KeyType::Client,
3998 KeyEntryLoadBits::PUBLIC,
3999 1,
4000 |_k, _av| Ok(()),
4001 )
4002 .expect("Trying to read certificate entry.");
4003
4004 assert!(key_entry.pure_cert());
4005 assert!(key_entry.cert().is_none());
4006 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4007
4008 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004009 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004010 domain: Domain::APP,
4011 nspace: 1,
4012 alias: Some(TEST_ALIAS.to_string()),
4013 blob: None,
4014 },
4015 KeyType::Client,
4016 1,
4017 |_, _| Ok(()),
4018 )
4019 .unwrap();
4020
4021 assert_eq!(
4022 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4023 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004024 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004025 domain: Domain::APP,
4026 nspace: 1,
4027 alias: Some(TEST_ALIAS.to_string()),
4028 blob: None,
4029 },
4030 KeyType::Client,
4031 KeyEntryLoadBits::NONE,
4032 1,
4033 |_k, _av| Ok(()),
4034 )
4035 .unwrap_err()
4036 .root_cause()
4037 .downcast_ref::<KsError>()
4038 );
4039
4040 Ok(())
4041 }
4042
4043 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004044 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4045 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004046 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004047 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4048 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004049 let (_key_guard, key_entry) = db
4050 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004051 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004052 domain: Domain::SELINUX,
4053 nspace: 1,
4054 alias: Some(TEST_ALIAS.to_string()),
4055 blob: None,
4056 },
4057 KeyType::Client,
4058 KeyEntryLoadBits::BOTH,
4059 1,
4060 |_k, _av| Ok(()),
4061 )
4062 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004063 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004064
4065 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004066 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004067 domain: Domain::SELINUX,
4068 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004069 alias: Some(TEST_ALIAS.to_string()),
4070 blob: None,
4071 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004072 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004073 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004074 |_, _| Ok(()),
4075 )
4076 .unwrap();
4077
4078 assert_eq!(
4079 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4080 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004081 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004082 domain: Domain::SELINUX,
4083 nspace: 1,
4084 alias: Some(TEST_ALIAS.to_string()),
4085 blob: None,
4086 },
4087 KeyType::Client,
4088 KeyEntryLoadBits::NONE,
4089 1,
4090 |_k, _av| Ok(()),
4091 )
4092 .unwrap_err()
4093 .root_cause()
4094 .downcast_ref::<KsError>()
4095 );
4096
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004097 Ok(())
4098 }
4099
4100 #[test]
4101 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4102 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004103 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004104 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4105 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004106 let (_, key_entry) = db
4107 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004108 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004109 KeyType::Client,
4110 KeyEntryLoadBits::BOTH,
4111 1,
4112 |_k, _av| Ok(()),
4113 )
4114 .unwrap();
4115
Qi Wub9433b52020-12-01 14:52:46 +08004116 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004117
4118 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004119 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004120 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004121 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004122 |_, _| Ok(()),
4123 )
4124 .unwrap();
4125
4126 assert_eq!(
4127 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4128 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004129 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004130 KeyType::Client,
4131 KeyEntryLoadBits::NONE,
4132 1,
4133 |_k, _av| Ok(()),
4134 )
4135 .unwrap_err()
4136 .root_cause()
4137 .downcast_ref::<KsError>()
4138 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004139
4140 Ok(())
4141 }
4142
4143 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004144 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4145 let mut db = new_test_db()?;
4146 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4147 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4148 .0;
4149 // Update the usage count of the limited use key.
4150 db.check_and_update_key_usage_count(key_id)?;
4151
4152 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004153 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004154 KeyType::Client,
4155 KeyEntryLoadBits::BOTH,
4156 1,
4157 |_k, _av| Ok(()),
4158 )?;
4159
4160 // The usage count is decremented now.
4161 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4162
4163 Ok(())
4164 }
4165
4166 #[test]
4167 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4168 let mut db = new_test_db()?;
4169 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4170 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4171 .0;
4172 // Update the usage count of the limited use key.
4173 db.check_and_update_key_usage_count(key_id).expect(concat!(
4174 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4175 "This should succeed."
4176 ));
4177
4178 // Try to update the exhausted limited use key.
4179 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4180 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4181 "This should fail."
4182 ));
4183 assert_eq!(
4184 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4185 e.root_cause().downcast_ref::<KsError>().unwrap()
4186 );
4187
4188 Ok(())
4189 }
4190
4191 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004192 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4193 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004194 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004195 .context("test_insert_and_load_full_keyentry_from_grant")?
4196 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004197
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004198 let granted_key = db
4199 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004200 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004201 domain: Domain::APP,
4202 nspace: 0,
4203 alias: Some(TEST_ALIAS.to_string()),
4204 blob: None,
4205 },
4206 1,
4207 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004208 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004209 |_k, _av| Ok(()),
4210 )
4211 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004212
4213 debug_dump_grant_table(&mut db)?;
4214
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004215 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004216 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4217 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004218 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08004219 Ok(())
4220 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004221 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004222
Qi Wub9433b52020-12-01 14:52:46 +08004223 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004224
Janis Danisevskis66784c42021-01-27 08:40:25 -08004225 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004226
4227 assert_eq!(
4228 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4229 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004230 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004231 KeyType::Client,
4232 KeyEntryLoadBits::NONE,
4233 2,
4234 |_k, _av| Ok(()),
4235 )
4236 .unwrap_err()
4237 .root_cause()
4238 .downcast_ref::<KsError>()
4239 );
4240
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004241 Ok(())
4242 }
4243
Janis Danisevskis45760022021-01-19 16:34:10 -08004244 // This test attempts to load a key by key id while the caller is not the owner
4245 // but a grant exists for the given key and the caller.
4246 #[test]
4247 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4248 let mut db = new_test_db()?;
4249 const OWNER_UID: u32 = 1u32;
4250 const GRANTEE_UID: u32 = 2u32;
4251 const SOMEONE_ELSE_UID: u32 = 3u32;
4252 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4253 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4254 .0;
4255
4256 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004257 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004258 domain: Domain::APP,
4259 nspace: 0,
4260 alias: Some(TEST_ALIAS.to_string()),
4261 blob: None,
4262 },
4263 OWNER_UID,
4264 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004265 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08004266 |_k, _av| Ok(()),
4267 )
4268 .unwrap();
4269
4270 debug_dump_grant_table(&mut db)?;
4271
4272 let id_descriptor =
4273 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4274
4275 let (_, key_entry) = db
4276 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004277 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004278 KeyType::Client,
4279 KeyEntryLoadBits::BOTH,
4280 GRANTEE_UID,
4281 |k, av| {
4282 assert_eq!(Domain::APP, k.domain);
4283 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004284 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08004285 Ok(())
4286 },
4287 )
4288 .unwrap();
4289
4290 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4291
4292 let (_, key_entry) = db
4293 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004294 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004295 KeyType::Client,
4296 KeyEntryLoadBits::BOTH,
4297 SOMEONE_ELSE_UID,
4298 |k, av| {
4299 assert_eq!(Domain::APP, k.domain);
4300 assert_eq!(OWNER_UID as i64, k.nspace);
4301 assert!(av.is_none());
4302 Ok(())
4303 },
4304 )
4305 .unwrap();
4306
4307 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4308
Janis Danisevskis66784c42021-01-27 08:40:25 -08004309 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004310
4311 assert_eq!(
4312 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4313 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004314 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004315 KeyType::Client,
4316 KeyEntryLoadBits::NONE,
4317 GRANTEE_UID,
4318 |_k, _av| Ok(()),
4319 )
4320 .unwrap_err()
4321 .root_cause()
4322 .downcast_ref::<KsError>()
4323 );
4324
4325 Ok(())
4326 }
4327
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004328 // Creates a key migrates it to a different location and then tries to access it by the old
4329 // and new location.
4330 #[test]
4331 fn test_migrate_key_app_to_app() -> Result<()> {
4332 let mut db = new_test_db()?;
4333 const SOURCE_UID: u32 = 1u32;
4334 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004335 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4336 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004337 let key_id_guard =
4338 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4339 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4340
4341 let source_descriptor: KeyDescriptor = KeyDescriptor {
4342 domain: Domain::APP,
4343 nspace: -1,
4344 alias: Some(SOURCE_ALIAS.to_string()),
4345 blob: None,
4346 };
4347
4348 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4349 domain: Domain::APP,
4350 nspace: -1,
4351 alias: Some(DESTINATION_ALIAS.to_string()),
4352 blob: None,
4353 };
4354
4355 let key_id = key_id_guard.id();
4356
4357 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4358 Ok(())
4359 })
4360 .unwrap();
4361
4362 let (_, key_entry) = db
4363 .load_key_entry(
4364 &destination_descriptor,
4365 KeyType::Client,
4366 KeyEntryLoadBits::BOTH,
4367 DESTINATION_UID,
4368 |k, av| {
4369 assert_eq!(Domain::APP, k.domain);
4370 assert_eq!(DESTINATION_UID as i64, k.nspace);
4371 assert!(av.is_none());
4372 Ok(())
4373 },
4374 )
4375 .unwrap();
4376
4377 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4378
4379 assert_eq!(
4380 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4381 db.load_key_entry(
4382 &source_descriptor,
4383 KeyType::Client,
4384 KeyEntryLoadBits::NONE,
4385 SOURCE_UID,
4386 |_k, _av| Ok(()),
4387 )
4388 .unwrap_err()
4389 .root_cause()
4390 .downcast_ref::<KsError>()
4391 );
4392
4393 Ok(())
4394 }
4395
4396 // Creates a key migrates it to a different location and then tries to access it by the old
4397 // and new location.
4398 #[test]
4399 fn test_migrate_key_app_to_selinux() -> Result<()> {
4400 let mut db = new_test_db()?;
4401 const SOURCE_UID: u32 = 1u32;
4402 const DESTINATION_UID: u32 = 2u32;
4403 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004404 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4405 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004406 let key_id_guard =
4407 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4408 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4409
4410 let source_descriptor: KeyDescriptor = KeyDescriptor {
4411 domain: Domain::APP,
4412 nspace: -1,
4413 alias: Some(SOURCE_ALIAS.to_string()),
4414 blob: None,
4415 };
4416
4417 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4418 domain: Domain::SELINUX,
4419 nspace: DESTINATION_NAMESPACE,
4420 alias: Some(DESTINATION_ALIAS.to_string()),
4421 blob: None,
4422 };
4423
4424 let key_id = key_id_guard.id();
4425
4426 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4427 Ok(())
4428 })
4429 .unwrap();
4430
4431 let (_, key_entry) = db
4432 .load_key_entry(
4433 &destination_descriptor,
4434 KeyType::Client,
4435 KeyEntryLoadBits::BOTH,
4436 DESTINATION_UID,
4437 |k, av| {
4438 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00004439 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004440 assert!(av.is_none());
4441 Ok(())
4442 },
4443 )
4444 .unwrap();
4445
4446 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4447
4448 assert_eq!(
4449 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4450 db.load_key_entry(
4451 &source_descriptor,
4452 KeyType::Client,
4453 KeyEntryLoadBits::NONE,
4454 SOURCE_UID,
4455 |_k, _av| Ok(()),
4456 )
4457 .unwrap_err()
4458 .root_cause()
4459 .downcast_ref::<KsError>()
4460 );
4461
4462 Ok(())
4463 }
4464
4465 // Creates two keys and tries to migrate the first to the location of the second which
4466 // is expected to fail.
4467 #[test]
4468 fn test_migrate_key_destination_occupied() -> Result<()> {
4469 let mut db = new_test_db()?;
4470 const SOURCE_UID: u32 = 1u32;
4471 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004472 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4473 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004474 let key_id_guard =
4475 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4476 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4477 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4478 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4479
4480 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4481 domain: Domain::APP,
4482 nspace: -1,
4483 alias: Some(DESTINATION_ALIAS.to_string()),
4484 blob: None,
4485 };
4486
4487 assert_eq!(
4488 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4489 db.migrate_key_namespace(
4490 key_id_guard,
4491 &destination_descriptor,
4492 DESTINATION_UID,
4493 |_k| Ok(())
4494 )
4495 .unwrap_err()
4496 .root_cause()
4497 .downcast_ref::<KsError>()
4498 );
4499
4500 Ok(())
4501 }
4502
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004503 #[test]
4504 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004505 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4506 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4507 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004508 const UID: u32 = 33;
4509 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4510 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4511 let key_id_untouched1 =
4512 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4513 let key_id_untouched2 =
4514 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4515 let key_id_deleted =
4516 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4517
4518 let (_, key_entry) = db
4519 .load_key_entry(
4520 &KeyDescriptor {
4521 domain: Domain::APP,
4522 nspace: -1,
4523 alias: Some(ALIAS1.to_string()),
4524 blob: None,
4525 },
4526 KeyType::Client,
4527 KeyEntryLoadBits::BOTH,
4528 UID,
4529 |k, av| {
4530 assert_eq!(Domain::APP, k.domain);
4531 assert_eq!(UID as i64, k.nspace);
4532 assert!(av.is_none());
4533 Ok(())
4534 },
4535 )
4536 .unwrap();
4537 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4538 let (_, key_entry) = db
4539 .load_key_entry(
4540 &KeyDescriptor {
4541 domain: Domain::APP,
4542 nspace: -1,
4543 alias: Some(ALIAS2.to_string()),
4544 blob: None,
4545 },
4546 KeyType::Client,
4547 KeyEntryLoadBits::BOTH,
4548 UID,
4549 |k, av| {
4550 assert_eq!(Domain::APP, k.domain);
4551 assert_eq!(UID as i64, k.nspace);
4552 assert!(av.is_none());
4553 Ok(())
4554 },
4555 )
4556 .unwrap();
4557 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4558 let (_, key_entry) = db
4559 .load_key_entry(
4560 &KeyDescriptor {
4561 domain: Domain::APP,
4562 nspace: -1,
4563 alias: Some(ALIAS3.to_string()),
4564 blob: None,
4565 },
4566 KeyType::Client,
4567 KeyEntryLoadBits::BOTH,
4568 UID,
4569 |k, av| {
4570 assert_eq!(Domain::APP, k.domain);
4571 assert_eq!(UID as i64, k.nspace);
4572 assert!(av.is_none());
4573 Ok(())
4574 },
4575 )
4576 .unwrap();
4577 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4578
4579 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4580 KeystoreDB::from_0_to_1(tx).no_gc()
4581 })
4582 .unwrap();
4583
4584 let (_, key_entry) = db
4585 .load_key_entry(
4586 &KeyDescriptor {
4587 domain: Domain::APP,
4588 nspace: -1,
4589 alias: Some(ALIAS1.to_string()),
4590 blob: None,
4591 },
4592 KeyType::Client,
4593 KeyEntryLoadBits::BOTH,
4594 UID,
4595 |k, av| {
4596 assert_eq!(Domain::APP, k.domain);
4597 assert_eq!(UID as i64, k.nspace);
4598 assert!(av.is_none());
4599 Ok(())
4600 },
4601 )
4602 .unwrap();
4603 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4604 let (_, key_entry) = db
4605 .load_key_entry(
4606 &KeyDescriptor {
4607 domain: Domain::APP,
4608 nspace: -1,
4609 alias: Some(ALIAS2.to_string()),
4610 blob: None,
4611 },
4612 KeyType::Client,
4613 KeyEntryLoadBits::BOTH,
4614 UID,
4615 |k, av| {
4616 assert_eq!(Domain::APP, k.domain);
4617 assert_eq!(UID as i64, k.nspace);
4618 assert!(av.is_none());
4619 Ok(())
4620 },
4621 )
4622 .unwrap();
4623 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4624 assert_eq!(
4625 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4626 db.load_key_entry(
4627 &KeyDescriptor {
4628 domain: Domain::APP,
4629 nspace: -1,
4630 alias: Some(ALIAS3.to_string()),
4631 blob: None,
4632 },
4633 KeyType::Client,
4634 KeyEntryLoadBits::BOTH,
4635 UID,
4636 |k, av| {
4637 assert_eq!(Domain::APP, k.domain);
4638 assert_eq!(UID as i64, k.nspace);
4639 assert!(av.is_none());
4640 Ok(())
4641 },
4642 )
4643 .unwrap_err()
4644 .root_cause()
4645 .downcast_ref::<KsError>()
4646 );
4647 }
4648
Janis Danisevskisaec14592020-11-12 09:41:49 -08004649 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4650
Janis Danisevskisaec14592020-11-12 09:41:49 -08004651 #[test]
4652 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4653 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004654 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4655 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004656 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004657 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004658 .context("test_insert_and_load_full_keyentry_domain_app")?
4659 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004660 let (_key_guard, key_entry) = db
4661 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004662 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004663 domain: Domain::APP,
4664 nspace: 0,
4665 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4666 blob: None,
4667 },
4668 KeyType::Client,
4669 KeyEntryLoadBits::BOTH,
4670 33,
4671 |_k, _av| Ok(()),
4672 )
4673 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004674 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004675 let state = Arc::new(AtomicU8::new(1));
4676 let state2 = state.clone();
4677
4678 // Spawning a second thread that attempts to acquire the key id lock
4679 // for the same key as the primary thread. The primary thread then
4680 // waits, thereby forcing the secondary thread into the second stage
4681 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4682 // The test succeeds if the secondary thread observes the transition
4683 // of `state` from 1 to 2, despite having a whole second to overtake
4684 // the primary thread.
4685 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004686 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004687 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004688 assert!(db
4689 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004690 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004691 domain: Domain::APP,
4692 nspace: 0,
4693 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4694 blob: None,
4695 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004696 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004697 KeyEntryLoadBits::BOTH,
4698 33,
4699 |_k, _av| Ok(()),
4700 )
4701 .is_ok());
4702 // We should only see a 2 here because we can only return
4703 // from load_key_entry when the `_key_guard` expires,
4704 // which happens at the end of the scope.
4705 assert_eq!(2, state2.load(Ordering::Relaxed));
4706 });
4707
4708 thread::sleep(std::time::Duration::from_millis(1000));
4709
4710 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4711
4712 // Return the handle from this scope so we can join with the
4713 // secondary thread after the key id lock has expired.
4714 handle
4715 // This is where the `_key_guard` goes out of scope,
4716 // which is the reason for concurrent load_key_entry on the same key
4717 // to unblock.
4718 };
4719 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4720 // main test thread. We will not see failing asserts in secondary threads otherwise.
4721 handle.join().unwrap();
4722 Ok(())
4723 }
4724
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004725 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004726 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004727 let temp_dir =
4728 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4729
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004730 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4731 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004732
4733 let _tx1 = db1
4734 .conn
4735 .transaction_with_behavior(TransactionBehavior::Immediate)
4736 .expect("Failed to create first transaction.");
4737
4738 let error = db2
4739 .conn
4740 .transaction_with_behavior(TransactionBehavior::Immediate)
4741 .context("Transaction begin failed.")
4742 .expect_err("This should fail.");
4743 let root_cause = error.root_cause();
4744 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4745 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4746 {
4747 return;
4748 }
4749 panic!(
4750 "Unexpected error {:?} \n{:?} \n{:?}",
4751 error,
4752 root_cause,
4753 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4754 )
4755 }
4756
4757 #[cfg(disabled)]
4758 #[test]
4759 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4760 let temp_dir = Arc::new(
4761 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4762 .expect("Failed to create temp dir."),
4763 );
4764
4765 let test_begin = Instant::now();
4766
Janis Danisevskis66784c42021-01-27 08:40:25 -08004767 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004768 let mut db =
4769 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004770 const OPEN_DB_COUNT: u32 = 50u32;
4771
4772 let mut actual_key_count = KEY_COUNT;
4773 // First insert KEY_COUNT keys.
4774 for count in 0..KEY_COUNT {
4775 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4776 actual_key_count = count;
4777 break;
4778 }
4779 let alias = format!("test_alias_{}", count);
4780 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4781 .expect("Failed to make key entry.");
4782 }
4783
4784 // Insert more keys from a different thread and into a different namespace.
4785 let temp_dir1 = temp_dir.clone();
4786 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004787 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4788 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004789
4790 for count in 0..actual_key_count {
4791 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4792 return;
4793 }
4794 let alias = format!("test_alias_{}", count);
4795 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4796 .expect("Failed to make key entry.");
4797 }
4798
4799 // then unbind them again.
4800 for count in 0..actual_key_count {
4801 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4802 return;
4803 }
4804 let key = KeyDescriptor {
4805 domain: Domain::APP,
4806 nspace: -1,
4807 alias: Some(format!("test_alias_{}", count)),
4808 blob: None,
4809 };
4810 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4811 }
4812 });
4813
4814 // And start unbinding the first set of keys.
4815 let temp_dir2 = temp_dir.clone();
4816 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004817 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4818 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004819
4820 for count in 0..actual_key_count {
4821 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4822 return;
4823 }
4824 let key = KeyDescriptor {
4825 domain: Domain::APP,
4826 nspace: -1,
4827 alias: Some(format!("test_alias_{}", count)),
4828 blob: None,
4829 };
4830 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4831 }
4832 });
4833
Janis Danisevskis66784c42021-01-27 08:40:25 -08004834 // While a lot of inserting and deleting is going on we have to open database connections
4835 // successfully and use them.
4836 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4837 // out of scope.
4838 #[allow(clippy::redundant_clone)]
4839 let temp_dir4 = temp_dir.clone();
4840 let handle4 = thread::spawn(move || {
4841 for count in 0..OPEN_DB_COUNT {
4842 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4843 return;
4844 }
Seth Moore444b51a2021-06-11 09:49:49 -07004845 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4846 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004847
4848 let alias = format!("test_alias_{}", count);
4849 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4850 .expect("Failed to make key entry.");
4851 let key = KeyDescriptor {
4852 domain: Domain::APP,
4853 nspace: -1,
4854 alias: Some(alias),
4855 blob: None,
4856 };
4857 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4858 }
4859 });
4860
4861 handle1.join().expect("Thread 1 panicked.");
4862 handle2.join().expect("Thread 2 panicked.");
4863 handle4.join().expect("Thread 4 panicked.");
4864
Janis Danisevskis66784c42021-01-27 08:40:25 -08004865 Ok(())
4866 }
4867
4868 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004869 fn list() -> Result<()> {
4870 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004871 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004872 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4873 (Domain::APP, 1, "test1"),
4874 (Domain::APP, 1, "test2"),
4875 (Domain::APP, 1, "test3"),
4876 (Domain::APP, 1, "test4"),
4877 (Domain::APP, 1, "test5"),
4878 (Domain::APP, 1, "test6"),
4879 (Domain::APP, 1, "test7"),
4880 (Domain::APP, 2, "test1"),
4881 (Domain::APP, 2, "test2"),
4882 (Domain::APP, 2, "test3"),
4883 (Domain::APP, 2, "test4"),
4884 (Domain::APP, 2, "test5"),
4885 (Domain::APP, 2, "test6"),
4886 (Domain::APP, 2, "test8"),
4887 (Domain::SELINUX, 100, "test1"),
4888 (Domain::SELINUX, 100, "test2"),
4889 (Domain::SELINUX, 100, "test3"),
4890 (Domain::SELINUX, 100, "test4"),
4891 (Domain::SELINUX, 100, "test5"),
4892 (Domain::SELINUX, 100, "test6"),
4893 (Domain::SELINUX, 100, "test9"),
4894 ];
4895
4896 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4897 .iter()
4898 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004899 let entry =
4900 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004901 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4902 });
4903 (entry.id(), *ns)
4904 })
4905 .collect();
4906
4907 for (domain, namespace) in
4908 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4909 {
4910 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4911 .iter()
4912 .filter_map(|(domain, ns, alias)| match ns {
4913 ns if *ns == *namespace => Some(KeyDescriptor {
4914 domain: *domain,
4915 nspace: *ns,
4916 alias: Some(alias.to_string()),
4917 blob: None,
4918 }),
4919 _ => None,
4920 })
4921 .collect();
4922 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07004923 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004924 list_result.sort();
4925 assert_eq!(list_o_descriptors, list_result);
4926
4927 let mut list_o_ids: Vec<i64> = list_o_descriptors
4928 .into_iter()
4929 .map(|d| {
4930 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004931 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004932 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004933 KeyType::Client,
4934 KeyEntryLoadBits::NONE,
4935 *namespace as u32,
4936 |_, _| Ok(()),
4937 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004938 .unwrap();
4939 entry.id()
4940 })
4941 .collect();
4942 list_o_ids.sort_unstable();
4943 let mut loaded_entries: Vec<i64> = list_o_keys
4944 .iter()
4945 .filter_map(|(id, ns)| match ns {
4946 ns if *ns == *namespace => Some(*id),
4947 _ => None,
4948 })
4949 .collect();
4950 loaded_entries.sort_unstable();
4951 assert_eq!(list_o_ids, loaded_entries);
4952 }
Janis Danisevskis18313832021-05-17 13:30:32 -07004953 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004954
4955 Ok(())
4956 }
4957
Joel Galenson0891bc12020-07-20 10:37:03 -07004958 // Helpers
4959
4960 // Checks that the given result is an error containing the given string.
4961 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4962 let error_str = format!(
4963 "{:#?}",
4964 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4965 );
4966 assert!(
4967 error_str.contains(target),
4968 "The string \"{}\" should contain \"{}\"",
4969 error_str,
4970 target
4971 );
4972 }
4973
Joel Galenson2aab4432020-07-22 15:27:57 -07004974 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004975 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004976 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004977 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004978 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004979 namespace: Option<i64>,
4980 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004981 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004982 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004983 }
4984
4985 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4986 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004987 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004988 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004989 Ok(KeyEntryRow {
4990 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004991 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004992 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004993 namespace: row.get(3)?,
4994 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004995 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004996 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004997 })
4998 })?
4999 .map(|r| r.context("Could not read keyentry row."))
5000 .collect::<Result<Vec<_>>>()
5001 }
5002
Max Biresb2e1d032021-02-08 21:35:05 -08005003 struct RemoteProvValues {
5004 cert_chain: Vec<u8>,
5005 priv_key: Vec<u8>,
5006 batch_cert: Vec<u8>,
5007 }
5008
Max Bires2b2e6562020-09-22 11:22:36 -07005009 fn load_attestation_key_pool(
5010 db: &mut KeystoreDB,
5011 expiration_date: i64,
5012 namespace: i64,
5013 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08005014 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07005015 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
5016 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
5017 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5018 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005019 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005020 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5021 db.store_signed_attestation_certificate_chain(
5022 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005023 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005024 &cert_chain,
5025 expiration_date,
5026 &KEYSTORE_UUID,
5027 )?;
5028 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005029 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005030 }
5031
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005032 // Note: The parameters and SecurityLevel associations are nonsensical. This
5033 // collection is only used to check if the parameters are preserved as expected by the
5034 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005035 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5036 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005037 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5038 KeyParameter::new(
5039 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5040 SecurityLevel::TRUSTED_ENVIRONMENT,
5041 ),
5042 KeyParameter::new(
5043 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5044 SecurityLevel::TRUSTED_ENVIRONMENT,
5045 ),
5046 KeyParameter::new(
5047 KeyParameterValue::Algorithm(Algorithm::RSA),
5048 SecurityLevel::TRUSTED_ENVIRONMENT,
5049 ),
5050 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5051 KeyParameter::new(
5052 KeyParameterValue::BlockMode(BlockMode::ECB),
5053 SecurityLevel::TRUSTED_ENVIRONMENT,
5054 ),
5055 KeyParameter::new(
5056 KeyParameterValue::BlockMode(BlockMode::GCM),
5057 SecurityLevel::TRUSTED_ENVIRONMENT,
5058 ),
5059 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5060 KeyParameter::new(
5061 KeyParameterValue::Digest(Digest::MD5),
5062 SecurityLevel::TRUSTED_ENVIRONMENT,
5063 ),
5064 KeyParameter::new(
5065 KeyParameterValue::Digest(Digest::SHA_2_224),
5066 SecurityLevel::TRUSTED_ENVIRONMENT,
5067 ),
5068 KeyParameter::new(
5069 KeyParameterValue::Digest(Digest::SHA_2_256),
5070 SecurityLevel::STRONGBOX,
5071 ),
5072 KeyParameter::new(
5073 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5074 SecurityLevel::TRUSTED_ENVIRONMENT,
5075 ),
5076 KeyParameter::new(
5077 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5078 SecurityLevel::TRUSTED_ENVIRONMENT,
5079 ),
5080 KeyParameter::new(
5081 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5082 SecurityLevel::STRONGBOX,
5083 ),
5084 KeyParameter::new(
5085 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5086 SecurityLevel::TRUSTED_ENVIRONMENT,
5087 ),
5088 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5089 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5090 KeyParameter::new(
5091 KeyParameterValue::EcCurve(EcCurve::P_224),
5092 SecurityLevel::TRUSTED_ENVIRONMENT,
5093 ),
5094 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5095 KeyParameter::new(
5096 KeyParameterValue::EcCurve(EcCurve::P_384),
5097 SecurityLevel::TRUSTED_ENVIRONMENT,
5098 ),
5099 KeyParameter::new(
5100 KeyParameterValue::EcCurve(EcCurve::P_521),
5101 SecurityLevel::TRUSTED_ENVIRONMENT,
5102 ),
5103 KeyParameter::new(
5104 KeyParameterValue::RSAPublicExponent(3),
5105 SecurityLevel::TRUSTED_ENVIRONMENT,
5106 ),
5107 KeyParameter::new(
5108 KeyParameterValue::IncludeUniqueID,
5109 SecurityLevel::TRUSTED_ENVIRONMENT,
5110 ),
5111 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5112 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5113 KeyParameter::new(
5114 KeyParameterValue::ActiveDateTime(1234567890),
5115 SecurityLevel::STRONGBOX,
5116 ),
5117 KeyParameter::new(
5118 KeyParameterValue::OriginationExpireDateTime(1234567890),
5119 SecurityLevel::TRUSTED_ENVIRONMENT,
5120 ),
5121 KeyParameter::new(
5122 KeyParameterValue::UsageExpireDateTime(1234567890),
5123 SecurityLevel::TRUSTED_ENVIRONMENT,
5124 ),
5125 KeyParameter::new(
5126 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5127 SecurityLevel::TRUSTED_ENVIRONMENT,
5128 ),
5129 KeyParameter::new(
5130 KeyParameterValue::MaxUsesPerBoot(1234567890),
5131 SecurityLevel::TRUSTED_ENVIRONMENT,
5132 ),
5133 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5134 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5135 KeyParameter::new(
5136 KeyParameterValue::NoAuthRequired,
5137 SecurityLevel::TRUSTED_ENVIRONMENT,
5138 ),
5139 KeyParameter::new(
5140 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5141 SecurityLevel::TRUSTED_ENVIRONMENT,
5142 ),
5143 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5144 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5145 KeyParameter::new(
5146 KeyParameterValue::TrustedUserPresenceRequired,
5147 SecurityLevel::TRUSTED_ENVIRONMENT,
5148 ),
5149 KeyParameter::new(
5150 KeyParameterValue::TrustedConfirmationRequired,
5151 SecurityLevel::TRUSTED_ENVIRONMENT,
5152 ),
5153 KeyParameter::new(
5154 KeyParameterValue::UnlockedDeviceRequired,
5155 SecurityLevel::TRUSTED_ENVIRONMENT,
5156 ),
5157 KeyParameter::new(
5158 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5159 SecurityLevel::SOFTWARE,
5160 ),
5161 KeyParameter::new(
5162 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5163 SecurityLevel::SOFTWARE,
5164 ),
5165 KeyParameter::new(
5166 KeyParameterValue::CreationDateTime(12345677890),
5167 SecurityLevel::SOFTWARE,
5168 ),
5169 KeyParameter::new(
5170 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5171 SecurityLevel::TRUSTED_ENVIRONMENT,
5172 ),
5173 KeyParameter::new(
5174 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5175 SecurityLevel::TRUSTED_ENVIRONMENT,
5176 ),
5177 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5178 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5179 KeyParameter::new(
5180 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5181 SecurityLevel::SOFTWARE,
5182 ),
5183 KeyParameter::new(
5184 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5185 SecurityLevel::TRUSTED_ENVIRONMENT,
5186 ),
5187 KeyParameter::new(
5188 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5189 SecurityLevel::TRUSTED_ENVIRONMENT,
5190 ),
5191 KeyParameter::new(
5192 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5193 SecurityLevel::TRUSTED_ENVIRONMENT,
5194 ),
5195 KeyParameter::new(
5196 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5197 SecurityLevel::TRUSTED_ENVIRONMENT,
5198 ),
5199 KeyParameter::new(
5200 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5201 SecurityLevel::TRUSTED_ENVIRONMENT,
5202 ),
5203 KeyParameter::new(
5204 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5205 SecurityLevel::TRUSTED_ENVIRONMENT,
5206 ),
5207 KeyParameter::new(
5208 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5209 SecurityLevel::TRUSTED_ENVIRONMENT,
5210 ),
5211 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00005212 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5213 SecurityLevel::TRUSTED_ENVIRONMENT,
5214 ),
5215 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005216 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5217 SecurityLevel::TRUSTED_ENVIRONMENT,
5218 ),
5219 KeyParameter::new(
5220 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5221 SecurityLevel::TRUSTED_ENVIRONMENT,
5222 ),
5223 KeyParameter::new(
5224 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5225 SecurityLevel::TRUSTED_ENVIRONMENT,
5226 ),
5227 KeyParameter::new(
5228 KeyParameterValue::VendorPatchLevel(3),
5229 SecurityLevel::TRUSTED_ENVIRONMENT,
5230 ),
5231 KeyParameter::new(
5232 KeyParameterValue::BootPatchLevel(4),
5233 SecurityLevel::TRUSTED_ENVIRONMENT,
5234 ),
5235 KeyParameter::new(
5236 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5237 SecurityLevel::TRUSTED_ENVIRONMENT,
5238 ),
5239 KeyParameter::new(
5240 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5241 SecurityLevel::TRUSTED_ENVIRONMENT,
5242 ),
5243 KeyParameter::new(
5244 KeyParameterValue::MacLength(256),
5245 SecurityLevel::TRUSTED_ENVIRONMENT,
5246 ),
5247 KeyParameter::new(
5248 KeyParameterValue::ResetSinceIdRotation,
5249 SecurityLevel::TRUSTED_ENVIRONMENT,
5250 ),
5251 KeyParameter::new(
5252 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5253 SecurityLevel::TRUSTED_ENVIRONMENT,
5254 ),
Qi Wub9433b52020-12-01 14:52:46 +08005255 ];
5256 if let Some(value) = max_usage_count {
5257 params.push(KeyParameter::new(
5258 KeyParameterValue::UsageCountLimit(value),
5259 SecurityLevel::SOFTWARE,
5260 ));
5261 }
5262 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005263 }
5264
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005265 fn make_test_key_entry(
5266 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005267 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005268 namespace: i64,
5269 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005270 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005271 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005272 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005273 let mut blob_metadata = BlobMetaData::new();
5274 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5275 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5276 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5277 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5278 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5279
5280 db.set_blob(
5281 &key_id,
5282 SubComponentType::KEY_BLOB,
5283 Some(TEST_KEY_BLOB),
5284 Some(&blob_metadata),
5285 )?;
5286 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5287 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005288
5289 let params = make_test_params(max_usage_count);
5290 db.insert_keyparameter(&key_id, &params)?;
5291
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005292 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005293 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005294 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005295 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005296 Ok(key_id)
5297 }
5298
Qi Wub9433b52020-12-01 14:52:46 +08005299 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5300 let params = make_test_params(max_usage_count);
5301
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005302 let mut blob_metadata = BlobMetaData::new();
5303 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5304 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5305 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5306 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5307 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5308
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005309 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005310 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005311
5312 KeyEntry {
5313 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005314 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005315 cert: Some(TEST_CERT_BLOB.to_vec()),
5316 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005317 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005318 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005319 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005320 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005321 }
5322 }
5323
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005324 fn make_bootlevel_key_entry(
5325 db: &mut KeystoreDB,
5326 domain: Domain,
5327 namespace: i64,
5328 alias: &str,
5329 logical_only: bool,
5330 ) -> Result<KeyIdGuard> {
5331 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5332 let mut blob_metadata = BlobMetaData::new();
5333 if !logical_only {
5334 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5335 }
5336 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5337
5338 db.set_blob(
5339 &key_id,
5340 SubComponentType::KEY_BLOB,
5341 Some(TEST_KEY_BLOB),
5342 Some(&blob_metadata),
5343 )?;
5344 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5345 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5346
5347 let mut params = make_test_params(None);
5348 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5349
5350 db.insert_keyparameter(&key_id, &params)?;
5351
5352 let mut metadata = KeyMetaData::new();
5353 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5354 db.insert_key_metadata(&key_id, &metadata)?;
5355 rebind_alias(db, &key_id, alias, domain, namespace)?;
5356 Ok(key_id)
5357 }
5358
5359 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5360 let mut params = make_test_params(None);
5361 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5362
5363 let mut blob_metadata = BlobMetaData::new();
5364 if !logical_only {
5365 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5366 }
5367 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5368
5369 let mut metadata = KeyMetaData::new();
5370 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5371
5372 KeyEntry {
5373 id: key_id,
5374 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5375 cert: Some(TEST_CERT_BLOB.to_vec()),
5376 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5377 km_uuid: KEYSTORE_UUID,
5378 parameters: params,
5379 metadata,
5380 pure_cert: false,
5381 }
5382 }
5383
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005384 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005385 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005386 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005387 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005388 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005389 NO_PARAMS,
5390 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005391 Ok((
5392 row.get(0)?,
5393 row.get(1)?,
5394 row.get(2)?,
5395 row.get(3)?,
5396 row.get(4)?,
5397 row.get(5)?,
5398 row.get(6)?,
5399 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005400 },
5401 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005402
5403 println!("Key entry table rows:");
5404 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005405 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005406 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005407 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5408 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005409 );
5410 }
5411 Ok(())
5412 }
5413
5414 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005415 let mut stmt = db
5416 .conn
5417 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005418 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5419 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5420 })?;
5421
5422 println!("Grant table rows:");
5423 for r in rows {
5424 let (id, gt, ki, av) = r.unwrap();
5425 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5426 }
5427 Ok(())
5428 }
5429
Joel Galenson0891bc12020-07-20 10:37:03 -07005430 // Use a custom random number generator that repeats each number once.
5431 // This allows us to test repeated elements.
5432
5433 thread_local! {
5434 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5435 }
5436
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005437 fn reset_random() {
5438 RANDOM_COUNTER.with(|counter| {
5439 *counter.borrow_mut() = 0;
5440 })
5441 }
5442
Joel Galenson0891bc12020-07-20 10:37:03 -07005443 pub fn random() -> i64 {
5444 RANDOM_COUNTER.with(|counter| {
5445 let result = *counter.borrow() / 2;
5446 *counter.borrow_mut() += 1;
5447 result
5448 })
5449 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005450
5451 #[test]
5452 fn test_last_off_body() -> Result<()> {
5453 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005454 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005455 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005456 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005457 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005458 let one_second = Duration::from_secs(1);
5459 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005460 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005461 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005462 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005463 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005464 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005465 Ok(())
5466 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005467
5468 #[test]
5469 fn test_unbind_keys_for_user() -> Result<()> {
5470 let mut db = new_test_db()?;
5471 db.unbind_keys_for_user(1, false)?;
5472
5473 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5474 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5475 db.unbind_keys_for_user(2, false)?;
5476
Janis Danisevskis18313832021-05-17 13:30:32 -07005477 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5478 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005479
5480 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005481 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005482
5483 Ok(())
5484 }
5485
5486 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005487 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5488 let mut db = new_test_db()?;
5489 let super_key = keystore2_crypto::generate_aes256_key()?;
5490 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5491 let (encrypted_super_key, metadata) =
5492 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5493
5494 let key_name_enc = SuperKeyType {
5495 alias: "test_super_key_1",
5496 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5497 };
5498
5499 let key_name_nonenc = SuperKeyType {
5500 alias: "test_super_key_2",
5501 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5502 };
5503
5504 // Install two super keys.
5505 db.store_super_key(
5506 1,
5507 &key_name_nonenc,
5508 &super_key,
5509 &BlobMetaData::new(),
5510 &KeyMetaData::new(),
5511 )?;
5512 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5513
5514 // Check that both can be found in the database.
5515 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5516 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5517
5518 // Install the same keys for a different user.
5519 db.store_super_key(
5520 2,
5521 &key_name_nonenc,
5522 &super_key,
5523 &BlobMetaData::new(),
5524 &KeyMetaData::new(),
5525 )?;
5526 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5527
5528 // Check that the second pair of keys can be found in the database.
5529 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5530 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5531
5532 // Delete only encrypted keys.
5533 db.unbind_keys_for_user(1, true)?;
5534
5535 // The encrypted superkey should be gone now.
5536 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5537 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5538
5539 // Reinsert the encrypted key.
5540 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5541
5542 // Check that both can be found in the database, again..
5543 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5544 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5545
5546 // Delete all even unencrypted keys.
5547 db.unbind_keys_for_user(1, false)?;
5548
5549 // Both should be gone now.
5550 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5551 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5552
5553 // Check that the second pair of keys was untouched.
5554 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5555 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5556
5557 Ok(())
5558 }
5559
5560 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005561 fn test_store_super_key() -> Result<()> {
5562 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005563 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005564 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005565 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005566 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005567 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005568
5569 let (encrypted_super_key, metadata) =
5570 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005571 db.store_super_key(
5572 1,
5573 &USER_SUPER_KEY,
5574 &encrypted_super_key,
5575 &metadata,
5576 &KeyMetaData::new(),
5577 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005578
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005579 // Check if super key exists.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005580 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005581
Paul Crowley7a658392021-03-18 17:08:20 -07005582 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005583 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5584 USER_SUPER_KEY.algorithm,
5585 key_entry,
5586 &pw,
5587 None,
5588 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005589
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005590 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005591 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005592
Hasini Gunasingheda895552021-01-27 19:34:37 +00005593 Ok(())
5594 }
Seth Moore78c091f2021-04-09 21:38:30 +00005595
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005596 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005597 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005598 MetricsStorage::KEY_ENTRY,
5599 MetricsStorage::KEY_ENTRY_ID_INDEX,
5600 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5601 MetricsStorage::BLOB_ENTRY,
5602 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5603 MetricsStorage::KEY_PARAMETER,
5604 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5605 MetricsStorage::KEY_METADATA,
5606 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5607 MetricsStorage::GRANT,
5608 MetricsStorage::AUTH_TOKEN,
5609 MetricsStorage::BLOB_METADATA,
5610 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005611 ]
5612 }
5613
5614 /// Perform a simple check to ensure that we can query all the storage types
5615 /// that are supported by the DB. Check for reasonable values.
5616 #[test]
5617 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005618 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005619
5620 let mut db = new_test_db()?;
5621
5622 for t in get_valid_statsd_storage_types() {
5623 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005624 // AuthToken can be less than a page since it's in a btree, not sqlite
5625 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005626 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005627 } else {
5628 assert!(stat.size >= PAGE_SIZE);
5629 }
Seth Moore78c091f2021-04-09 21:38:30 +00005630 assert!(stat.size >= stat.unused_size);
5631 }
5632
5633 Ok(())
5634 }
5635
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005636 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005637 get_valid_statsd_storage_types()
5638 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005639 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005640 .collect()
5641 }
5642
5643 fn assert_storage_increased(
5644 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005645 increased_storage_types: Vec<MetricsStorage>,
5646 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005647 ) {
5648 for storage in increased_storage_types {
5649 // Verify the expected storage increased.
5650 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005651 let storage = storage;
5652 let old = &baseline[&storage.0];
5653 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005654 assert!(
5655 new.unused_size <= old.unused_size,
5656 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005657 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005658 new.unused_size,
5659 old.unused_size
5660 );
5661
5662 // Update the baseline with the new value so that it succeeds in the
5663 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005664 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005665 }
5666
5667 // Get an updated map of the storage and verify there were no unexpected changes.
5668 let updated_stats = get_storage_stats_map(db);
5669 assert_eq!(updated_stats.len(), baseline.len());
5670
5671 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005672 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005673 let mut s = String::new();
5674 for &k in map.keys() {
5675 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5676 .expect("string concat failed");
5677 }
5678 s
5679 };
5680
5681 assert!(
5682 updated_stats[&k].size == baseline[&k].size
5683 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5684 "updated_stats:\n{}\nbaseline:\n{}",
5685 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005686 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005687 );
5688 }
5689 }
5690
5691 #[test]
5692 fn test_verify_key_table_size_reporting() -> Result<()> {
5693 let mut db = new_test_db()?;
5694 let mut working_stats = get_storage_stats_map(&mut db);
5695
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005696 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005697 assert_storage_increased(
5698 &mut db,
5699 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005700 MetricsStorage::KEY_ENTRY,
5701 MetricsStorage::KEY_ENTRY_ID_INDEX,
5702 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005703 ],
5704 &mut working_stats,
5705 );
5706
5707 let mut blob_metadata = BlobMetaData::new();
5708 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5709 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5710 assert_storage_increased(
5711 &mut db,
5712 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005713 MetricsStorage::BLOB_ENTRY,
5714 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5715 MetricsStorage::BLOB_METADATA,
5716 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005717 ],
5718 &mut working_stats,
5719 );
5720
5721 let params = make_test_params(None);
5722 db.insert_keyparameter(&key_id, &params)?;
5723 assert_storage_increased(
5724 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005725 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005726 &mut working_stats,
5727 );
5728
5729 let mut metadata = KeyMetaData::new();
5730 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5731 db.insert_key_metadata(&key_id, &metadata)?;
5732 assert_storage_increased(
5733 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005734 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005735 &mut working_stats,
5736 );
5737
5738 let mut sum = 0;
5739 for stat in working_stats.values() {
5740 sum += stat.size;
5741 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005742 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005743 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5744
5745 Ok(())
5746 }
5747
5748 #[test]
5749 fn test_verify_auth_table_size_reporting() -> Result<()> {
5750 let mut db = new_test_db()?;
5751 let mut working_stats = get_storage_stats_map(&mut db);
5752 db.insert_auth_token(&HardwareAuthToken {
5753 challenge: 123,
5754 userId: 456,
5755 authenticatorId: 789,
5756 authenticatorType: kmhw_authenticator_type::ANY,
5757 timestamp: Timestamp { milliSeconds: 10 },
5758 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005759 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005760 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005761 Ok(())
5762 }
5763
5764 #[test]
5765 fn test_verify_grant_table_size_reporting() -> Result<()> {
5766 const OWNER: i64 = 1;
5767 let mut db = new_test_db()?;
5768 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5769
5770 let mut working_stats = get_storage_stats_map(&mut db);
5771 db.grant(
5772 &KeyDescriptor {
5773 domain: Domain::APP,
5774 nspace: 0,
5775 alias: Some(TEST_ALIAS.to_string()),
5776 blob: None,
5777 },
5778 OWNER as u32,
5779 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005780 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005781 |_, _| Ok(()),
5782 )?;
5783
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005784 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005785
5786 Ok(())
5787 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005788
5789 #[test]
5790 fn find_auth_token_entry_returns_latest() -> Result<()> {
5791 let mut db = new_test_db()?;
5792 db.insert_auth_token(&HardwareAuthToken {
5793 challenge: 123,
5794 userId: 456,
5795 authenticatorId: 789,
5796 authenticatorType: kmhw_authenticator_type::ANY,
5797 timestamp: Timestamp { milliSeconds: 10 },
5798 mac: b"mac0".to_vec(),
5799 });
5800 std::thread::sleep(std::time::Duration::from_millis(1));
5801 db.insert_auth_token(&HardwareAuthToken {
5802 challenge: 123,
5803 userId: 457,
5804 authenticatorId: 789,
5805 authenticatorType: kmhw_authenticator_type::ANY,
5806 timestamp: Timestamp { milliSeconds: 12 },
5807 mac: b"mac1".to_vec(),
5808 });
5809 std::thread::sleep(std::time::Duration::from_millis(1));
5810 db.insert_auth_token(&HardwareAuthToken {
5811 challenge: 123,
5812 userId: 458,
5813 authenticatorId: 789,
5814 authenticatorType: kmhw_authenticator_type::ANY,
5815 timestamp: Timestamp { milliSeconds: 3 },
5816 mac: b"mac2".to_vec(),
5817 });
5818 // All three entries are in the database
5819 assert_eq!(db.perboot.auth_tokens_len(), 3);
5820 // It selected the most recent timestamp
5821 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5822 Ok(())
5823 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005824
5825 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005826 fn test_load_key_descriptor() -> Result<()> {
5827 let mut db = new_test_db()?;
5828 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5829
5830 let key = db.load_key_descriptor(key_id)?.unwrap();
5831
5832 assert_eq!(key.domain, Domain::APP);
5833 assert_eq!(key.nspace, 1);
5834 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5835
5836 // No such id
5837 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5838 Ok(())
5839 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005840}