blob: ce0cb1ddf84792792cb2d850e2c694ad8f68b812 [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;
45
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080047use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070048use crate::permission::KeyPermSet;
Janis Danisevskis850d4862021-05-05 08:41:14 -070049use crate::utils::{get_current_time_in_seconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080050use crate::{
51 db_utils::{self, SqlField},
52 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070053 super_key::USER_SUPER_KEY,
54};
55use crate::{
56 error::{Error as KsError, ErrorCode, ResponseCode},
57 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080058};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080059use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080060use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070061
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080063 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080065};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070066use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070067 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070068};
Max Bires2b2e6562020-09-22 11:22:36 -070069use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
70 AttestationPoolStatus::AttestationPoolStatus,
71};
Seth Moore78c091f2021-04-09 21:38:30 +000072use statslog_rust::keystore2_storage_stats::{
73 Keystore2StorageStats, StorageType as StatsdStorageType,
74};
Max Bires2b2e6562020-09-22 11:22:36 -070075
76use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080077use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000078use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070079#[cfg(not(test))]
80use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070081use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080082 params,
83 types::FromSql,
84 types::FromSqlResult,
85 types::ToSqlOutput,
86 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080087 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070088};
Max Bires2b2e6562020-09-22 11:22:36 -070089
Janis Danisevskisaec14592020-11-12 09:41:49 -080090use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080091 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080092 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070093 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080095};
Max Bires2b2e6562020-09-22 11:22:36 -070096
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800100impl_metadata!(
101 /// A set of metadata for key entries.
102 #[derive(Debug, Default, Eq, PartialEq)]
103 pub struct KeyMetaData;
104 /// A metadata entry for key entries.
105 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
106 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800107 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800108 CreationDate(DateTime) with accessor creation_date,
109 /// Expiration date for attestation keys.
110 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700111 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
112 /// provisioning
113 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
114 /// Vector representing the raw public key so results from the server can be matched
115 /// to the right entry
116 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700117 /// SEC1 public key for ECDH encryption
118 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800119 // --- ADD NEW META DATA FIELDS HERE ---
120 // For backwards compatibility add new entries only to
121 // end of this list and above this comment.
122 };
123);
124
125impl KeyMetaData {
126 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
127 let mut stmt = tx
128 .prepare(
129 "SELECT tag, data from persistent.keymetadata
130 WHERE keyentryid = ?;",
131 )
132 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
133
134 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
135
136 let mut rows =
137 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
138 db_utils::with_rows_extract_all(&mut rows, |row| {
139 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
140 metadata.insert(
141 db_tag,
142 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
143 .context("Failed to read KeyMetaEntry.")?,
144 );
145 Ok(())
146 })
147 .context("In KeyMetaData::load_from_db.")?;
148
149 Ok(Self { data: metadata })
150 }
151
152 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
153 let mut stmt = tx
154 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000155 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800156 VALUES (?, ?, ?);",
157 )
158 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
159
160 let iter = self.data.iter();
161 for (tag, entry) in iter {
162 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
163 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
164 })?;
165 }
166 Ok(())
167 }
168}
169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170impl_metadata!(
171 /// A set of metadata for key blobs.
172 #[derive(Debug, Default, Eq, PartialEq)]
173 pub struct BlobMetaData;
174 /// A metadata entry for key blobs.
175 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
176 pub enum BlobMetaEntry {
177 /// If present, indicates that the blob is encrypted with another key or a key derived
178 /// from a password.
179 EncryptedBy(EncryptedBy) with accessor encrypted_by,
180 /// If the blob is password encrypted this field is set to the
181 /// salt used for the key derivation.
182 Salt(Vec<u8>) with accessor salt,
183 /// If the blob is encrypted, this field is set to the initialization vector.
184 Iv(Vec<u8>) with accessor iv,
185 /// If the blob is encrypted, this field holds the AEAD TAG.
186 AeadTag(Vec<u8>) with accessor aead_tag,
187 /// The uuid of the owning KeyMint instance.
188 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700189 /// If the key is ECDH encrypted, this is the ephemeral public key
190 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000191 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
192 /// of that key
193 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800194 // --- ADD NEW META DATA FIELDS HERE ---
195 // For backwards compatibility add new entries only to
196 // end of this list and above this comment.
197 };
198);
199
200impl BlobMetaData {
201 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
202 let mut stmt = tx
203 .prepare(
204 "SELECT tag, data from persistent.blobmetadata
205 WHERE blobentryid = ?;",
206 )
207 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
208
209 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
210
211 let mut rows =
212 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
213 db_utils::with_rows_extract_all(&mut rows, |row| {
214 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
215 metadata.insert(
216 db_tag,
217 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
218 .context("Failed to read BlobMetaEntry.")?,
219 );
220 Ok(())
221 })
222 .context("In BlobMetaData::load_from_db.")?;
223
224 Ok(Self { data: metadata })
225 }
226
227 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
228 let mut stmt = tx
229 .prepare(
230 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
231 VALUES (?, ?, ?);",
232 )
233 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
234
235 let iter = self.data.iter();
236 for (tag, entry) in iter {
237 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
238 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
239 })?;
240 }
241 Ok(())
242 }
243}
244
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800245/// Indicates the type of the keyentry.
246#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
247pub enum KeyType {
248 /// This is a client key type. These keys are created or imported through the Keystore 2.0
249 /// AIDL interface android.system.keystore2.
250 Client,
251 /// This is a super key type. These keys are created by keystore itself and used to encrypt
252 /// other key blobs to provide LSKF binding.
253 Super,
254 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
255 Attestation,
256}
257
258impl ToSql for KeyType {
259 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
260 Ok(ToSqlOutput::Owned(Value::Integer(match self {
261 KeyType::Client => 0,
262 KeyType::Super => 1,
263 KeyType::Attestation => 2,
264 })))
265 }
266}
267
268impl FromSql for KeyType {
269 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
270 match i64::column_result(value)? {
271 0 => Ok(KeyType::Client),
272 1 => Ok(KeyType::Super),
273 2 => Ok(KeyType::Attestation),
274 v => Err(FromSqlError::OutOfRange(v)),
275 }
276 }
277}
278
Max Bires8e93d2b2021-01-14 13:17:59 -0800279/// Uuid representation that can be stored in the database.
280/// Right now it can only be initialized from SecurityLevel.
281/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
282#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
283pub struct Uuid([u8; 16]);
284
285impl Deref for Uuid {
286 type Target = [u8; 16];
287
288 fn deref(&self) -> &Self::Target {
289 &self.0
290 }
291}
292
293impl From<SecurityLevel> for Uuid {
294 fn from(sec_level: SecurityLevel) -> Self {
295 Self((sec_level.0 as u128).to_be_bytes())
296 }
297}
298
299impl ToSql for Uuid {
300 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
301 self.0.to_sql()
302 }
303}
304
305impl FromSql for Uuid {
306 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
307 let blob = Vec::<u8>::column_result(value)?;
308 if blob.len() != 16 {
309 return Err(FromSqlError::OutOfRange(blob.len() as i64));
310 }
311 let mut arr = [0u8; 16];
312 arr.copy_from_slice(&blob);
313 Ok(Self(arr))
314 }
315}
316
317/// Key entries that are not associated with any KeyMint instance, such as pure certificate
318/// entries are associated with this UUID.
319pub static KEYSTORE_UUID: Uuid = Uuid([
320 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
321]);
322
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800323/// Indicates how the sensitive part of this key blob is encrypted.
324#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
325pub enum EncryptedBy {
326 /// The keyblob is encrypted by a user password.
327 /// In the database this variant is represented as NULL.
328 Password,
329 /// The keyblob is encrypted by another key with wrapped key id.
330 /// In the database this variant is represented as non NULL value
331 /// that is convertible to i64, typically NUMERIC.
332 KeyId(i64),
333}
334
335impl ToSql for EncryptedBy {
336 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
337 match self {
338 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
339 Self::KeyId(id) => id.to_sql(),
340 }
341 }
342}
343
344impl FromSql for EncryptedBy {
345 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
346 match value {
347 ValueRef::Null => Ok(Self::Password),
348 _ => Ok(Self::KeyId(i64::column_result(value)?)),
349 }
350 }
351}
352
353/// A database representation of wall clock time. DateTime stores unix epoch time as
354/// i64 in milliseconds.
355#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
356pub struct DateTime(i64);
357
358/// Error type returned when creating DateTime or converting it from and to
359/// SystemTime.
360#[derive(thiserror::Error, Debug)]
361pub enum DateTimeError {
362 /// This is returned when SystemTime and Duration computations fail.
363 #[error(transparent)]
364 SystemTimeError(#[from] SystemTimeError),
365
366 /// This is returned when type conversions fail.
367 #[error(transparent)]
368 TypeConversion(#[from] std::num::TryFromIntError),
369
370 /// This is returned when checked time arithmetic failed.
371 #[error("Time arithmetic failed.")]
372 TimeArithmetic,
373}
374
375impl DateTime {
376 /// Constructs a new DateTime object denoting the current time. This may fail during
377 /// conversion to unix epoch time and during conversion to the internal i64 representation.
378 pub fn now() -> Result<Self, DateTimeError> {
379 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
380 }
381
382 /// Constructs a new DateTime object from milliseconds.
383 pub fn from_millis_epoch(millis: i64) -> Self {
384 Self(millis)
385 }
386
387 /// Returns unix epoch time in milliseconds.
388 pub fn to_millis_epoch(&self) -> i64 {
389 self.0
390 }
391
392 /// Returns unix epoch time in seconds.
393 pub fn to_secs_epoch(&self) -> i64 {
394 self.0 / 1000
395 }
396}
397
398impl ToSql for DateTime {
399 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
400 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
401 }
402}
403
404impl FromSql for DateTime {
405 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
406 Ok(Self(i64::column_result(value)?))
407 }
408}
409
410impl TryInto<SystemTime> for DateTime {
411 type Error = DateTimeError;
412
413 fn try_into(self) -> Result<SystemTime, Self::Error> {
414 // We want to construct a SystemTime representation equivalent to self, denoting
415 // a point in time THEN, but we cannot set the time directly. We can only construct
416 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
417 // and between EPOCH and THEN. With this common reference we can construct the
418 // duration between NOW and THEN which we can add to our SystemTime representation
419 // of NOW to get a SystemTime representation of THEN.
420 // Durations can only be positive, thus the if statement below.
421 let now = SystemTime::now();
422 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
423 let then_epoch = Duration::from_millis(self.0.try_into()?);
424 Ok(if now_epoch > then_epoch {
425 // then = now - (now_epoch - then_epoch)
426 now_epoch
427 .checked_sub(then_epoch)
428 .and_then(|d| now.checked_sub(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 } else {
431 // then = now + (then_epoch - now_epoch)
432 then_epoch
433 .checked_sub(now_epoch)
434 .and_then(|d| now.checked_add(d))
435 .ok_or(DateTimeError::TimeArithmetic)?
436 })
437 }
438}
439
440impl TryFrom<SystemTime> for DateTime {
441 type Error = DateTimeError;
442
443 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
444 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
445 }
446}
447
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800448#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
449enum KeyLifeCycle {
450 /// Existing keys have a key ID but are not fully populated yet.
451 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
452 /// them to Unreferenced for garbage collection.
453 Existing,
454 /// A live key is fully populated and usable by clients.
455 Live,
456 /// An unreferenced key is scheduled for garbage collection.
457 Unreferenced,
458}
459
460impl ToSql for KeyLifeCycle {
461 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
462 match self {
463 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
464 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
465 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
466 }
467 }
468}
469
470impl FromSql for KeyLifeCycle {
471 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
472 match i64::column_result(value)? {
473 0 => Ok(KeyLifeCycle::Existing),
474 1 => Ok(KeyLifeCycle::Live),
475 2 => Ok(KeyLifeCycle::Unreferenced),
476 v => Err(FromSqlError::OutOfRange(v)),
477 }
478 }
479}
480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700481/// Keys have a KeyMint blob component and optional public certificate and
482/// certificate chain components.
483/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
484/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800485#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700486pub struct KeyEntryLoadBits(u32);
487
488impl KeyEntryLoadBits {
489 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
490 pub const NONE: KeyEntryLoadBits = Self(0);
491 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
492 pub const KM: KeyEntryLoadBits = Self(1);
493 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
494 pub const PUBLIC: KeyEntryLoadBits = Self(2);
495 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
496 pub const BOTH: KeyEntryLoadBits = Self(3);
497
498 /// Returns true if this object indicates that the public components shall be loaded.
499 pub const fn load_public(&self) -> bool {
500 self.0 & Self::PUBLIC.0 != 0
501 }
502
503 /// Returns true if the object indicates that the KeyMint component shall be loaded.
504 pub const fn load_km(&self) -> bool {
505 self.0 & Self::KM.0 != 0
506 }
507}
508
Janis Danisevskisaec14592020-11-12 09:41:49 -0800509lazy_static! {
510 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
511}
512
513struct KeyIdLockDb {
514 locked_keys: Mutex<HashSet<i64>>,
515 cond_var: Condvar,
516}
517
518/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
519/// from the database a second time. Most functions manipulating the key blob database
520/// require a KeyIdGuard.
521#[derive(Debug)]
522pub struct KeyIdGuard(i64);
523
524impl KeyIdLockDb {
525 fn new() -> Self {
526 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
527 }
528
529 /// This function blocks until an exclusive lock for the given key entry id can
530 /// be acquired. It returns a guard object, that represents the lifecycle of the
531 /// acquired lock.
532 pub fn get(&self, key_id: i64) -> KeyIdGuard {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 while locked_keys.contains(&key_id) {
535 locked_keys = self.cond_var.wait(locked_keys).unwrap();
536 }
537 locked_keys.insert(key_id);
538 KeyIdGuard(key_id)
539 }
540
541 /// This function attempts to acquire an exclusive lock on a given key id. If the
542 /// given key id is already taken the function returns None immediately. If a lock
543 /// can be acquired this function returns a guard object, that represents the
544 /// lifecycle of the acquired lock.
545 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
546 let mut locked_keys = self.locked_keys.lock().unwrap();
547 if locked_keys.insert(key_id) {
548 Some(KeyIdGuard(key_id))
549 } else {
550 None
551 }
552 }
553}
554
555impl KeyIdGuard {
556 /// Get the numeric key id of the locked key.
557 pub fn id(&self) -> i64 {
558 self.0
559 }
560}
561
562impl Drop for KeyIdGuard {
563 fn drop(&mut self) {
564 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
565 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800566 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800567 KEY_ID_LOCK.cond_var.notify_all();
568 }
569}
570
Max Bires8e93d2b2021-01-14 13:17:59 -0800571/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700572#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800573pub struct CertificateInfo {
574 cert: Option<Vec<u8>>,
575 cert_chain: Option<Vec<u8>>,
576}
577
578impl CertificateInfo {
579 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
580 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
581 Self { cert, cert_chain }
582 }
583
584 /// Take the cert
585 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
586 self.cert.take()
587 }
588
589 /// Take the cert chain
590 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
591 self.cert_chain.take()
592 }
593}
594
Max Bires2b2e6562020-09-22 11:22:36 -0700595/// This type represents a certificate chain with a private key corresponding to the leaf
596/// 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 -0700597pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800598 /// A KM key blob
599 pub private_key: ZVec,
600 /// A batch cert for private_key
601 pub batch_cert: Vec<u8>,
602 /// A full certificate chain from root signing authority to private_key, including batch_cert
603 /// for convenience.
604 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700605}
606
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700607/// This type represents a Keystore 2.0 key entry.
608/// An entry has a unique `id` by which it can be found in the database.
609/// It has a security level field, key parameters, and three optional fields
610/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800611#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700612pub struct KeyEntry {
613 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800614 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615 cert: Option<Vec<u8>>,
616 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800617 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700618 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800619 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800620 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700621}
622
623impl KeyEntry {
624 /// Returns the unique id of the Key entry.
625 pub fn id(&self) -> i64 {
626 self.id
627 }
628 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800629 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
630 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 /// Extracts the Optional KeyMint blob including its metadata.
633 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
634 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700635 }
636 /// Exposes the optional public certificate.
637 pub fn cert(&self) -> &Option<Vec<u8>> {
638 &self.cert
639 }
640 /// Extracts the optional public certificate.
641 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
642 self.cert.take()
643 }
644 /// Exposes the optional public certificate chain.
645 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
646 &self.cert_chain
647 }
648 /// Extracts the optional public certificate_chain.
649 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
650 self.cert_chain.take()
651 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800652 /// Returns the uuid of the owning KeyMint instance.
653 pub fn km_uuid(&self) -> &Uuid {
654 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700656 /// Exposes the key parameters of this key entry.
657 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
658 &self.parameters
659 }
660 /// Consumes this key entry and extracts the keyparameters from it.
661 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
662 self.parameters
663 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800664 /// Exposes the key metadata of this key entry.
665 pub fn metadata(&self) -> &KeyMetaData {
666 &self.metadata
667 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800668 /// This returns true if the entry is a pure certificate entry with no
669 /// private key component.
670 pub fn pure_cert(&self) -> bool {
671 self.pure_cert
672 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000673 /// Consumes this key entry and extracts the keyparameters and metadata from it.
674 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
675 (self.parameters, self.metadata)
676 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700677}
678
679/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800680#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681pub struct SubComponentType(u32);
682impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800683 /// Persistent identifier for a key blob.
684 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700685 /// Persistent identifier for a certificate blob.
686 pub const CERT: SubComponentType = Self(1);
687 /// Persistent identifier for a certificate chain blob.
688 pub const CERT_CHAIN: SubComponentType = Self(2);
689}
690
691impl ToSql for SubComponentType {
692 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
693 self.0.to_sql()
694 }
695}
696
697impl FromSql for SubComponentType {
698 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
699 Ok(Self(u32::column_result(value)?))
700 }
701}
702
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800703/// This trait is private to the database module. It is used to convey whether or not the garbage
704/// collector shall be invoked after a database access. All closures passed to
705/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
706/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
707/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
708/// `.need_gc()`.
709trait DoGc<T> {
710 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
711
712 fn no_gc(self) -> Result<(bool, T)>;
713
714 fn need_gc(self) -> Result<(bool, T)>;
715}
716
717impl<T> DoGc<T> for Result<T> {
718 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
719 self.map(|r| (need_gc, r))
720 }
721
722 fn no_gc(self) -> Result<(bool, T)> {
723 self.do_gc(false)
724 }
725
726 fn need_gc(self) -> Result<(bool, T)> {
727 self.do_gc(true)
728 }
729}
730
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700731/// KeystoreDB wraps a connection to an SQLite database and tracks its
732/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700733pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700734 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700735 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700736 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700737}
738
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000739/// Database representation of the monotonic time retrieved from the system call clock_gettime with
740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
741#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
742pub struct MonotonicRawTime(i64);
743
744impl MonotonicRawTime {
745 /// Constructs a new MonotonicRawTime
746 pub fn now() -> Self {
747 Self(get_current_time_in_seconds())
748 }
749
David Drysdale0e45a612021-02-25 17:24:36 +0000750 /// Constructs a new MonotonicRawTime from a given number of seconds.
751 pub fn from_secs(val: i64) -> Self {
752 Self(val)
753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
757 self.0
758 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800759
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000760 /// Returns the value of MonotonicRawTime in milli seconds as i64
761 pub fn milli_seconds(&self) -> i64 {
762 self.0 * 1000
763 }
764
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800765 /// Like i64::checked_sub.
766 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
767 self.0.checked_sub(other.0).map(Self)
768 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000769}
770
771impl ToSql for MonotonicRawTime {
772 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
773 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
774 }
775}
776
777impl FromSql for MonotonicRawTime {
778 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
779 Ok(Self(i64::column_result(value)?))
780 }
781}
782
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000783/// This struct encapsulates the information to be stored in the database about the auth tokens
784/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700785#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000786pub struct AuthTokenEntry {
787 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000789}
790
791impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000792 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000793 AuthTokenEntry { auth_token, time_received }
794 }
795
796 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800797 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000798 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800799 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
800 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000801 })
802 }
803
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000804 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800805 pub fn auth_token(&self) -> &HardwareAuthToken {
806 &self.auth_token
807 }
808
809 /// Returns the auth token wrapped by the AuthTokenEntry
810 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000811 self.auth_token
812 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800813
814 /// Returns the time that this auth token was received.
815 pub fn time_received(&self) -> MonotonicRawTime {
816 self.time_received
817 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000818
819 /// Returns the challenge value of the auth token.
820 pub fn challenge(&self) -> i64 {
821 self.auth_token.challenge
822 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000823}
824
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800825/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
826/// This object does not allow access to the database connection. But it keeps a database
827/// connection alive in order to keep the in memory per boot database alive.
828pub struct PerBootDbKeepAlive(Connection);
829
Joel Galenson26f4d012020-07-17 14:57:21 -0700830impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800831 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800832
Seth Moore78c091f2021-04-09 21:38:30 +0000833 /// Name of the file that holds the cross-boot persistent database.
834 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
835
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700836 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800837 /// files persistent.sqlite and perboot.sqlite in the given directory.
838 /// It also attempts to initialize all of the tables.
839 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700840 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700841 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700842 let _wp = wd::watch_millis("KeystoreDB::new", 500);
843
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800844 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800845 let mut persistent_path = db_root.to_path_buf();
Seth Moore78c091f2021-04-09 21:38:30 +0000846 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700847
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800848 // Now convert them to strings prefixed with "file:"
849 let mut persistent_path_str = "file:".to_owned();
850 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800851
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700852 let conn = Self::make_connection(&persistent_path_str)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800853
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700854 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800855 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800856 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800857 })?;
858 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700859 }
860
Janis Danisevskis66784c42021-01-27 08:40:25 -0800861 fn init_tables(tx: &Transaction) -> Result<()> {
862 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700863 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700864 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800865 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700866 domain INTEGER,
867 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800868 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800869 state INTEGER,
870 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700871 NO_PARAMS,
872 )
873 .context("Failed to initialize \"keyentry\" table.")?;
874
Janis Danisevskis66784c42021-01-27 08:40:25 -0800875 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800876 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
877 ON keyentry(id);",
878 NO_PARAMS,
879 )
880 .context("Failed to create index keyentry_id_index.")?;
881
882 tx.execute(
883 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
884 ON keyentry(domain, namespace, alias);",
885 NO_PARAMS,
886 )
887 .context("Failed to create index keyentry_domain_namespace_index.")?;
888
889 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700890 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
891 id INTEGER PRIMARY KEY,
892 subcomponent_type INTEGER,
893 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800894 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700895 NO_PARAMS,
896 )
897 .context("Failed to initialize \"blobentry\" table.")?;
898
Janis Danisevskis66784c42021-01-27 08:40:25 -0800899 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800900 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
901 ON blobentry(keyentryid);",
902 NO_PARAMS,
903 )
904 .context("Failed to create index blobentry_keyentryid_index.")?;
905
906 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800907 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
908 id INTEGER PRIMARY KEY,
909 blobentryid INTEGER,
910 tag INTEGER,
911 data ANY,
912 UNIQUE (blobentryid, tag));",
913 NO_PARAMS,
914 )
915 .context("Failed to initialize \"blobmetadata\" table.")?;
916
917 tx.execute(
918 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
919 ON blobmetadata(blobentryid);",
920 NO_PARAMS,
921 )
922 .context("Failed to create index blobmetadata_blobentryid_index.")?;
923
924 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700925 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000926 keyentryid INTEGER,
927 tag INTEGER,
928 data ANY,
929 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700930 NO_PARAMS,
931 )
932 .context("Failed to initialize \"keyparameter\" table.")?;
933
Janis Danisevskis66784c42021-01-27 08:40:25 -0800934 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800935 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
936 ON keyparameter(keyentryid);",
937 NO_PARAMS,
938 )
939 .context("Failed to create index keyparameter_keyentryid_index.")?;
940
941 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800942 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
943 keyentryid INTEGER,
944 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000945 data ANY,
946 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800947 NO_PARAMS,
948 )
949 .context("Failed to initialize \"keymetadata\" table.")?;
950
Janis Danisevskis66784c42021-01-27 08:40:25 -0800951 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800952 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
953 ON keymetadata(keyentryid);",
954 NO_PARAMS,
955 )
956 .context("Failed to create index keymetadata_keyentryid_index.")?;
957
958 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800959 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700960 id INTEGER UNIQUE,
961 grantee INTEGER,
962 keyentryid INTEGER,
963 access_vector INTEGER);",
964 NO_PARAMS,
965 )
966 .context("Failed to initialize \"grant\" table.")?;
967
Joel Galenson0891bc12020-07-20 10:37:03 -0700968 Ok(())
969 }
970
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700971 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700972 let conn =
973 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
974
Janis Danisevskis66784c42021-01-27 08:40:25 -0800975 loop {
976 if let Err(e) = conn
977 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
978 .context("Failed to attach database persistent.")
979 {
980 if Self::is_locked_error(&e) {
981 std::thread::sleep(std::time::Duration::from_micros(500));
982 continue;
983 } else {
984 return Err(e);
985 }
986 }
987 break;
988 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700989
Matthew Maurer4fb19112021-05-06 15:40:44 -0700990 // Drop the cache size from default (2M) to 0.5M
991 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
992 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -0700993
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700994 Ok(conn)
995 }
996
Seth Moore78c091f2021-04-09 21:38:30 +0000997 fn do_table_size_query(
998 &mut self,
999 storage_type: StatsdStorageType,
1000 query: &str,
1001 params: &[&str],
1002 ) -> Result<Keystore2StorageStats> {
1003 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1004 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1005 .with_context(|| {
1006 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1007 })
1008 .no_gc()
1009 })?;
1010 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1011 }
1012
1013 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1014 self.do_table_size_query(
1015 StatsdStorageType::Database,
1016 "SELECT page_count * page_size, freelist_count * page_size
1017 FROM pragma_page_count('persistent'),
1018 pragma_page_size('persistent'),
1019 persistent.pragma_freelist_count();",
1020 &[],
1021 )
1022 }
1023
1024 fn get_table_size(
1025 &mut self,
1026 storage_type: StatsdStorageType,
1027 schema: &str,
1028 table: &str,
1029 ) -> Result<Keystore2StorageStats> {
1030 self.do_table_size_query(
1031 storage_type,
1032 "SELECT pgsize,unused FROM dbstat(?1)
1033 WHERE name=?2 AND aggregate=TRUE;",
1034 &[schema, table],
1035 )
1036 }
1037
1038 /// Fetches a storage statisitics atom for a given storage type. For storage
1039 /// types that map to a table, information about the table's storage is
1040 /// returned. Requests for storage types that are not DB tables return None.
1041 pub fn get_storage_stat(
1042 &mut self,
1043 storage_type: StatsdStorageType,
1044 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001045 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1046
Seth Moore78c091f2021-04-09 21:38:30 +00001047 match storage_type {
1048 StatsdStorageType::Database => self.get_total_size(),
1049 StatsdStorageType::KeyEntry => {
1050 self.get_table_size(storage_type, "persistent", "keyentry")
1051 }
1052 StatsdStorageType::KeyEntryIdIndex => {
1053 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1054 }
1055 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1056 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1057 }
1058 StatsdStorageType::BlobEntry => {
1059 self.get_table_size(storage_type, "persistent", "blobentry")
1060 }
1061 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1062 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1063 }
1064 StatsdStorageType::KeyParameter => {
1065 self.get_table_size(storage_type, "persistent", "keyparameter")
1066 }
1067 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1068 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1069 }
1070 StatsdStorageType::KeyMetadata => {
1071 self.get_table_size(storage_type, "persistent", "keymetadata")
1072 }
1073 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1074 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1075 }
1076 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1077 StatsdStorageType::AuthToken => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001078 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1079 // reportable
1080 // Size provided is only an approximation
1081 Ok(Keystore2StorageStats {
1082 storage_type,
1083 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1084 as i64,
1085 unused_size: 0,
1086 })
Seth Moore78c091f2021-04-09 21:38:30 +00001087 }
1088 StatsdStorageType::BlobMetadata => {
1089 self.get_table_size(storage_type, "persistent", "blobmetadata")
1090 }
1091 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1092 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1093 }
1094 _ => Err(anyhow::Error::msg(format!(
1095 "Unsupported storage type: {}",
1096 storage_type as i32
1097 ))),
1098 }
1099 }
1100
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001101 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001102 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1103 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001104 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1105 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001106 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001107 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001108 blob_ids_to_delete: &[i64],
1109 max_blobs: usize,
1110 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001111 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001112 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001113 // Delete the given blobs.
1114 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001115 tx.execute(
1116 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001117 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001118 )
1119 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001120 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1121 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001122 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001123
1124 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1125
Janis Danisevskis3395f862021-05-06 10:54:17 -07001126 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1127 let result: Vec<(i64, Vec<u8>)> = {
1128 let mut stmt = tx
1129 .prepare(
1130 "SELECT id, blob FROM persistent.blobentry
1131 WHERE subcomponent_type = ?
1132 AND (
1133 id NOT IN (
1134 SELECT MAX(id) FROM persistent.blobentry
1135 WHERE subcomponent_type = ?
1136 GROUP BY keyentryid, subcomponent_type
1137 )
1138 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1139 ) LIMIT ?;",
1140 )
1141 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001142
Janis Danisevskis3395f862021-05-06 10:54:17 -07001143 let rows = stmt
1144 .query_map(
1145 params![
1146 SubComponentType::KEY_BLOB,
1147 SubComponentType::KEY_BLOB,
1148 max_blobs as i64,
1149 ],
1150 |row| Ok((row.get(0)?, row.get(1)?)),
1151 )
1152 .context("Trying to query superseded blob.")?;
1153
1154 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1155 .context("Trying to extract superseded blobs.")?
1156 };
1157
1158 let result = result
1159 .into_iter()
1160 .map(|(blob_id, blob)| {
1161 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1162 })
1163 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1164 .context("Trying to load blob metadata.")?;
1165 if !result.is_empty() {
1166 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167 }
1168
1169 // We did not find any superseded key blob, so let's remove other superseded blob in
1170 // one transaction.
1171 tx.execute(
1172 "DELETE FROM persistent.blobentry
1173 WHERE NOT subcomponent_type = ?
1174 AND (
1175 id NOT IN (
1176 SELECT MAX(id) FROM persistent.blobentry
1177 WHERE NOT subcomponent_type = ?
1178 GROUP BY keyentryid, subcomponent_type
1179 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1180 );",
1181 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1182 )
1183 .context("Trying to purge superseded blobs.")?;
1184
Janis Danisevskis3395f862021-05-06 10:54:17 -07001185 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001186 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001187 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001188 }
1189
1190 /// This maintenance function should be called only once before the database is used for the
1191 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1192 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1193 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1194 /// Keystore crashed at some point during key generation. Callers may want to log such
1195 /// occurrences.
1196 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1197 /// it to `KeyLifeCycle::Live` may have grants.
1198 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001199 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1200
Janis Danisevskis66784c42021-01-27 08:40:25 -08001201 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1202 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001203 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1204 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1205 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001206 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001207 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001208 })
1209 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001210 }
1211
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001212 /// Checks if a key exists with given key type and key descriptor properties.
1213 pub fn key_exists(
1214 &mut self,
1215 domain: Domain,
1216 nspace: i64,
1217 alias: &str,
1218 key_type: KeyType,
1219 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001220 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1221
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001222 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1223 let key_descriptor =
1224 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1225 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1226 match result {
1227 Ok(_) => Ok(true),
1228 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1229 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1230 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1231 },
1232 }
1233 .no_gc()
1234 })
1235 .context("In key_exists.")
1236 }
1237
Hasini Gunasingheda895552021-01-27 19:34:37 +00001238 /// Stores a super key in the database.
1239 pub fn store_super_key(
1240 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001241 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001242 key_type: &SuperKeyType,
1243 blob: &[u8],
1244 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001245 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001246 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001247 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1248
Hasini Gunasingheda895552021-01-27 19:34:37 +00001249 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1250 let key_id = Self::insert_with_retry(|id| {
1251 tx.execute(
1252 "INSERT into persistent.keyentry
1253 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001254 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001255 params![
1256 id,
1257 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001258 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001259 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001260 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001261 KeyLifeCycle::Live,
1262 &KEYSTORE_UUID,
1263 ],
1264 )
1265 })
1266 .context("Failed to insert into keyentry table.")?;
1267
Paul Crowley8d5b2532021-03-19 10:53:07 -07001268 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1269
Hasini Gunasingheda895552021-01-27 19:34:37 +00001270 Self::set_blob_internal(
1271 &tx,
1272 key_id,
1273 SubComponentType::KEY_BLOB,
1274 Some(blob),
1275 Some(blob_metadata),
1276 )
1277 .context("Failed to store key blob.")?;
1278
1279 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1280 .context("Trying to load key components.")
1281 .no_gc()
1282 })
1283 .context("In store_super_key.")
1284 }
1285
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001286 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001287 pub fn load_super_key(
1288 &mut self,
1289 key_type: &SuperKeyType,
1290 user_id: u32,
1291 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001292 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1293
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001294 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1295 let key_descriptor = KeyDescriptor {
1296 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001297 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001298 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001299 blob: None,
1300 };
1301 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1302 match id {
1303 Ok(id) => {
1304 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1305 .context("In load_super_key. Failed to load key entry.")?;
1306 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1307 }
1308 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1309 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1310 _ => Err(error).context("In load_super_key."),
1311 },
1312 }
1313 .no_gc()
1314 })
1315 .context("In load_super_key.")
1316 }
1317
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001318 /// Atomically loads a key entry and associated metadata or creates it using the
1319 /// callback create_new_key callback. The callback is called during a database
1320 /// transaction. This means that implementers should be mindful about using
1321 /// blocking operations such as IPC or grabbing mutexes.
1322 pub fn get_or_create_key_with<F>(
1323 &mut self,
1324 domain: Domain,
1325 namespace: i64,
1326 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001327 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001328 create_new_key: F,
1329 ) -> Result<(KeyIdGuard, KeyEntry)>
1330 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001331 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001332 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001333 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1334
Janis Danisevskis66784c42021-01-27 08:40:25 -08001335 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1336 let id = {
1337 let mut stmt = tx
1338 .prepare(
1339 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001340 WHERE
1341 key_type = ?
1342 AND domain = ?
1343 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001344 AND alias = ?
1345 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001346 )
1347 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1348 let mut rows = stmt
1349 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1350 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001351
Janis Danisevskis66784c42021-01-27 08:40:25 -08001352 db_utils::with_rows_extract_one(&mut rows, |row| {
1353 Ok(match row {
1354 Some(r) => r.get(0).context("Failed to unpack id.")?,
1355 None => None,
1356 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001357 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001358 .context("In get_or_create_key_with.")?
1359 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001360
Janis Danisevskis66784c42021-01-27 08:40:25 -08001361 let (id, entry) = match id {
1362 Some(id) => (
1363 id,
1364 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1365 .context("In get_or_create_key_with.")?,
1366 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001367
Janis Danisevskis66784c42021-01-27 08:40:25 -08001368 None => {
1369 let id = Self::insert_with_retry(|id| {
1370 tx.execute(
1371 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001372 (id, key_type, domain, namespace, alias, state, km_uuid)
1373 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001374 params![
1375 id,
1376 KeyType::Super,
1377 domain.0,
1378 namespace,
1379 alias,
1380 KeyLifeCycle::Live,
1381 km_uuid,
1382 ],
1383 )
1384 })
1385 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001386
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 let (blob, metadata) =
1388 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001389 Self::set_blob_internal(
1390 &tx,
1391 id,
1392 SubComponentType::KEY_BLOB,
1393 Some(&blob),
1394 Some(&metadata),
1395 )
Paul Crowley7a658392021-03-18 17:08:20 -07001396 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001397 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001398 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001399 KeyEntry {
1400 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001401 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001402 pure_cert: false,
1403 ..Default::default()
1404 },
1405 )
1406 }
1407 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001408 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001409 })
1410 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001411 }
1412
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001413 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001414 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1415 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001416 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1417 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001418 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001419 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001420 loop {
1421 match self
1422 .conn
1423 .transaction_with_behavior(behavior)
1424 .context("In with_transaction.")
1425 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1426 .and_then(|(result, tx)| {
1427 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1428 Ok(result)
1429 }) {
1430 Ok(result) => break Ok(result),
1431 Err(e) => {
1432 if Self::is_locked_error(&e) {
1433 std::thread::sleep(std::time::Duration::from_micros(500));
1434 continue;
1435 } else {
1436 return Err(e).context("In with_transaction.");
1437 }
1438 }
1439 }
1440 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001441 .map(|(need_gc, result)| {
1442 if need_gc {
1443 if let Some(ref gc) = self.gc {
1444 gc.notify_gc();
1445 }
1446 }
1447 result
1448 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001449 }
1450
1451 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001452 matches!(
1453 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1454 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1455 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1456 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001457 }
1458
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001459 /// Creates a new key entry and allocates a new randomized id for the new key.
1460 /// The key id gets associated with a domain and namespace but not with an alias.
1461 /// To complete key generation `rebind_alias` should be called after all of the
1462 /// key artifacts, i.e., blobs and parameters have been associated with the new
1463 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1464 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001465 pub fn create_key_entry(
1466 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001467 domain: &Domain,
1468 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001469 km_uuid: &Uuid,
1470 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001471 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1472
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001473 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001474 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001475 })
1476 .context("In create_key_entry.")
1477 }
1478
1479 fn create_key_entry_internal(
1480 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001481 domain: &Domain,
1482 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001483 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001484 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001485 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001486 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001487 _ => {
1488 return Err(KsError::sys())
1489 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1490 }
1491 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001492 Ok(KEY_ID_LOCK.get(
1493 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001494 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001495 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001496 (id, key_type, domain, namespace, alias, state, km_uuid)
1497 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001498 params![
1499 id,
1500 KeyType::Client,
1501 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001502 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001503 KeyLifeCycle::Existing,
1504 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001505 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001506 )
1507 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001508 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001509 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001510 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001511
Max Bires2b2e6562020-09-22 11:22:36 -07001512 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1513 /// The key id gets associated with a domain and namespace later but not with an alias. The
1514 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1515 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1516 /// a key.
1517 pub fn create_attestation_key_entry(
1518 &mut self,
1519 maced_public_key: &[u8],
1520 raw_public_key: &[u8],
1521 private_key: &[u8],
1522 km_uuid: &Uuid,
1523 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001524 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1525
Max Bires2b2e6562020-09-22 11:22:36 -07001526 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1527 let key_id = KEY_ID_LOCK.get(
1528 Self::insert_with_retry(|id| {
1529 tx.execute(
1530 "INSERT into persistent.keyentry
1531 (id, key_type, domain, namespace, alias, state, km_uuid)
1532 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1533 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1534 )
1535 })
1536 .context("In create_key_entry")?,
1537 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001538 Self::set_blob_internal(
1539 &tx,
1540 key_id.0,
1541 SubComponentType::KEY_BLOB,
1542 Some(private_key),
1543 None,
1544 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001545 let mut metadata = KeyMetaData::new();
1546 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1547 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1548 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001549 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001550 })
1551 .context("In create_attestation_key_entry")
1552 }
1553
Janis Danisevskis377d1002021-01-27 19:07:48 -08001554 /// Set a new blob and associates it with the given key id. Each blob
1555 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001556 /// Each key can have one of each sub component type associated. If more
1557 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001558 /// will get garbage collected.
1559 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1560 /// removed by setting blob to None.
1561 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001562 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001563 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001564 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001565 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001566 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001567 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001568 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1569
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001570 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001571 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001572 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001573 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001574 }
1575
Janis Danisevskiseed69842021-02-18 20:04:10 -08001576 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1577 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1578 /// We use this to insert key blobs into the database which can then be garbage collected
1579 /// lazily by the key garbage collector.
1580 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001581 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1582
Janis Danisevskiseed69842021-02-18 20:04:10 -08001583 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1584 Self::set_blob_internal(
1585 &tx,
1586 Self::UNASSIGNED_KEY_ID,
1587 SubComponentType::KEY_BLOB,
1588 Some(blob),
1589 Some(blob_metadata),
1590 )
1591 .need_gc()
1592 })
1593 .context("In set_deleted_blob.")
1594 }
1595
Janis Danisevskis377d1002021-01-27 19:07:48 -08001596 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001597 tx: &Transaction,
1598 key_id: i64,
1599 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001600 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001601 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001602 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001603 match (blob, sc_type) {
1604 (Some(blob), _) => {
1605 tx.execute(
1606 "INSERT INTO persistent.blobentry
1607 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1608 params![sc_type, key_id, blob],
1609 )
1610 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001611 if let Some(blob_metadata) = blob_metadata {
1612 let blob_id = tx
1613 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1614 row.get(0)
1615 })
1616 .context("In set_blob_internal: Failed to get new blob id.")?;
1617 blob_metadata
1618 .store_in_db(blob_id, tx)
1619 .context("In set_blob_internal: Trying to store blob metadata.")?;
1620 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001621 }
1622 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1623 tx.execute(
1624 "DELETE FROM persistent.blobentry
1625 WHERE subcomponent_type = ? AND keyentryid = ?;",
1626 params![sc_type, key_id],
1627 )
1628 .context("In set_blob_internal: Failed to delete blob.")?;
1629 }
1630 (None, _) => {
1631 return Err(KsError::sys())
1632 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1633 }
1634 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001635 Ok(())
1636 }
1637
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001638 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1639 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001640 #[cfg(test)]
1641 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001642 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001643 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001644 })
1645 .context("In insert_keyparameter.")
1646 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001647
Janis Danisevskis66784c42021-01-27 08:40:25 -08001648 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001649 tx: &Transaction,
1650 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001651 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001652 ) -> Result<()> {
1653 let mut stmt = tx
1654 .prepare(
1655 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1656 VALUES (?, ?, ?, ?);",
1657 )
1658 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1659
Janis Danisevskis66784c42021-01-27 08:40:25 -08001660 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001661 stmt.insert(params![
1662 key_id.0,
1663 p.get_tag().0,
1664 p.key_parameter_value(),
1665 p.security_level().0
1666 ])
1667 .with_context(|| {
1668 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1669 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001670 }
1671 Ok(())
1672 }
1673
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001674 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001675 #[cfg(test)]
1676 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001677 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001678 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001679 })
1680 .context("In insert_key_metadata.")
1681 }
1682
Max Bires2b2e6562020-09-22 11:22:36 -07001683 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1684 /// on the public key.
1685 pub fn store_signed_attestation_certificate_chain(
1686 &mut self,
1687 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001688 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001689 cert_chain: &[u8],
1690 expiration_date: i64,
1691 km_uuid: &Uuid,
1692 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001693 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1694
Max Bires2b2e6562020-09-22 11:22:36 -07001695 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1696 let mut stmt = tx
1697 .prepare(
1698 "SELECT keyentryid
1699 FROM persistent.keymetadata
1700 WHERE tag = ? AND data = ? AND keyentryid IN
1701 (SELECT id
1702 FROM persistent.keyentry
1703 WHERE
1704 alias IS NULL AND
1705 domain IS NULL AND
1706 namespace IS NULL AND
1707 key_type = ? AND
1708 km_uuid = ?);",
1709 )
1710 .context("Failed to store attestation certificate chain.")?;
1711 let mut rows = stmt
1712 .query(params![
1713 KeyMetaData::AttestationRawPubKey,
1714 raw_public_key,
1715 KeyType::Attestation,
1716 km_uuid
1717 ])
1718 .context("Failed to fetch keyid")?;
1719 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1720 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1721 .get(0)
1722 .context("Failed to unpack id.")
1723 })
1724 .context("Failed to get key_id.")?;
1725 let num_updated = tx
1726 .execute(
1727 "UPDATE persistent.keyentry
1728 SET alias = ?
1729 WHERE id = ?;",
1730 params!["signed", key_id],
1731 )
1732 .context("Failed to update alias.")?;
1733 if num_updated != 1 {
1734 return Err(KsError::sys()).context("Alias not updated for the key.");
1735 }
1736 let mut metadata = KeyMetaData::new();
1737 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1738 expiration_date,
1739 )));
1740 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001741 Self::set_blob_internal(
1742 &tx,
1743 key_id,
1744 SubComponentType::CERT_CHAIN,
1745 Some(cert_chain),
1746 None,
1747 )
1748 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001749 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1750 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001751 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001752 })
1753 .context("In store_signed_attestation_certificate_chain: ")
1754 }
1755
1756 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1757 /// currently have a key assigned to it.
1758 pub fn assign_attestation_key(
1759 &mut self,
1760 domain: Domain,
1761 namespace: i64,
1762 km_uuid: &Uuid,
1763 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001764 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1765
Max Bires2b2e6562020-09-22 11:22:36 -07001766 match domain {
1767 Domain::APP | Domain::SELINUX => {}
1768 _ => {
1769 return Err(KsError::sys()).context(format!(
1770 concat!(
1771 "In assign_attestation_key: Domain {:?} ",
1772 "must be either App or SELinux.",
1773 ),
1774 domain
1775 ));
1776 }
1777 }
1778 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1779 let result = tx
1780 .execute(
1781 "UPDATE persistent.keyentry
1782 SET domain=?1, namespace=?2
1783 WHERE
1784 id =
1785 (SELECT MIN(id)
1786 FROM persistent.keyentry
1787 WHERE ALIAS IS NOT NULL
1788 AND domain IS NULL
1789 AND key_type IS ?3
1790 AND state IS ?4
1791 AND km_uuid IS ?5)
1792 AND
1793 (SELECT COUNT(*)
1794 FROM persistent.keyentry
1795 WHERE domain=?1
1796 AND namespace=?2
1797 AND key_type IS ?3
1798 AND state IS ?4
1799 AND km_uuid IS ?5) = 0;",
1800 params![
1801 domain.0 as u32,
1802 namespace,
1803 KeyType::Attestation,
1804 KeyLifeCycle::Live,
1805 km_uuid,
1806 ],
1807 )
1808 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001809 if result == 0 {
1810 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1811 } else if result > 1 {
1812 return Err(KsError::sys())
1813 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001814 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001815 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001816 })
1817 .context("In assign_attestation_key: ")
1818 }
1819
1820 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1821 /// provisioning server, or the maximum number available if there are not num_keys number of
1822 /// entries in the table.
1823 pub fn fetch_unsigned_attestation_keys(
1824 &mut self,
1825 num_keys: i32,
1826 km_uuid: &Uuid,
1827 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001828 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1829
Max Bires2b2e6562020-09-22 11:22:36 -07001830 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1831 let mut stmt = tx
1832 .prepare(
1833 "SELECT data
1834 FROM persistent.keymetadata
1835 WHERE tag = ? AND keyentryid IN
1836 (SELECT id
1837 FROM persistent.keyentry
1838 WHERE
1839 alias IS NULL AND
1840 domain IS NULL AND
1841 namespace IS NULL AND
1842 key_type = ? AND
1843 km_uuid = ?
1844 LIMIT ?);",
1845 )
1846 .context("Failed to prepare statement")?;
1847 let rows = stmt
1848 .query_map(
1849 params![
1850 KeyMetaData::AttestationMacedPublicKey,
1851 KeyType::Attestation,
1852 km_uuid,
1853 num_keys
1854 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001855 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001856 )?
1857 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1858 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001859 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001860 })
1861 .context("In fetch_unsigned_attestation_keys")
1862 }
1863
1864 /// Removes any keys that have expired as of the current time. Returns the number of keys
1865 /// marked unreferenced that are bound to be garbage collected.
1866 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001867 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1868
Max Bires2b2e6562020-09-22 11:22:36 -07001869 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1870 let mut stmt = tx
1871 .prepare(
1872 "SELECT keyentryid, data
1873 FROM persistent.keymetadata
1874 WHERE tag = ? AND keyentryid IN
1875 (SELECT id
1876 FROM persistent.keyentry
1877 WHERE key_type = ?);",
1878 )
1879 .context("Failed to prepare query")?;
1880 let key_ids_to_check = stmt
1881 .query_map(
1882 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1883 |row| Ok((row.get(0)?, row.get(1)?)),
1884 )?
1885 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1886 .context("Failed to get date metadata")?;
1887 let curr_time = DateTime::from_millis_epoch(
1888 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1889 );
1890 let mut num_deleted = 0;
1891 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1892 if Self::mark_unreferenced(&tx, id)? {
1893 num_deleted += 1;
1894 }
1895 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001896 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001897 })
1898 .context("In delete_expired_attestation_keys: ")
1899 }
1900
Max Bires60d7ed12021-03-05 15:59:22 -08001901 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1902 /// they are in. This is useful primarily as a testing mechanism.
1903 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001904 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1905
Max Bires60d7ed12021-03-05 15:59:22 -08001906 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1907 let mut stmt = tx
1908 .prepare(
1909 "SELECT id FROM persistent.keyentry
1910 WHERE key_type IS ?;",
1911 )
1912 .context("Failed to prepare statement")?;
1913 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001914 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001915 .collect::<rusqlite::Result<Vec<i64>>>()
1916 .context("Failed to execute statement")?;
1917 let num_deleted = keys_to_delete
1918 .iter()
1919 .map(|id| Self::mark_unreferenced(&tx, *id))
1920 .collect::<Result<Vec<bool>>>()
1921 .context("Failed to execute mark_unreferenced on a keyid")?
1922 .into_iter()
1923 .filter(|result| *result)
1924 .count() as i64;
1925 Ok(num_deleted).do_gc(num_deleted != 0)
1926 })
1927 .context("In delete_all_attestation_keys: ")
1928 }
1929
Max Bires2b2e6562020-09-22 11:22:36 -07001930 /// Counts the number of keys that will expire by the provided epoch date and the number of
1931 /// keys not currently assigned to a domain.
1932 pub fn get_attestation_pool_status(
1933 &mut self,
1934 date: i64,
1935 km_uuid: &Uuid,
1936 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001937 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1938
Max Bires2b2e6562020-09-22 11:22:36 -07001939 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1940 let mut stmt = tx.prepare(
1941 "SELECT data
1942 FROM persistent.keymetadata
1943 WHERE tag = ? AND keyentryid IN
1944 (SELECT id
1945 FROM persistent.keyentry
1946 WHERE alias IS NOT NULL
1947 AND key_type = ?
1948 AND km_uuid = ?
1949 AND state = ?);",
1950 )?;
1951 let times = stmt
1952 .query_map(
1953 params![
1954 KeyMetaData::AttestationExpirationDate,
1955 KeyType::Attestation,
1956 km_uuid,
1957 KeyLifeCycle::Live
1958 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001959 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001960 )?
1961 .collect::<rusqlite::Result<Vec<DateTime>>>()
1962 .context("Failed to execute metadata statement")?;
1963 let expiring =
1964 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1965 as i32;
1966 stmt = tx.prepare(
1967 "SELECT alias, domain
1968 FROM persistent.keyentry
1969 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1970 )?;
1971 let rows = stmt
1972 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1973 Ok((row.get(0)?, row.get(1)?))
1974 })?
1975 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1976 .context("Failed to execute keyentry statement")?;
1977 let mut unassigned = 0i32;
1978 let mut attested = 0i32;
1979 let total = rows.len() as i32;
1980 for (alias, domain) in rows {
1981 match (alias, domain) {
1982 (Some(_alias), None) => {
1983 attested += 1;
1984 unassigned += 1;
1985 }
1986 (Some(_alias), Some(_domain)) => {
1987 attested += 1;
1988 }
1989 _ => {}
1990 }
1991 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001992 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001993 })
1994 .context("In get_attestation_pool_status: ")
1995 }
1996
1997 /// Fetches the private key and corresponding certificate chain assigned to a
1998 /// domain/namespace pair. Will either return nothing if the domain/namespace is
1999 /// not assigned, or one CertificateChain.
2000 pub fn retrieve_attestation_key_and_cert_chain(
2001 &mut self,
2002 domain: Domain,
2003 namespace: i64,
2004 km_uuid: &Uuid,
2005 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002006 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2007
Max Bires2b2e6562020-09-22 11:22:36 -07002008 match domain {
2009 Domain::APP | Domain::SELINUX => {}
2010 _ => {
2011 return Err(KsError::sys())
2012 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2013 }
2014 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002015 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2016 let mut stmt = tx.prepare(
2017 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002018 FROM persistent.blobentry
2019 WHERE keyentryid IN
2020 (SELECT id
2021 FROM persistent.keyentry
2022 WHERE key_type = ?
2023 AND domain = ?
2024 AND namespace = ?
2025 AND state = ?
2026 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002027 )?;
2028 let rows = stmt
2029 .query_map(
2030 params![
2031 KeyType::Attestation,
2032 domain.0 as u32,
2033 namespace,
2034 KeyLifeCycle::Live,
2035 km_uuid
2036 ],
2037 |row| Ok((row.get(0)?, row.get(1)?)),
2038 )?
2039 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002040 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002041 if rows.is_empty() {
2042 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002043 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002044 return Err(KsError::sys()).context(format!(
2045 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002046 "Expected to get a single attestation",
2047 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2048 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002049 rows.len()
2050 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002051 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002052 let mut km_blob: Vec<u8> = Vec::new();
2053 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002054 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002055 for row in rows {
2056 let sub_type: SubComponentType = row.0;
2057 match sub_type {
2058 SubComponentType::KEY_BLOB => {
2059 km_blob = row.1;
2060 }
2061 SubComponentType::CERT_CHAIN => {
2062 cert_chain_blob = row.1;
2063 }
Max Biresb2e1d032021-02-08 21:35:05 -08002064 SubComponentType::CERT => {
2065 batch_cert_blob = row.1;
2066 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002067 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2068 }
2069 }
2070 Ok(Some(CertificateChain {
2071 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002072 batch_cert: batch_cert_blob,
2073 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002074 }))
2075 .no_gc()
2076 })
Max Biresb2e1d032021-02-08 21:35:05 -08002077 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002078 }
2079
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002080 /// Updates the alias column of the given key id `newid` with the given alias,
2081 /// and atomically, removes the alias, domain, and namespace from another row
2082 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002083 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2084 /// collector.
2085 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002086 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002087 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002088 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002089 domain: &Domain,
2090 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002091 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002092 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002093 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002094 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002095 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002096 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002097 domain
2098 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002099 }
2100 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002101 let updated = tx
2102 .execute(
2103 "UPDATE persistent.keyentry
2104 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002105 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002106 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2107 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002108 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002109 let result = tx
2110 .execute(
2111 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002112 SET alias = ?, state = ?
2113 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2114 params![
2115 alias,
2116 KeyLifeCycle::Live,
2117 newid.0,
2118 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002119 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002120 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002121 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002122 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002123 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002124 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002125 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002126 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002127 result
2128 ));
2129 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002130 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002131 }
2132
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002133 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2134 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2135 pub fn migrate_key_namespace(
2136 &mut self,
2137 key_id_guard: KeyIdGuard,
2138 destination: &KeyDescriptor,
2139 caller_uid: u32,
2140 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2141 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002142 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2143
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002144 let destination = match destination.domain {
2145 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2146 Domain::SELINUX => (*destination).clone(),
2147 domain => {
2148 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2149 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2150 }
2151 };
2152
2153 // Security critical: Must return immediately on failure. Do not remove the '?';
2154 check_permission(&destination)
2155 .context("In migrate_key_namespace: Trying to check permission.")?;
2156
2157 let alias = destination
2158 .alias
2159 .as_ref()
2160 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2161 .context("In migrate_key_namespace: Alias must be specified.")?;
2162
2163 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2164 // Query the destination location. If there is a key, the migration request fails.
2165 if tx
2166 .query_row(
2167 "SELECT id FROM persistent.keyentry
2168 WHERE alias = ? AND domain = ? AND namespace = ?;",
2169 params![alias, destination.domain.0, destination.nspace],
2170 |_| Ok(()),
2171 )
2172 .optional()
2173 .context("Failed to query destination.")?
2174 .is_some()
2175 {
2176 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2177 .context("Target already exists.");
2178 }
2179
2180 let updated = tx
2181 .execute(
2182 "UPDATE persistent.keyentry
2183 SET alias = ?, domain = ?, namespace = ?
2184 WHERE id = ?;",
2185 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2186 )
2187 .context("Failed to update key entry.")?;
2188
2189 if updated != 1 {
2190 return Err(KsError::sys())
2191 .context(format!("Update succeeded, but {} rows were updated.", updated));
2192 }
2193 Ok(()).no_gc()
2194 })
2195 .context("In migrate_key_namespace:")
2196 }
2197
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002198 /// Store a new key in a single transaction.
2199 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2200 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002201 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2202 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002203 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002204 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002205 key: &KeyDescriptor,
2206 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002207 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002208 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002209 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002210 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002211 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002212 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2213
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002214 let (alias, domain, namespace) = match key {
2215 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2216 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2217 (alias, key.domain, nspace)
2218 }
2219 _ => {
2220 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2221 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2222 }
2223 };
2224 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002225 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002226 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002227 let (blob, blob_metadata) = *blob_info;
2228 Self::set_blob_internal(
2229 tx,
2230 key_id.id(),
2231 SubComponentType::KEY_BLOB,
2232 Some(blob),
2233 Some(&blob_metadata),
2234 )
2235 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002236 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002237 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002238 .context("Trying to insert the certificate.")?;
2239 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002240 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002241 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002242 tx,
2243 key_id.id(),
2244 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002245 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002246 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002247 )
2248 .context("Trying to insert the certificate chain.")?;
2249 }
2250 Self::insert_keyparameter_internal(tx, &key_id, params)
2251 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002252 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002253 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002254 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002255 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002256 })
2257 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002258 }
2259
Janis Danisevskis377d1002021-01-27 19:07:48 -08002260 /// Store a new certificate
2261 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2262 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002263 pub fn store_new_certificate(
2264 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002265 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002266 cert: &[u8],
2267 km_uuid: &Uuid,
2268 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002269 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2270
Janis Danisevskis377d1002021-01-27 19:07:48 -08002271 let (alias, domain, namespace) = match key {
2272 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2273 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2274 (alias, key.domain, nspace)
2275 }
2276 _ => {
2277 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2278 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2279 )
2280 }
2281 };
2282 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002283 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002284 .context("Trying to create new key entry.")?;
2285
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002286 Self::set_blob_internal(
2287 tx,
2288 key_id.id(),
2289 SubComponentType::CERT_CHAIN,
2290 Some(cert),
2291 None,
2292 )
2293 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002294
2295 let mut metadata = KeyMetaData::new();
2296 metadata.add(KeyMetaEntry::CreationDate(
2297 DateTime::now().context("Trying to make creation time.")?,
2298 ));
2299
2300 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2301
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002302 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002303 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002304 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002305 })
2306 .context("In store_new_certificate.")
2307 }
2308
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002309 // Helper function loading the key_id given the key descriptor
2310 // tuple comprising domain, namespace, and alias.
2311 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002312 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002313 let alias = key
2314 .alias
2315 .as_ref()
2316 .map_or_else(|| Err(KsError::sys()), Ok)
2317 .context("In load_key_entry_id: Alias must be specified.")?;
2318 let mut stmt = tx
2319 .prepare(
2320 "SELECT id FROM persistent.keyentry
2321 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002322 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002323 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002324 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002325 AND alias = ?
2326 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002327 )
2328 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2329 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002330 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002331 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002332 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002333 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002334 .get(0)
2335 .context("Failed to unpack id.")
2336 })
2337 .context("In load_key_entry_id.")
2338 }
2339
2340 /// This helper function completes the access tuple of a key, which is required
2341 /// to perform access control. The strategy depends on the `domain` field in the
2342 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002343 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002344 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002345 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002346 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002347 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002348 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002349 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002350 /// `namespace`.
2351 /// In each case the information returned is sufficient to perform the access
2352 /// check and the key id can be used to load further key artifacts.
2353 fn load_access_tuple(
2354 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002355 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002356 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002357 caller_uid: u32,
2358 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2359 match key.domain {
2360 // Domain App or SELinux. In this case we load the key_id from
2361 // the keyentry database for further loading of key components.
2362 // We already have the full access tuple to perform access control.
2363 // The only distinction is that we use the caller_uid instead
2364 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002365 // Domain::APP.
2366 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002367 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002368 if access_key.domain == Domain::APP {
2369 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002370 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002371 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002372 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002373
2374 Ok((key_id, access_key, None))
2375 }
2376
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002377 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002378 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002379 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002380 let mut stmt = tx
2381 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002382 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002383 WHERE grantee = ? AND id = ? AND
2384 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002385 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002386 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002387 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002388 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002389 .context("Domain:Grant: query failed.")?;
2390 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002391 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002392 let r =
2393 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002394 Ok((
2395 r.get(0).context("Failed to unpack key_id.")?,
2396 r.get(1).context("Failed to unpack access_vector.")?,
2397 ))
2398 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002399 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002400 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002401 }
2402
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002403 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002404 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002405 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002406 let (domain, namespace): (Domain, i64) = {
2407 let mut stmt = tx
2408 .prepare(
2409 "SELECT domain, namespace FROM persistent.keyentry
2410 WHERE
2411 id = ?
2412 AND state = ?;",
2413 )
2414 .context("Domain::KEY_ID: prepare statement failed")?;
2415 let mut rows = stmt
2416 .query(params![key.nspace, KeyLifeCycle::Live])
2417 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002418 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002419 let r =
2420 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002421 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002422 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002423 r.get(1).context("Failed to unpack namespace.")?,
2424 ))
2425 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002426 .context("Domain::KEY_ID.")?
2427 };
2428
2429 // We may use a key by id after loading it by grant.
2430 // In this case we have to check if the caller has a grant for this particular
2431 // key. We can skip this if we already know that the caller is the owner.
2432 // But we cannot know this if domain is anything but App. E.g. in the case
2433 // of Domain::SELINUX we have to speculatively check for grants because we have to
2434 // consult the SEPolicy before we know if the caller is the owner.
2435 let access_vector: Option<KeyPermSet> =
2436 if domain != Domain::APP || namespace != caller_uid as i64 {
2437 let access_vector: Option<i32> = tx
2438 .query_row(
2439 "SELECT access_vector FROM persistent.grant
2440 WHERE grantee = ? AND keyentryid = ?;",
2441 params![caller_uid as i64, key.nspace],
2442 |row| row.get(0),
2443 )
2444 .optional()
2445 .context("Domain::KEY_ID: query grant failed.")?;
2446 access_vector.map(|p| p.into())
2447 } else {
2448 None
2449 };
2450
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002451 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002452 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002453 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002454 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002455
Janis Danisevskis45760022021-01-19 16:34:10 -08002456 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002457 }
2458 _ => Err(anyhow!(KsError::sys())),
2459 }
2460 }
2461
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002462 fn load_blob_components(
2463 key_id: i64,
2464 load_bits: KeyEntryLoadBits,
2465 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002466 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002467 let mut stmt = tx
2468 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002469 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002470 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2471 )
2472 .context("In load_blob_components: prepare statement failed.")?;
2473
2474 let mut rows =
2475 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2476
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002477 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002478 let mut cert_blob: Option<Vec<u8>> = None;
2479 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002480 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002481 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002482 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002483 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002484 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002485 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2486 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002487 key_blob = Some((
2488 row.get(0).context("Failed to extract key blob id.")?,
2489 row.get(2).context("Failed to extract key blob.")?,
2490 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002491 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002492 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002493 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002494 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002495 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002496 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002497 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002498 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002499 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002500 (SubComponentType::CERT, _, _)
2501 | (SubComponentType::CERT_CHAIN, _, _)
2502 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002503 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2504 }
2505 Ok(())
2506 })
2507 .context("In load_blob_components.")?;
2508
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002509 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2510 Ok(Some((
2511 blob,
2512 BlobMetaData::load_from_db(blob_id, tx)
2513 .context("In load_blob_components: Trying to load blob_metadata.")?,
2514 )))
2515 })?;
2516
2517 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002518 }
2519
2520 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2521 let mut stmt = tx
2522 .prepare(
2523 "SELECT tag, data, security_level from persistent.keyparameter
2524 WHERE keyentryid = ?;",
2525 )
2526 .context("In load_key_parameters: prepare statement failed.")?;
2527
2528 let mut parameters: Vec<KeyParameter> = Vec::new();
2529
2530 let mut rows =
2531 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002532 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002533 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2534 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002535 parameters.push(
2536 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2537 .context("Failed to read KeyParameter.")?,
2538 );
2539 Ok(())
2540 })
2541 .context("In load_key_parameters.")?;
2542
2543 Ok(parameters)
2544 }
2545
Qi Wub9433b52020-12-01 14:52:46 +08002546 /// Decrements the usage count of a limited use key. This function first checks whether the
2547 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2548 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2549 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002550 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002551 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2552
Qi Wub9433b52020-12-01 14:52:46 +08002553 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2554 let limit: Option<i32> = tx
2555 .query_row(
2556 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2557 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2558 |row| row.get(0),
2559 )
2560 .optional()
2561 .context("Trying to load usage count")?;
2562
2563 let limit = limit
2564 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2565 .context("The Key no longer exists. Key is exhausted.")?;
2566
2567 tx.execute(
2568 "UPDATE persistent.keyparameter
2569 SET data = data - 1
2570 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2571 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2572 )
2573 .context("Failed to update key usage count.")?;
2574
2575 match limit {
2576 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002577 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002578 .context("Trying to mark limited use key for deletion."),
2579 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002580 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002581 }
2582 })
2583 .context("In check_and_update_key_usage_count.")
2584 }
2585
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002586 /// Load a key entry by the given key descriptor.
2587 /// It uses the `check_permission` callback to verify if the access is allowed
2588 /// given the key access tuple read from the database using `load_access_tuple`.
2589 /// With `load_bits` the caller may specify which blobs shall be loaded from
2590 /// the blob database.
2591 pub fn load_key_entry(
2592 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002593 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002594 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002595 load_bits: KeyEntryLoadBits,
2596 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002597 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2598 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002599 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2600
Janis Danisevskis66784c42021-01-27 08:40:25 -08002601 loop {
2602 match self.load_key_entry_internal(
2603 key,
2604 key_type,
2605 load_bits,
2606 caller_uid,
2607 &check_permission,
2608 ) {
2609 Ok(result) => break Ok(result),
2610 Err(e) => {
2611 if Self::is_locked_error(&e) {
2612 std::thread::sleep(std::time::Duration::from_micros(500));
2613 continue;
2614 } else {
2615 return Err(e).context("In load_key_entry.");
2616 }
2617 }
2618 }
2619 }
2620 }
2621
2622 fn load_key_entry_internal(
2623 &mut self,
2624 key: &KeyDescriptor,
2625 key_type: KeyType,
2626 load_bits: KeyEntryLoadBits,
2627 caller_uid: u32,
2628 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002629 ) -> Result<(KeyIdGuard, KeyEntry)> {
2630 // KEY ID LOCK 1/2
2631 // If we got a key descriptor with a key id we can get the lock right away.
2632 // Otherwise we have to defer it until we know the key id.
2633 let key_id_guard = match key.domain {
2634 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2635 _ => None,
2636 };
2637
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002638 let tx = self
2639 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002640 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002641 .context("In load_key_entry: Failed to initialize transaction.")?;
2642
2643 // Load the key_id and complete the access control tuple.
2644 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002645 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2646 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002647
2648 // Perform access control. It is vital that we return here if the permission is denied.
2649 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002650 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002651
Janis Danisevskisaec14592020-11-12 09:41:49 -08002652 // KEY ID LOCK 2/2
2653 // If we did not get a key id lock by now, it was because we got a key descriptor
2654 // without a key id. At this point we got the key id, so we can try and get a lock.
2655 // However, we cannot block here, because we are in the middle of the transaction.
2656 // So first we try to get the lock non blocking. If that fails, we roll back the
2657 // transaction and block until we get the lock. After we successfully got the lock,
2658 // we start a new transaction and load the access tuple again.
2659 //
2660 // We don't need to perform access control again, because we already established
2661 // that the caller had access to the given key. But we need to make sure that the
2662 // key id still exists. So we have to load the key entry by key id this time.
2663 let (key_id_guard, tx) = match key_id_guard {
2664 None => match KEY_ID_LOCK.try_get(key_id) {
2665 None => {
2666 // Roll back the transaction.
2667 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002668
Janis Danisevskisaec14592020-11-12 09:41:49 -08002669 // Block until we have a key id lock.
2670 let key_id_guard = KEY_ID_LOCK.get(key_id);
2671
2672 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002673 let tx = self
2674 .conn
2675 .unchecked_transaction()
2676 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002677
2678 Self::load_access_tuple(
2679 &tx,
2680 // This time we have to load the key by the retrieved key id, because the
2681 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002682 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002683 domain: Domain::KEY_ID,
2684 nspace: key_id,
2685 ..Default::default()
2686 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002687 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002688 caller_uid,
2689 )
2690 .context("In load_key_entry. (deferred key lock)")?;
2691 (key_id_guard, tx)
2692 }
2693 Some(l) => (l, tx),
2694 },
2695 Some(key_id_guard) => (key_id_guard, tx),
2696 };
2697
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002698 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2699 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002700
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002701 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2702
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002703 Ok((key_id_guard, key_entry))
2704 }
2705
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002706 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002707 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002708 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2709 .context("Trying to delete keyentry.")?;
2710 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2711 .context("Trying to delete keymetadata.")?;
2712 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2713 .context("Trying to delete keyparameters.")?;
2714 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2715 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002716 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002717 }
2718
2719 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002720 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002721 pub fn unbind_key(
2722 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002723 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002724 key_type: KeyType,
2725 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002726 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002727 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002728 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2729
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002730 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2731 let (key_id, access_key_descriptor, access_vector) =
2732 Self::load_access_tuple(tx, key, key_type, caller_uid)
2733 .context("Trying to get access tuple.")?;
2734
2735 // Perform access control. It is vital that we return here if the permission is denied.
2736 // So do not touch that '?' at the end.
2737 check_permission(&access_key_descriptor, access_vector)
2738 .context("While checking permission.")?;
2739
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002740 Self::mark_unreferenced(tx, key_id)
2741 .map(|need_gc| (need_gc, ()))
2742 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002743 })
2744 .context("In unbind_key.")
2745 }
2746
Max Bires8e93d2b2021-01-14 13:17:59 -08002747 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2748 tx.query_row(
2749 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2750 params![key_id],
2751 |row| row.get(0),
2752 )
2753 .context("In get_key_km_uuid.")
2754 }
2755
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002756 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2757 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2758 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002759 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2760
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002761 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2762 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2763 .context("In unbind_keys_for_namespace.");
2764 }
2765 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2766 tx.execute(
2767 "DELETE FROM persistent.keymetadata
2768 WHERE keyentryid IN (
2769 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002770 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002771 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002772 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002773 )
2774 .context("Trying to delete keymetadata.")?;
2775 tx.execute(
2776 "DELETE FROM persistent.keyparameter
2777 WHERE keyentryid IN (
2778 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002779 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002780 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002781 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002782 )
2783 .context("Trying to delete keyparameters.")?;
2784 tx.execute(
2785 "DELETE FROM persistent.grant
2786 WHERE keyentryid IN (
2787 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002788 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002789 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002790 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002791 )
2792 .context("Trying to delete grants.")?;
2793 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002794 "DELETE FROM persistent.keyentry
2795 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2796 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002797 )
2798 .context("Trying to delete keyentry.")?;
2799 Ok(()).need_gc()
2800 })
2801 .context("In unbind_keys_for_namespace")
2802 }
2803
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002804 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2805 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2806 {
2807 tx.execute(
2808 "DELETE FROM persistent.keymetadata
2809 WHERE keyentryid IN (
2810 SELECT id FROM persistent.keyentry
2811 WHERE state = ?
2812 );",
2813 params![KeyLifeCycle::Unreferenced],
2814 )
2815 .context("Trying to delete keymetadata.")?;
2816 tx.execute(
2817 "DELETE FROM persistent.keyparameter
2818 WHERE keyentryid IN (
2819 SELECT id FROM persistent.keyentry
2820 WHERE state = ?
2821 );",
2822 params![KeyLifeCycle::Unreferenced],
2823 )
2824 .context("Trying to delete keyparameters.")?;
2825 tx.execute(
2826 "DELETE FROM persistent.grant
2827 WHERE keyentryid IN (
2828 SELECT id FROM persistent.keyentry
2829 WHERE state = ?
2830 );",
2831 params![KeyLifeCycle::Unreferenced],
2832 )
2833 .context("Trying to delete grants.")?;
2834 tx.execute(
2835 "DELETE FROM persistent.keyentry
2836 WHERE state = ?;",
2837 params![KeyLifeCycle::Unreferenced],
2838 )
2839 .context("Trying to delete keyentry.")?;
2840 Result::<()>::Ok(())
2841 }
2842 .context("In cleanup_unreferenced")
2843 }
2844
Hasini Gunasingheda895552021-01-27 19:34:37 +00002845 /// Delete the keys created on behalf of the user, denoted by the user id.
2846 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2847 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2848 /// The caller of this function should notify the gc if the returned value is true.
2849 pub fn unbind_keys_for_user(
2850 &mut self,
2851 user_id: u32,
2852 keep_non_super_encrypted_keys: bool,
2853 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002854 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2855
Hasini Gunasingheda895552021-01-27 19:34:37 +00002856 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2857 let mut stmt = tx
2858 .prepare(&format!(
2859 "SELECT id from persistent.keyentry
2860 WHERE (
2861 key_type = ?
2862 AND domain = ?
2863 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2864 AND state = ?
2865 ) OR (
2866 key_type = ?
2867 AND namespace = ?
2868 AND alias = ?
2869 AND state = ?
2870 );",
2871 aid_user_offset = AID_USER_OFFSET
2872 ))
2873 .context(concat!(
2874 "In unbind_keys_for_user. ",
2875 "Failed to prepare the query to find the keys created by apps."
2876 ))?;
2877
2878 let mut rows = stmt
2879 .query(params![
2880 // WHERE client key:
2881 KeyType::Client,
2882 Domain::APP.0 as u32,
2883 user_id,
2884 KeyLifeCycle::Live,
2885 // OR super key:
2886 KeyType::Super,
2887 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002888 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002889 KeyLifeCycle::Live
2890 ])
2891 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2892
2893 let mut key_ids: Vec<i64> = Vec::new();
2894 db_utils::with_rows_extract_all(&mut rows, |row| {
2895 key_ids
2896 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2897 Ok(())
2898 })
2899 .context("In unbind_keys_for_user.")?;
2900
2901 let mut notify_gc = false;
2902 for key_id in key_ids {
2903 if keep_non_super_encrypted_keys {
2904 // Load metadata and filter out non-super-encrypted keys.
2905 if let (_, Some((_, blob_metadata)), _, _) =
2906 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2907 .context("In unbind_keys_for_user: Trying to load blob info.")?
2908 {
2909 if blob_metadata.encrypted_by().is_none() {
2910 continue;
2911 }
2912 }
2913 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002914 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002915 .context("In unbind_keys_for_user.")?
2916 || notify_gc;
2917 }
2918 Ok(()).do_gc(notify_gc)
2919 })
2920 .context("In unbind_keys_for_user.")
2921 }
2922
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002923 fn load_key_components(
2924 tx: &Transaction,
2925 load_bits: KeyEntryLoadBits,
2926 key_id: i64,
2927 ) -> Result<KeyEntry> {
2928 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2929
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002930 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002931 Self::load_blob_components(key_id, load_bits, &tx)
2932 .context("In load_key_components.")?;
2933
Max Bires8e93d2b2021-01-14 13:17:59 -08002934 let parameters = Self::load_key_parameters(key_id, &tx)
2935 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002936
Max Bires8e93d2b2021-01-14 13:17:59 -08002937 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2938 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002939
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002940 Ok(KeyEntry {
2941 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002942 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002943 cert: cert_blob,
2944 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002945 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002946 parameters,
2947 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002948 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002949 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002950 }
2951
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002952 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2953 /// The key descriptors will have the domain, nspace, and alias field set.
2954 /// Domain must be APP or SELINUX, the caller must make sure of that.
2955 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002956 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2957
Janis Danisevskis66784c42021-01-27 08:40:25 -08002958 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2959 let mut stmt = tx
2960 .prepare(
2961 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002962 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002963 )
2964 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002965
Janis Danisevskis66784c42021-01-27 08:40:25 -08002966 let mut rows = stmt
2967 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2968 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002969
Janis Danisevskis66784c42021-01-27 08:40:25 -08002970 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2971 db_utils::with_rows_extract_all(&mut rows, |row| {
2972 descriptors.push(KeyDescriptor {
2973 domain,
2974 nspace: namespace,
2975 alias: Some(row.get(0).context("Trying to extract alias.")?),
2976 blob: None,
2977 });
2978 Ok(())
2979 })
2980 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002981 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002982 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002983 }
2984
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002985 /// Adds a grant to the grant table.
2986 /// Like `load_key_entry` this function loads the access tuple before
2987 /// it uses the callback for a permission check. Upon success,
2988 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2989 /// grant table. The new row will have a randomized id, which is used as
2990 /// grant id in the namespace field of the resulting KeyDescriptor.
2991 pub fn grant(
2992 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002993 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002994 caller_uid: u32,
2995 grantee_uid: u32,
2996 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002997 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002998 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002999 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3000
Janis Danisevskis66784c42021-01-27 08:40:25 -08003001 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3002 // Load the key_id and complete the access control tuple.
3003 // We ignore the access vector here because grants cannot be granted.
3004 // The access vector returned here expresses the permissions the
3005 // grantee has if key.domain == Domain::GRANT. But this vector
3006 // cannot include the grant permission by design, so there is no way the
3007 // subsequent permission check can pass.
3008 // We could check key.domain == Domain::GRANT and fail early.
3009 // But even if we load the access tuple by grant here, the permission
3010 // check denies the attempt to create a grant by grant descriptor.
3011 let (key_id, access_key_descriptor, _) =
3012 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3013 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003014
Janis Danisevskis66784c42021-01-27 08:40:25 -08003015 // Perform access control. It is vital that we return here if the permission
3016 // was denied. So do not touch that '?' at the end of the line.
3017 // This permission check checks if the caller has the grant permission
3018 // for the given key and in addition to all of the permissions
3019 // expressed in `access_vector`.
3020 check_permission(&access_key_descriptor, &access_vector)
3021 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003022
Janis Danisevskis66784c42021-01-27 08:40:25 -08003023 let grant_id = if let Some(grant_id) = tx
3024 .query_row(
3025 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003026 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003027 params![key_id, grantee_uid],
3028 |row| row.get(0),
3029 )
3030 .optional()
3031 .context("In grant: Failed get optional existing grant id.")?
3032 {
3033 tx.execute(
3034 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003035 SET access_vector = ?
3036 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003037 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003038 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003039 .context("In grant: Failed to update existing grant.")?;
3040 grant_id
3041 } else {
3042 Self::insert_with_retry(|id| {
3043 tx.execute(
3044 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3045 VALUES (?, ?, ?, ?);",
3046 params![id, grantee_uid, key_id, i32::from(access_vector)],
3047 )
3048 })
3049 .context("In grant")?
3050 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003051
Janis Danisevskis66784c42021-01-27 08:40:25 -08003052 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003053 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003054 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003055 }
3056
3057 /// This function checks permissions like `grant` and `load_key_entry`
3058 /// before removing a grant from the grant table.
3059 pub fn ungrant(
3060 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003061 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003062 caller_uid: u32,
3063 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003064 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003065 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003066 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3067
Janis Danisevskis66784c42021-01-27 08:40:25 -08003068 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3069 // Load the key_id and complete the access control tuple.
3070 // We ignore the access vector here because grants cannot be granted.
3071 let (key_id, access_key_descriptor, _) =
3072 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3073 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003074
Janis Danisevskis66784c42021-01-27 08:40:25 -08003075 // Perform access control. We must return here if the permission
3076 // was denied. So do not touch the '?' at the end of this line.
3077 check_permission(&access_key_descriptor)
3078 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003079
Janis Danisevskis66784c42021-01-27 08:40:25 -08003080 tx.execute(
3081 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003082 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 params![key_id, grantee_uid],
3084 )
3085 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003086
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003087 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003088 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003089 }
3090
Joel Galenson845f74b2020-09-09 14:11:55 -07003091 // Generates a random id and passes it to the given function, which will
3092 // try to insert it into a database. If that insertion fails, retry;
3093 // otherwise return the id.
3094 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3095 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003096 let newid: i64 = match random() {
3097 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3098 i => i,
3099 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003100 match inserter(newid) {
3101 // If the id already existed, try again.
3102 Err(rusqlite::Error::SqliteFailure(
3103 libsqlite3_sys::Error {
3104 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3105 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3106 },
3107 _,
3108 )) => (),
3109 Err(e) => {
3110 return Err(e).context("In insert_with_retry: failed to insert into database.")
3111 }
3112 _ => return Ok(newid),
3113 }
3114 }
3115 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003116
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003117 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3118 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3119 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3120 auth_token.clone(),
3121 MonotonicRawTime::now(),
3122 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003123 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003124
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003125 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003126 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003127 where
3128 F: Fn(&AuthTokenEntry) -> bool,
3129 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003130 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003131 }
3132
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003133 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003134 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3135 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003136 }
3137
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003138 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003139 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3140 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003141 }
3142
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003143 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003144 fn get_last_off_body(&self) -> MonotonicRawTime {
3145 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003146 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003147}
3148
3149#[cfg(test)]
3150mod tests {
3151
3152 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003153 use crate::key_parameter::{
3154 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3155 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3156 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003157 use crate::key_perm_set;
3158 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003159 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003160 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003161 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3162 HardwareAuthToken::HardwareAuthToken,
3163 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003164 };
3165 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003166 Timestamp::Timestamp,
3167 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003168 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003169 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003170 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003171 use std::collections::BTreeMap;
3172 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003173 use std::sync::atomic::{AtomicU8, Ordering};
3174 use std::sync::Arc;
3175 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003176 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003177 #[cfg(disabled)]
3178 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003179
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003180 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003181 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003182
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003183 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003184 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003185 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003186 })?;
3187 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003188 }
3189
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003190 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3191 where
3192 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3193 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003194 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003195
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003196 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003197 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003198
Janis Danisevskis3395f862021-05-06 10:54:17 -07003199 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003200 }
3201
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003202 fn rebind_alias(
3203 db: &mut KeystoreDB,
3204 newid: &KeyIdGuard,
3205 alias: &str,
3206 domain: Domain,
3207 namespace: i64,
3208 ) -> Result<bool> {
3209 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003210 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003211 })
3212 .context("In rebind_alias.")
3213 }
3214
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003215 #[test]
3216 fn datetime() -> Result<()> {
3217 let conn = Connection::open_in_memory()?;
3218 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3219 let now = SystemTime::now();
3220 let duration = Duration::from_secs(1000);
3221 let then = now.checked_sub(duration).unwrap();
3222 let soon = now.checked_add(duration).unwrap();
3223 conn.execute(
3224 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3225 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3226 )?;
3227 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3228 let mut rows = stmt.query(NO_PARAMS)?;
3229 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3230 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3231 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3232 assert!(rows.next()?.is_none());
3233 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3234 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3235 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3236 Ok(())
3237 }
3238
Joel Galenson0891bc12020-07-20 10:37:03 -07003239 // Ensure that we're using the "injected" random function, not the real one.
3240 #[test]
3241 fn test_mocked_random() {
3242 let rand1 = random();
3243 let rand2 = random();
3244 let rand3 = random();
3245 if rand1 == rand2 {
3246 assert_eq!(rand2 + 1, rand3);
3247 } else {
3248 assert_eq!(rand1 + 1, rand2);
3249 assert_eq!(rand2, rand3);
3250 }
3251 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003252
Joel Galenson26f4d012020-07-17 14:57:21 -07003253 // Test that we have the correct tables.
3254 #[test]
3255 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003256 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003257 let tables = db
3258 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003259 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003260 .query_map(params![], |row| row.get(0))?
3261 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003262 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003263 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003264 assert_eq!(tables[1], "blobmetadata");
3265 assert_eq!(tables[2], "grant");
3266 assert_eq!(tables[3], "keyentry");
3267 assert_eq!(tables[4], "keymetadata");
3268 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003269 Ok(())
3270 }
3271
3272 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003273 fn test_auth_token_table_invariant() -> Result<()> {
3274 let mut db = new_test_db()?;
3275 let auth_token1 = HardwareAuthToken {
3276 challenge: i64::MAX,
3277 userId: 200,
3278 authenticatorId: 200,
3279 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3280 timestamp: Timestamp { milliSeconds: 500 },
3281 mac: String::from("mac").into_bytes(),
3282 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003283 db.insert_auth_token(&auth_token1);
3284 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003285 assert_eq!(auth_tokens_returned.len(), 1);
3286
3287 // insert another auth token with the same values for the columns in the UNIQUE constraint
3288 // of the auth token table and different value for timestamp
3289 let auth_token2 = HardwareAuthToken {
3290 challenge: i64::MAX,
3291 userId: 200,
3292 authenticatorId: 200,
3293 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3294 timestamp: Timestamp { milliSeconds: 600 },
3295 mac: String::from("mac").into_bytes(),
3296 };
3297
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003298 db.insert_auth_token(&auth_token2);
3299 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003300 assert_eq!(auth_tokens_returned.len(), 1);
3301
3302 if let Some(auth_token) = auth_tokens_returned.pop() {
3303 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3304 }
3305
3306 // insert another auth token with the different values for the columns in the UNIQUE
3307 // constraint of the auth token table
3308 let auth_token3 = HardwareAuthToken {
3309 challenge: i64::MAX,
3310 userId: 201,
3311 authenticatorId: 200,
3312 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3313 timestamp: Timestamp { milliSeconds: 600 },
3314 mac: String::from("mac").into_bytes(),
3315 };
3316
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003317 db.insert_auth_token(&auth_token3);
3318 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003319 assert_eq!(auth_tokens_returned.len(), 2);
3320
3321 Ok(())
3322 }
3323
3324 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003325 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3326 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003327 }
3328
3329 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003330 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003331 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003332 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003333
Janis Danisevskis66784c42021-01-27 08:40:25 -08003334 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003335 let entries = get_keyentry(&db)?;
3336 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003337
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003338 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003339
3340 let entries_new = get_keyentry(&db)?;
3341 assert_eq!(entries, entries_new);
3342 Ok(())
3343 }
3344
3345 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003346 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003347 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3348 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003349 }
3350
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003351 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003352
Janis Danisevskis66784c42021-01-27 08:40:25 -08003353 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3354 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003355
3356 let entries = get_keyentry(&db)?;
3357 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003358 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3359 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003360
3361 // Test that we must pass in a valid Domain.
3362 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003363 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003364 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003365 );
3366 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003367 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003368 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003369 );
3370 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003371 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003372 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003373 );
3374
3375 Ok(())
3376 }
3377
Joel Galenson33c04ad2020-08-03 11:04:38 -07003378 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003379 fn test_add_unsigned_key() -> Result<()> {
3380 let mut db = new_test_db()?;
3381 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3382 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3383 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3384 db.create_attestation_key_entry(
3385 &public_key,
3386 &raw_public_key,
3387 &private_key,
3388 &KEYSTORE_UUID,
3389 )?;
3390 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3391 assert_eq!(keys.len(), 1);
3392 assert_eq!(keys[0], public_key);
3393 Ok(())
3394 }
3395
3396 #[test]
3397 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3398 let mut db = new_test_db()?;
3399 let expiration_date: i64 = 20;
3400 let namespace: i64 = 30;
3401 let base_byte: u8 = 1;
3402 let loaded_values =
3403 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3404 let chain =
3405 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3406 assert_eq!(true, chain.is_some());
3407 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003408 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003409 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3410 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003411 Ok(())
3412 }
3413
3414 #[test]
3415 fn test_get_attestation_pool_status() -> Result<()> {
3416 let mut db = new_test_db()?;
3417 let namespace: i64 = 30;
3418 load_attestation_key_pool(
3419 &mut db, 10, /* expiration */
3420 namespace, 0x01, /* base_byte */
3421 )?;
3422 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3423 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3424 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3425 assert_eq!(status.expiring, 0);
3426 assert_eq!(status.attested, 3);
3427 assert_eq!(status.unassigned, 0);
3428 assert_eq!(status.total, 3);
3429 assert_eq!(
3430 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3431 1
3432 );
3433 assert_eq!(
3434 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3435 2
3436 );
3437 assert_eq!(
3438 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3439 3
3440 );
3441 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3442 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3443 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3444 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003445 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003446 db.create_attestation_key_entry(
3447 &public_key,
3448 &raw_public_key,
3449 &private_key,
3450 &KEYSTORE_UUID,
3451 )?;
3452 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3453 assert_eq!(status.attested, 3);
3454 assert_eq!(status.unassigned, 0);
3455 assert_eq!(status.total, 4);
3456 db.store_signed_attestation_certificate_chain(
3457 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003458 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003459 &cert_chain,
3460 20,
3461 &KEYSTORE_UUID,
3462 )?;
3463 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3464 assert_eq!(status.attested, 4);
3465 assert_eq!(status.unassigned, 1);
3466 assert_eq!(status.total, 4);
3467 Ok(())
3468 }
3469
3470 #[test]
3471 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003472 let temp_dir =
3473 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3474 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003475 let expiration_date: i64 =
3476 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3477 let namespace: i64 = 30;
3478 let namespace_del1: i64 = 45;
3479 let namespace_del2: i64 = 60;
3480 let entry_values = load_attestation_key_pool(
3481 &mut db,
3482 expiration_date,
3483 namespace,
3484 0x01, /* base_byte */
3485 )?;
3486 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3487 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003488
3489 let blob_entry_row_count: u32 = db
3490 .conn
3491 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3492 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003493 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3494 // one key, one certificate chain, and one certificate.
3495 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003496
Max Bires2b2e6562020-09-22 11:22:36 -07003497 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3498
3499 let mut cert_chain =
3500 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003501 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003502 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003503 assert_eq!(entry_values.batch_cert, value.batch_cert);
3504 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003505 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003506
3507 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3508 Domain::APP,
3509 namespace_del1,
3510 &KEYSTORE_UUID,
3511 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003512 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003513 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3514 Domain::APP,
3515 namespace_del2,
3516 &KEYSTORE_UUID,
3517 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003518 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003519
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003520 // Give the garbage collector half a second to catch up.
3521 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003522
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003523 let blob_entry_row_count: u32 = db
3524 .conn
3525 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3526 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003527 // There shound be 3 blob entries left, because we deleted two of the attestation
3528 // key entries with three blobs each.
3529 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003530
Max Bires2b2e6562020-09-22 11:22:36 -07003531 Ok(())
3532 }
3533
3534 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003535 fn test_delete_all_attestation_keys() -> Result<()> {
3536 let mut db = new_test_db()?;
3537 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3538 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3539 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3540 let result = db.delete_all_attestation_keys()?;
3541
3542 // Give the garbage collector half a second to catch up.
3543 std::thread::sleep(Duration::from_millis(500));
3544
3545 // Attestation keys should be deleted, and the regular key should remain.
3546 assert_eq!(result, 2);
3547
3548 Ok(())
3549 }
3550
3551 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003552 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003553 fn extractor(
3554 ke: &KeyEntryRow,
3555 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3556 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003557 }
3558
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003559 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003560 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3561 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003562 let entries = get_keyentry(&db)?;
3563 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003564 assert_eq!(
3565 extractor(&entries[0]),
3566 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3567 );
3568 assert_eq!(
3569 extractor(&entries[1]),
3570 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3571 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003572
3573 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003574 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003575 let entries = get_keyentry(&db)?;
3576 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003577 assert_eq!(
3578 extractor(&entries[0]),
3579 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3580 );
3581 assert_eq!(
3582 extractor(&entries[1]),
3583 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3584 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003585
3586 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003587 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003588 let entries = get_keyentry(&db)?;
3589 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003590 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3591 assert_eq!(
3592 extractor(&entries[1]),
3593 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3594 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003595
3596 // Test that we must pass in a valid Domain.
3597 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003598 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003599 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003600 );
3601 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003602 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003603 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003604 );
3605 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003606 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003607 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003608 );
3609
3610 // Test that we correctly handle setting an alias for something that does not exist.
3611 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003612 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003613 "Expected to update a single entry but instead updated 0",
3614 );
3615 // Test that we correctly abort the transaction in this case.
3616 let entries = get_keyentry(&db)?;
3617 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003618 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3619 assert_eq!(
3620 extractor(&entries[1]),
3621 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3622 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003623
3624 Ok(())
3625 }
3626
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003627 #[test]
3628 fn test_grant_ungrant() -> Result<()> {
3629 const CALLER_UID: u32 = 15;
3630 const GRANTEE_UID: u32 = 12;
3631 const SELINUX_NAMESPACE: i64 = 7;
3632
3633 let mut db = new_test_db()?;
3634 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003635 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3636 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3637 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003638 )?;
3639 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003640 domain: super::Domain::APP,
3641 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003642 alias: Some("key".to_string()),
3643 blob: None,
3644 };
3645 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3646 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3647
3648 // Reset totally predictable random number generator in case we
3649 // are not the first test running on this thread.
3650 reset_random();
3651 let next_random = 0i64;
3652
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003653 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003654 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003655 assert_eq!(*a, PVEC1);
3656 assert_eq!(
3657 *k,
3658 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003659 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003660 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003661 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003662 alias: Some("key".to_string()),
3663 blob: None,
3664 }
3665 );
3666 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003667 })
3668 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003669
3670 assert_eq!(
3671 app_granted_key,
3672 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003673 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003674 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003675 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003676 alias: None,
3677 blob: None,
3678 }
3679 );
3680
3681 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003682 domain: super::Domain::SELINUX,
3683 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003684 alias: Some("yek".to_string()),
3685 blob: None,
3686 };
3687
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003688 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003689 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003690 assert_eq!(*a, PVEC1);
3691 assert_eq!(
3692 *k,
3693 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003694 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003695 // namespace must be the supplied SELinux
3696 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003697 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003698 alias: Some("yek".to_string()),
3699 blob: None,
3700 }
3701 );
3702 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003703 })
3704 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003705
3706 assert_eq!(
3707 selinux_granted_key,
3708 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003709 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003710 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003711 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003712 alias: None,
3713 blob: None,
3714 }
3715 );
3716
3717 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003718 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003719 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003720 assert_eq!(*a, PVEC2);
3721 assert_eq!(
3722 *k,
3723 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003724 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725 // namespace must be the supplied SELinux
3726 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003727 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003728 alias: Some("yek".to_string()),
3729 blob: None,
3730 }
3731 );
3732 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003733 })
3734 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003735
3736 assert_eq!(
3737 selinux_granted_key,
3738 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003739 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003740 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003741 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003742 alias: None,
3743 blob: None,
3744 }
3745 );
3746
3747 {
3748 // Limiting scope of stmt, because it borrows db.
3749 let mut stmt = db
3750 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003751 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003752 let mut rows =
3753 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3754 Ok((
3755 row.get(0)?,
3756 row.get(1)?,
3757 row.get(2)?,
3758 KeyPermSet::from(row.get::<_, i32>(3)?),
3759 ))
3760 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003761
3762 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003763 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003764 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003765 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003766 assert!(rows.next().is_none());
3767 }
3768
3769 debug_dump_keyentry_table(&mut db)?;
3770 println!("app_key {:?}", app_key);
3771 println!("selinux_key {:?}", selinux_key);
3772
Janis Danisevskis66784c42021-01-27 08:40:25 -08003773 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3774 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775
3776 Ok(())
3777 }
3778
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003779 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003780 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3781 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3782
3783 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003784 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003785 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003786 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003787 let mut blob_metadata = BlobMetaData::new();
3788 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3789 db.set_blob(
3790 &key_id,
3791 SubComponentType::KEY_BLOB,
3792 Some(TEST_KEY_BLOB),
3793 Some(&blob_metadata),
3794 )?;
3795 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3796 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003797 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003798
3799 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003800 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003801 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003802 )?;
3803 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003804 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3805 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003806 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003807 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003808 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003809 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003810 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003811 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003812 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003813
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003814 drop(rows);
3815 drop(stmt);
3816
3817 assert_eq!(
3818 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3819 BlobMetaData::load_from_db(id, tx).no_gc()
3820 })
3821 .expect("Should find blob metadata."),
3822 blob_metadata
3823 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003824 Ok(())
3825 }
3826
3827 static TEST_ALIAS: &str = "my super duper key";
3828
3829 #[test]
3830 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3831 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003832 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003833 .context("test_insert_and_load_full_keyentry_domain_app")?
3834 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003835 let (_key_guard, key_entry) = db
3836 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003837 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003838 domain: Domain::APP,
3839 nspace: 0,
3840 alias: Some(TEST_ALIAS.to_string()),
3841 blob: None,
3842 },
3843 KeyType::Client,
3844 KeyEntryLoadBits::BOTH,
3845 1,
3846 |_k, _av| Ok(()),
3847 )
3848 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003849 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003850
3851 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003852 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003853 domain: Domain::APP,
3854 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003855 alias: Some(TEST_ALIAS.to_string()),
3856 blob: None,
3857 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003858 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003859 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003860 |_, _| Ok(()),
3861 )
3862 .unwrap();
3863
3864 assert_eq!(
3865 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3866 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003867 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003868 domain: Domain::APP,
3869 nspace: 0,
3870 alias: Some(TEST_ALIAS.to_string()),
3871 blob: None,
3872 },
3873 KeyType::Client,
3874 KeyEntryLoadBits::NONE,
3875 1,
3876 |_k, _av| Ok(()),
3877 )
3878 .unwrap_err()
3879 .root_cause()
3880 .downcast_ref::<KsError>()
3881 );
3882
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003883 Ok(())
3884 }
3885
3886 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003887 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3888 let mut db = new_test_db()?;
3889
3890 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003891 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003892 domain: Domain::APP,
3893 nspace: 1,
3894 alias: Some(TEST_ALIAS.to_string()),
3895 blob: None,
3896 },
3897 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003898 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003899 )
3900 .expect("Trying to insert cert.");
3901
3902 let (_key_guard, mut key_entry) = db
3903 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003904 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003905 domain: Domain::APP,
3906 nspace: 1,
3907 alias: Some(TEST_ALIAS.to_string()),
3908 blob: None,
3909 },
3910 KeyType::Client,
3911 KeyEntryLoadBits::PUBLIC,
3912 1,
3913 |_k, _av| Ok(()),
3914 )
3915 .expect("Trying to read certificate entry.");
3916
3917 assert!(key_entry.pure_cert());
3918 assert!(key_entry.cert().is_none());
3919 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3920
3921 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003922 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003923 domain: Domain::APP,
3924 nspace: 1,
3925 alias: Some(TEST_ALIAS.to_string()),
3926 blob: None,
3927 },
3928 KeyType::Client,
3929 1,
3930 |_, _| Ok(()),
3931 )
3932 .unwrap();
3933
3934 assert_eq!(
3935 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3936 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003937 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003938 domain: Domain::APP,
3939 nspace: 1,
3940 alias: Some(TEST_ALIAS.to_string()),
3941 blob: None,
3942 },
3943 KeyType::Client,
3944 KeyEntryLoadBits::NONE,
3945 1,
3946 |_k, _av| Ok(()),
3947 )
3948 .unwrap_err()
3949 .root_cause()
3950 .downcast_ref::<KsError>()
3951 );
3952
3953 Ok(())
3954 }
3955
3956 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003957 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3958 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003959 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003960 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3961 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003962 let (_key_guard, key_entry) = db
3963 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003964 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003965 domain: Domain::SELINUX,
3966 nspace: 1,
3967 alias: Some(TEST_ALIAS.to_string()),
3968 blob: None,
3969 },
3970 KeyType::Client,
3971 KeyEntryLoadBits::BOTH,
3972 1,
3973 |_k, _av| Ok(()),
3974 )
3975 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003976 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003977
3978 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003979 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003980 domain: Domain::SELINUX,
3981 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003982 alias: Some(TEST_ALIAS.to_string()),
3983 blob: None,
3984 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003985 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003986 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003987 |_, _| Ok(()),
3988 )
3989 .unwrap();
3990
3991 assert_eq!(
3992 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3993 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003994 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003995 domain: Domain::SELINUX,
3996 nspace: 1,
3997 alias: Some(TEST_ALIAS.to_string()),
3998 blob: None,
3999 },
4000 KeyType::Client,
4001 KeyEntryLoadBits::NONE,
4002 1,
4003 |_k, _av| Ok(()),
4004 )
4005 .unwrap_err()
4006 .root_cause()
4007 .downcast_ref::<KsError>()
4008 );
4009
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004010 Ok(())
4011 }
4012
4013 #[test]
4014 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4015 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004016 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004017 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4018 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004019 let (_, key_entry) = db
4020 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004021 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004022 KeyType::Client,
4023 KeyEntryLoadBits::BOTH,
4024 1,
4025 |_k, _av| Ok(()),
4026 )
4027 .unwrap();
4028
Qi Wub9433b52020-12-01 14:52:46 +08004029 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004030
4031 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004032 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004033 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004034 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004035 |_, _| Ok(()),
4036 )
4037 .unwrap();
4038
4039 assert_eq!(
4040 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4041 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004042 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004043 KeyType::Client,
4044 KeyEntryLoadBits::NONE,
4045 1,
4046 |_k, _av| Ok(()),
4047 )
4048 .unwrap_err()
4049 .root_cause()
4050 .downcast_ref::<KsError>()
4051 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004052
4053 Ok(())
4054 }
4055
4056 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004057 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4058 let mut db = new_test_db()?;
4059 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4060 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4061 .0;
4062 // Update the usage count of the limited use key.
4063 db.check_and_update_key_usage_count(key_id)?;
4064
4065 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004066 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004067 KeyType::Client,
4068 KeyEntryLoadBits::BOTH,
4069 1,
4070 |_k, _av| Ok(()),
4071 )?;
4072
4073 // The usage count is decremented now.
4074 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4075
4076 Ok(())
4077 }
4078
4079 #[test]
4080 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4081 let mut db = new_test_db()?;
4082 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4083 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4084 .0;
4085 // Update the usage count of the limited use key.
4086 db.check_and_update_key_usage_count(key_id).expect(concat!(
4087 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4088 "This should succeed."
4089 ));
4090
4091 // Try to update the exhausted limited use key.
4092 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4093 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4094 "This should fail."
4095 ));
4096 assert_eq!(
4097 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4098 e.root_cause().downcast_ref::<KsError>().unwrap()
4099 );
4100
4101 Ok(())
4102 }
4103
4104 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004105 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4106 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004107 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004108 .context("test_insert_and_load_full_keyentry_from_grant")?
4109 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004110
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004111 let granted_key = db
4112 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004113 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004114 domain: Domain::APP,
4115 nspace: 0,
4116 alias: Some(TEST_ALIAS.to_string()),
4117 blob: None,
4118 },
4119 1,
4120 2,
4121 key_perm_set![KeyPerm::use_()],
4122 |_k, _av| Ok(()),
4123 )
4124 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004125
4126 debug_dump_grant_table(&mut db)?;
4127
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004128 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004129 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4130 assert_eq!(Domain::GRANT, k.domain);
4131 assert!(av.unwrap().includes(KeyPerm::use_()));
4132 Ok(())
4133 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004134 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004135
Qi Wub9433b52020-12-01 14:52:46 +08004136 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004137
Janis Danisevskis66784c42021-01-27 08:40:25 -08004138 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004139
4140 assert_eq!(
4141 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4142 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004143 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004144 KeyType::Client,
4145 KeyEntryLoadBits::NONE,
4146 2,
4147 |_k, _av| Ok(()),
4148 )
4149 .unwrap_err()
4150 .root_cause()
4151 .downcast_ref::<KsError>()
4152 );
4153
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004154 Ok(())
4155 }
4156
Janis Danisevskis45760022021-01-19 16:34:10 -08004157 // This test attempts to load a key by key id while the caller is not the owner
4158 // but a grant exists for the given key and the caller.
4159 #[test]
4160 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4161 let mut db = new_test_db()?;
4162 const OWNER_UID: u32 = 1u32;
4163 const GRANTEE_UID: u32 = 2u32;
4164 const SOMEONE_ELSE_UID: u32 = 3u32;
4165 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4166 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4167 .0;
4168
4169 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004170 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004171 domain: Domain::APP,
4172 nspace: 0,
4173 alias: Some(TEST_ALIAS.to_string()),
4174 blob: None,
4175 },
4176 OWNER_UID,
4177 GRANTEE_UID,
4178 key_perm_set![KeyPerm::use_()],
4179 |_k, _av| Ok(()),
4180 )
4181 .unwrap();
4182
4183 debug_dump_grant_table(&mut db)?;
4184
4185 let id_descriptor =
4186 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4187
4188 let (_, key_entry) = db
4189 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004190 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004191 KeyType::Client,
4192 KeyEntryLoadBits::BOTH,
4193 GRANTEE_UID,
4194 |k, av| {
4195 assert_eq!(Domain::APP, k.domain);
4196 assert_eq!(OWNER_UID as i64, k.nspace);
4197 assert!(av.unwrap().includes(KeyPerm::use_()));
4198 Ok(())
4199 },
4200 )
4201 .unwrap();
4202
4203 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4204
4205 let (_, key_entry) = db
4206 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004207 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004208 KeyType::Client,
4209 KeyEntryLoadBits::BOTH,
4210 SOMEONE_ELSE_UID,
4211 |k, av| {
4212 assert_eq!(Domain::APP, k.domain);
4213 assert_eq!(OWNER_UID as i64, k.nspace);
4214 assert!(av.is_none());
4215 Ok(())
4216 },
4217 )
4218 .unwrap();
4219
4220 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4221
Janis Danisevskis66784c42021-01-27 08:40:25 -08004222 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004223
4224 assert_eq!(
4225 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4226 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004227 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004228 KeyType::Client,
4229 KeyEntryLoadBits::NONE,
4230 GRANTEE_UID,
4231 |_k, _av| Ok(()),
4232 )
4233 .unwrap_err()
4234 .root_cause()
4235 .downcast_ref::<KsError>()
4236 );
4237
4238 Ok(())
4239 }
4240
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004241 // Creates a key migrates it to a different location and then tries to access it by the old
4242 // and new location.
4243 #[test]
4244 fn test_migrate_key_app_to_app() -> Result<()> {
4245 let mut db = new_test_db()?;
4246 const SOURCE_UID: u32 = 1u32;
4247 const DESTINATION_UID: u32 = 2u32;
4248 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4249 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4250 let key_id_guard =
4251 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4252 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4253
4254 let source_descriptor: KeyDescriptor = KeyDescriptor {
4255 domain: Domain::APP,
4256 nspace: -1,
4257 alias: Some(SOURCE_ALIAS.to_string()),
4258 blob: None,
4259 };
4260
4261 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4262 domain: Domain::APP,
4263 nspace: -1,
4264 alias: Some(DESTINATION_ALIAS.to_string()),
4265 blob: None,
4266 };
4267
4268 let key_id = key_id_guard.id();
4269
4270 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4271 Ok(())
4272 })
4273 .unwrap();
4274
4275 let (_, key_entry) = db
4276 .load_key_entry(
4277 &destination_descriptor,
4278 KeyType::Client,
4279 KeyEntryLoadBits::BOTH,
4280 DESTINATION_UID,
4281 |k, av| {
4282 assert_eq!(Domain::APP, k.domain);
4283 assert_eq!(DESTINATION_UID as i64, k.nspace);
4284 assert!(av.is_none());
4285 Ok(())
4286 },
4287 )
4288 .unwrap();
4289
4290 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4291
4292 assert_eq!(
4293 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4294 db.load_key_entry(
4295 &source_descriptor,
4296 KeyType::Client,
4297 KeyEntryLoadBits::NONE,
4298 SOURCE_UID,
4299 |_k, _av| Ok(()),
4300 )
4301 .unwrap_err()
4302 .root_cause()
4303 .downcast_ref::<KsError>()
4304 );
4305
4306 Ok(())
4307 }
4308
4309 // Creates a key migrates it to a different location and then tries to access it by the old
4310 // and new location.
4311 #[test]
4312 fn test_migrate_key_app_to_selinux() -> Result<()> {
4313 let mut db = new_test_db()?;
4314 const SOURCE_UID: u32 = 1u32;
4315 const DESTINATION_UID: u32 = 2u32;
4316 const DESTINATION_NAMESPACE: i64 = 1000i64;
4317 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4318 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4319 let key_id_guard =
4320 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4321 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4322
4323 let source_descriptor: KeyDescriptor = KeyDescriptor {
4324 domain: Domain::APP,
4325 nspace: -1,
4326 alias: Some(SOURCE_ALIAS.to_string()),
4327 blob: None,
4328 };
4329
4330 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4331 domain: Domain::SELINUX,
4332 nspace: DESTINATION_NAMESPACE,
4333 alias: Some(DESTINATION_ALIAS.to_string()),
4334 blob: None,
4335 };
4336
4337 let key_id = key_id_guard.id();
4338
4339 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4340 Ok(())
4341 })
4342 .unwrap();
4343
4344 let (_, key_entry) = db
4345 .load_key_entry(
4346 &destination_descriptor,
4347 KeyType::Client,
4348 KeyEntryLoadBits::BOTH,
4349 DESTINATION_UID,
4350 |k, av| {
4351 assert_eq!(Domain::SELINUX, k.domain);
4352 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4353 assert!(av.is_none());
4354 Ok(())
4355 },
4356 )
4357 .unwrap();
4358
4359 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4360
4361 assert_eq!(
4362 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4363 db.load_key_entry(
4364 &source_descriptor,
4365 KeyType::Client,
4366 KeyEntryLoadBits::NONE,
4367 SOURCE_UID,
4368 |_k, _av| Ok(()),
4369 )
4370 .unwrap_err()
4371 .root_cause()
4372 .downcast_ref::<KsError>()
4373 );
4374
4375 Ok(())
4376 }
4377
4378 // Creates two keys and tries to migrate the first to the location of the second which
4379 // is expected to fail.
4380 #[test]
4381 fn test_migrate_key_destination_occupied() -> Result<()> {
4382 let mut db = new_test_db()?;
4383 const SOURCE_UID: u32 = 1u32;
4384 const DESTINATION_UID: u32 = 2u32;
4385 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4386 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4387 let key_id_guard =
4388 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4389 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4390 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4391 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4392
4393 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4394 domain: Domain::APP,
4395 nspace: -1,
4396 alias: Some(DESTINATION_ALIAS.to_string()),
4397 blob: None,
4398 };
4399
4400 assert_eq!(
4401 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4402 db.migrate_key_namespace(
4403 key_id_guard,
4404 &destination_descriptor,
4405 DESTINATION_UID,
4406 |_k| Ok(())
4407 )
4408 .unwrap_err()
4409 .root_cause()
4410 .downcast_ref::<KsError>()
4411 );
4412
4413 Ok(())
4414 }
4415
Janis Danisevskisaec14592020-11-12 09:41:49 -08004416 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4417
Janis Danisevskisaec14592020-11-12 09:41:49 -08004418 #[test]
4419 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4420 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004421 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4422 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004423 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004424 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004425 .context("test_insert_and_load_full_keyentry_domain_app")?
4426 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004427 let (_key_guard, key_entry) = db
4428 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004429 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004430 domain: Domain::APP,
4431 nspace: 0,
4432 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4433 blob: None,
4434 },
4435 KeyType::Client,
4436 KeyEntryLoadBits::BOTH,
4437 33,
4438 |_k, _av| Ok(()),
4439 )
4440 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004441 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004442 let state = Arc::new(AtomicU8::new(1));
4443 let state2 = state.clone();
4444
4445 // Spawning a second thread that attempts to acquire the key id lock
4446 // for the same key as the primary thread. The primary thread then
4447 // waits, thereby forcing the secondary thread into the second stage
4448 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4449 // The test succeeds if the secondary thread observes the transition
4450 // of `state` from 1 to 2, despite having a whole second to overtake
4451 // the primary thread.
4452 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004453 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004454 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004455 assert!(db
4456 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004457 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004458 domain: Domain::APP,
4459 nspace: 0,
4460 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4461 blob: None,
4462 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004463 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004464 KeyEntryLoadBits::BOTH,
4465 33,
4466 |_k, _av| Ok(()),
4467 )
4468 .is_ok());
4469 // We should only see a 2 here because we can only return
4470 // from load_key_entry when the `_key_guard` expires,
4471 // which happens at the end of the scope.
4472 assert_eq!(2, state2.load(Ordering::Relaxed));
4473 });
4474
4475 thread::sleep(std::time::Duration::from_millis(1000));
4476
4477 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4478
4479 // Return the handle from this scope so we can join with the
4480 // secondary thread after the key id lock has expired.
4481 handle
4482 // This is where the `_key_guard` goes out of scope,
4483 // which is the reason for concurrent load_key_entry on the same key
4484 // to unblock.
4485 };
4486 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4487 // main test thread. We will not see failing asserts in secondary threads otherwise.
4488 handle.join().unwrap();
4489 Ok(())
4490 }
4491
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004492 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004493 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004494 let temp_dir =
4495 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4496
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004497 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4498 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004499
4500 let _tx1 = db1
4501 .conn
4502 .transaction_with_behavior(TransactionBehavior::Immediate)
4503 .expect("Failed to create first transaction.");
4504
4505 let error = db2
4506 .conn
4507 .transaction_with_behavior(TransactionBehavior::Immediate)
4508 .context("Transaction begin failed.")
4509 .expect_err("This should fail.");
4510 let root_cause = error.root_cause();
4511 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4512 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4513 {
4514 return;
4515 }
4516 panic!(
4517 "Unexpected error {:?} \n{:?} \n{:?}",
4518 error,
4519 root_cause,
4520 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4521 )
4522 }
4523
4524 #[cfg(disabled)]
4525 #[test]
4526 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4527 let temp_dir = Arc::new(
4528 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4529 .expect("Failed to create temp dir."),
4530 );
4531
4532 let test_begin = Instant::now();
4533
4534 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4535 const KEY_COUNT: u32 = 500u32;
4536 const OPEN_DB_COUNT: u32 = 50u32;
4537
4538 let mut actual_key_count = KEY_COUNT;
4539 // First insert KEY_COUNT keys.
4540 for count in 0..KEY_COUNT {
4541 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4542 actual_key_count = count;
4543 break;
4544 }
4545 let alias = format!("test_alias_{}", count);
4546 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4547 .expect("Failed to make key entry.");
4548 }
4549
4550 // Insert more keys from a different thread and into a different namespace.
4551 let temp_dir1 = temp_dir.clone();
4552 let handle1 = thread::spawn(move || {
4553 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4554
4555 for count in 0..actual_key_count {
4556 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4557 return;
4558 }
4559 let alias = format!("test_alias_{}", count);
4560 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4561 .expect("Failed to make key entry.");
4562 }
4563
4564 // then unbind them again.
4565 for count in 0..actual_key_count {
4566 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4567 return;
4568 }
4569 let key = KeyDescriptor {
4570 domain: Domain::APP,
4571 nspace: -1,
4572 alias: Some(format!("test_alias_{}", count)),
4573 blob: None,
4574 };
4575 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4576 }
4577 });
4578
4579 // And start unbinding the first set of keys.
4580 let temp_dir2 = temp_dir.clone();
4581 let handle2 = thread::spawn(move || {
4582 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4583
4584 for count in 0..actual_key_count {
4585 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4586 return;
4587 }
4588 let key = KeyDescriptor {
4589 domain: Domain::APP,
4590 nspace: -1,
4591 alias: Some(format!("test_alias_{}", count)),
4592 blob: None,
4593 };
4594 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4595 }
4596 });
4597
4598 let stop_deleting = Arc::new(AtomicU8::new(0));
4599 let stop_deleting2 = stop_deleting.clone();
4600
4601 // And delete anything that is unreferenced keys.
4602 let temp_dir3 = temp_dir.clone();
4603 let handle3 = thread::spawn(move || {
4604 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4605
4606 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4607 while let Some((key_guard, _key)) =
4608 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4609 {
4610 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4611 return;
4612 }
4613 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4614 }
4615 std::thread::sleep(std::time::Duration::from_millis(100));
4616 }
4617 });
4618
4619 // While a lot of inserting and deleting is going on we have to open database connections
4620 // successfully and use them.
4621 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4622 // out of scope.
4623 #[allow(clippy::redundant_clone)]
4624 let temp_dir4 = temp_dir.clone();
4625 let handle4 = thread::spawn(move || {
4626 for count in 0..OPEN_DB_COUNT {
4627 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4628 return;
4629 }
4630 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4631
4632 let alias = format!("test_alias_{}", count);
4633 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4634 .expect("Failed to make key entry.");
4635 let key = KeyDescriptor {
4636 domain: Domain::APP,
4637 nspace: -1,
4638 alias: Some(alias),
4639 blob: None,
4640 };
4641 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4642 }
4643 });
4644
4645 handle1.join().expect("Thread 1 panicked.");
4646 handle2.join().expect("Thread 2 panicked.");
4647 handle4.join().expect("Thread 4 panicked.");
4648
4649 stop_deleting.store(1, Ordering::Relaxed);
4650 handle3.join().expect("Thread 3 panicked.");
4651
4652 Ok(())
4653 }
4654
4655 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004656 fn list() -> Result<()> {
4657 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004658 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004659 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4660 (Domain::APP, 1, "test1"),
4661 (Domain::APP, 1, "test2"),
4662 (Domain::APP, 1, "test3"),
4663 (Domain::APP, 1, "test4"),
4664 (Domain::APP, 1, "test5"),
4665 (Domain::APP, 1, "test6"),
4666 (Domain::APP, 1, "test7"),
4667 (Domain::APP, 2, "test1"),
4668 (Domain::APP, 2, "test2"),
4669 (Domain::APP, 2, "test3"),
4670 (Domain::APP, 2, "test4"),
4671 (Domain::APP, 2, "test5"),
4672 (Domain::APP, 2, "test6"),
4673 (Domain::APP, 2, "test8"),
4674 (Domain::SELINUX, 100, "test1"),
4675 (Domain::SELINUX, 100, "test2"),
4676 (Domain::SELINUX, 100, "test3"),
4677 (Domain::SELINUX, 100, "test4"),
4678 (Domain::SELINUX, 100, "test5"),
4679 (Domain::SELINUX, 100, "test6"),
4680 (Domain::SELINUX, 100, "test9"),
4681 ];
4682
4683 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4684 .iter()
4685 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004686 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4687 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004688 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4689 });
4690 (entry.id(), *ns)
4691 })
4692 .collect();
4693
4694 for (domain, namespace) in
4695 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4696 {
4697 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4698 .iter()
4699 .filter_map(|(domain, ns, alias)| match ns {
4700 ns if *ns == *namespace => Some(KeyDescriptor {
4701 domain: *domain,
4702 nspace: *ns,
4703 alias: Some(alias.to_string()),
4704 blob: None,
4705 }),
4706 _ => None,
4707 })
4708 .collect();
4709 list_o_descriptors.sort();
4710 let mut list_result = db.list(*domain, *namespace)?;
4711 list_result.sort();
4712 assert_eq!(list_o_descriptors, list_result);
4713
4714 let mut list_o_ids: Vec<i64> = list_o_descriptors
4715 .into_iter()
4716 .map(|d| {
4717 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004718 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004719 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004720 KeyType::Client,
4721 KeyEntryLoadBits::NONE,
4722 *namespace as u32,
4723 |_, _| Ok(()),
4724 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004725 .unwrap();
4726 entry.id()
4727 })
4728 .collect();
4729 list_o_ids.sort_unstable();
4730 let mut loaded_entries: Vec<i64> = list_o_keys
4731 .iter()
4732 .filter_map(|(id, ns)| match ns {
4733 ns if *ns == *namespace => Some(*id),
4734 _ => None,
4735 })
4736 .collect();
4737 loaded_entries.sort_unstable();
4738 assert_eq!(list_o_ids, loaded_entries);
4739 }
4740 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4741
4742 Ok(())
4743 }
4744
Joel Galenson0891bc12020-07-20 10:37:03 -07004745 // Helpers
4746
4747 // Checks that the given result is an error containing the given string.
4748 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4749 let error_str = format!(
4750 "{:#?}",
4751 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4752 );
4753 assert!(
4754 error_str.contains(target),
4755 "The string \"{}\" should contain \"{}\"",
4756 error_str,
4757 target
4758 );
4759 }
4760
Joel Galenson2aab4432020-07-22 15:27:57 -07004761 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004762 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004763 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004764 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004765 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004766 namespace: Option<i64>,
4767 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004768 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004769 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004770 }
4771
4772 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4773 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004774 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004775 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004776 Ok(KeyEntryRow {
4777 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004778 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004779 domain: match row.get(2)? {
4780 Some(i) => Some(Domain(i)),
4781 None => None,
4782 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004783 namespace: row.get(3)?,
4784 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004785 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004786 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004787 })
4788 })?
4789 .map(|r| r.context("Could not read keyentry row."))
4790 .collect::<Result<Vec<_>>>()
4791 }
4792
Max Biresb2e1d032021-02-08 21:35:05 -08004793 struct RemoteProvValues {
4794 cert_chain: Vec<u8>,
4795 priv_key: Vec<u8>,
4796 batch_cert: Vec<u8>,
4797 }
4798
Max Bires2b2e6562020-09-22 11:22:36 -07004799 fn load_attestation_key_pool(
4800 db: &mut KeystoreDB,
4801 expiration_date: i64,
4802 namespace: i64,
4803 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004804 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004805 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4806 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4807 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4808 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004809 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004810 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4811 db.store_signed_attestation_certificate_chain(
4812 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004813 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004814 &cert_chain,
4815 expiration_date,
4816 &KEYSTORE_UUID,
4817 )?;
4818 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004819 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004820 }
4821
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004822 // Note: The parameters and SecurityLevel associations are nonsensical. This
4823 // collection is only used to check if the parameters are preserved as expected by the
4824 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004825 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4826 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004827 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4828 KeyParameter::new(
4829 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4830 SecurityLevel::TRUSTED_ENVIRONMENT,
4831 ),
4832 KeyParameter::new(
4833 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4834 SecurityLevel::TRUSTED_ENVIRONMENT,
4835 ),
4836 KeyParameter::new(
4837 KeyParameterValue::Algorithm(Algorithm::RSA),
4838 SecurityLevel::TRUSTED_ENVIRONMENT,
4839 ),
4840 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4841 KeyParameter::new(
4842 KeyParameterValue::BlockMode(BlockMode::ECB),
4843 SecurityLevel::TRUSTED_ENVIRONMENT,
4844 ),
4845 KeyParameter::new(
4846 KeyParameterValue::BlockMode(BlockMode::GCM),
4847 SecurityLevel::TRUSTED_ENVIRONMENT,
4848 ),
4849 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4850 KeyParameter::new(
4851 KeyParameterValue::Digest(Digest::MD5),
4852 SecurityLevel::TRUSTED_ENVIRONMENT,
4853 ),
4854 KeyParameter::new(
4855 KeyParameterValue::Digest(Digest::SHA_2_224),
4856 SecurityLevel::TRUSTED_ENVIRONMENT,
4857 ),
4858 KeyParameter::new(
4859 KeyParameterValue::Digest(Digest::SHA_2_256),
4860 SecurityLevel::STRONGBOX,
4861 ),
4862 KeyParameter::new(
4863 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4864 SecurityLevel::TRUSTED_ENVIRONMENT,
4865 ),
4866 KeyParameter::new(
4867 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4868 SecurityLevel::TRUSTED_ENVIRONMENT,
4869 ),
4870 KeyParameter::new(
4871 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4872 SecurityLevel::STRONGBOX,
4873 ),
4874 KeyParameter::new(
4875 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4876 SecurityLevel::TRUSTED_ENVIRONMENT,
4877 ),
4878 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4879 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4880 KeyParameter::new(
4881 KeyParameterValue::EcCurve(EcCurve::P_224),
4882 SecurityLevel::TRUSTED_ENVIRONMENT,
4883 ),
4884 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4885 KeyParameter::new(
4886 KeyParameterValue::EcCurve(EcCurve::P_384),
4887 SecurityLevel::TRUSTED_ENVIRONMENT,
4888 ),
4889 KeyParameter::new(
4890 KeyParameterValue::EcCurve(EcCurve::P_521),
4891 SecurityLevel::TRUSTED_ENVIRONMENT,
4892 ),
4893 KeyParameter::new(
4894 KeyParameterValue::RSAPublicExponent(3),
4895 SecurityLevel::TRUSTED_ENVIRONMENT,
4896 ),
4897 KeyParameter::new(
4898 KeyParameterValue::IncludeUniqueID,
4899 SecurityLevel::TRUSTED_ENVIRONMENT,
4900 ),
4901 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4902 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4903 KeyParameter::new(
4904 KeyParameterValue::ActiveDateTime(1234567890),
4905 SecurityLevel::STRONGBOX,
4906 ),
4907 KeyParameter::new(
4908 KeyParameterValue::OriginationExpireDateTime(1234567890),
4909 SecurityLevel::TRUSTED_ENVIRONMENT,
4910 ),
4911 KeyParameter::new(
4912 KeyParameterValue::UsageExpireDateTime(1234567890),
4913 SecurityLevel::TRUSTED_ENVIRONMENT,
4914 ),
4915 KeyParameter::new(
4916 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4917 SecurityLevel::TRUSTED_ENVIRONMENT,
4918 ),
4919 KeyParameter::new(
4920 KeyParameterValue::MaxUsesPerBoot(1234567890),
4921 SecurityLevel::TRUSTED_ENVIRONMENT,
4922 ),
4923 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4924 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4925 KeyParameter::new(
4926 KeyParameterValue::NoAuthRequired,
4927 SecurityLevel::TRUSTED_ENVIRONMENT,
4928 ),
4929 KeyParameter::new(
4930 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4931 SecurityLevel::TRUSTED_ENVIRONMENT,
4932 ),
4933 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4934 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4935 KeyParameter::new(
4936 KeyParameterValue::TrustedUserPresenceRequired,
4937 SecurityLevel::TRUSTED_ENVIRONMENT,
4938 ),
4939 KeyParameter::new(
4940 KeyParameterValue::TrustedConfirmationRequired,
4941 SecurityLevel::TRUSTED_ENVIRONMENT,
4942 ),
4943 KeyParameter::new(
4944 KeyParameterValue::UnlockedDeviceRequired,
4945 SecurityLevel::TRUSTED_ENVIRONMENT,
4946 ),
4947 KeyParameter::new(
4948 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4949 SecurityLevel::SOFTWARE,
4950 ),
4951 KeyParameter::new(
4952 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4953 SecurityLevel::SOFTWARE,
4954 ),
4955 KeyParameter::new(
4956 KeyParameterValue::CreationDateTime(12345677890),
4957 SecurityLevel::SOFTWARE,
4958 ),
4959 KeyParameter::new(
4960 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4961 SecurityLevel::TRUSTED_ENVIRONMENT,
4962 ),
4963 KeyParameter::new(
4964 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4965 SecurityLevel::TRUSTED_ENVIRONMENT,
4966 ),
4967 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4968 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4969 KeyParameter::new(
4970 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4971 SecurityLevel::SOFTWARE,
4972 ),
4973 KeyParameter::new(
4974 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4975 SecurityLevel::TRUSTED_ENVIRONMENT,
4976 ),
4977 KeyParameter::new(
4978 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4979 SecurityLevel::TRUSTED_ENVIRONMENT,
4980 ),
4981 KeyParameter::new(
4982 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4983 SecurityLevel::TRUSTED_ENVIRONMENT,
4984 ),
4985 KeyParameter::new(
4986 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4987 SecurityLevel::TRUSTED_ENVIRONMENT,
4988 ),
4989 KeyParameter::new(
4990 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4991 SecurityLevel::TRUSTED_ENVIRONMENT,
4992 ),
4993 KeyParameter::new(
4994 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4995 SecurityLevel::TRUSTED_ENVIRONMENT,
4996 ),
4997 KeyParameter::new(
4998 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4999 SecurityLevel::TRUSTED_ENVIRONMENT,
5000 ),
5001 KeyParameter::new(
5002 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5003 SecurityLevel::TRUSTED_ENVIRONMENT,
5004 ),
5005 KeyParameter::new(
5006 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5007 SecurityLevel::TRUSTED_ENVIRONMENT,
5008 ),
5009 KeyParameter::new(
5010 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5011 SecurityLevel::TRUSTED_ENVIRONMENT,
5012 ),
5013 KeyParameter::new(
5014 KeyParameterValue::VendorPatchLevel(3),
5015 SecurityLevel::TRUSTED_ENVIRONMENT,
5016 ),
5017 KeyParameter::new(
5018 KeyParameterValue::BootPatchLevel(4),
5019 SecurityLevel::TRUSTED_ENVIRONMENT,
5020 ),
5021 KeyParameter::new(
5022 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5023 SecurityLevel::TRUSTED_ENVIRONMENT,
5024 ),
5025 KeyParameter::new(
5026 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5027 SecurityLevel::TRUSTED_ENVIRONMENT,
5028 ),
5029 KeyParameter::new(
5030 KeyParameterValue::MacLength(256),
5031 SecurityLevel::TRUSTED_ENVIRONMENT,
5032 ),
5033 KeyParameter::new(
5034 KeyParameterValue::ResetSinceIdRotation,
5035 SecurityLevel::TRUSTED_ENVIRONMENT,
5036 ),
5037 KeyParameter::new(
5038 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5039 SecurityLevel::TRUSTED_ENVIRONMENT,
5040 ),
Qi Wub9433b52020-12-01 14:52:46 +08005041 ];
5042 if let Some(value) = max_usage_count {
5043 params.push(KeyParameter::new(
5044 KeyParameterValue::UsageCountLimit(value),
5045 SecurityLevel::SOFTWARE,
5046 ));
5047 }
5048 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005049 }
5050
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005051 fn make_test_key_entry(
5052 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005053 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005054 namespace: i64,
5055 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005056 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005057 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005058 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005059 let mut blob_metadata = BlobMetaData::new();
5060 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5061 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5062 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5063 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5064 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5065
5066 db.set_blob(
5067 &key_id,
5068 SubComponentType::KEY_BLOB,
5069 Some(TEST_KEY_BLOB),
5070 Some(&blob_metadata),
5071 )?;
5072 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5073 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005074
5075 let params = make_test_params(max_usage_count);
5076 db.insert_keyparameter(&key_id, &params)?;
5077
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005078 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005079 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005080 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005081 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005082 Ok(key_id)
5083 }
5084
Qi Wub9433b52020-12-01 14:52:46 +08005085 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5086 let params = make_test_params(max_usage_count);
5087
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005088 let mut blob_metadata = BlobMetaData::new();
5089 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5090 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5091 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5092 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5093 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5094
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005095 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005096 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005097
5098 KeyEntry {
5099 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005100 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005101 cert: Some(TEST_CERT_BLOB.to_vec()),
5102 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005103 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005104 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005105 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005106 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005107 }
5108 }
5109
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005110 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005111 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005112 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005113 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005114 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005115 NO_PARAMS,
5116 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005117 Ok((
5118 row.get(0)?,
5119 row.get(1)?,
5120 row.get(2)?,
5121 row.get(3)?,
5122 row.get(4)?,
5123 row.get(5)?,
5124 row.get(6)?,
5125 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005126 },
5127 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005128
5129 println!("Key entry table rows:");
5130 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005131 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005132 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005133 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5134 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005135 );
5136 }
5137 Ok(())
5138 }
5139
5140 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005141 let mut stmt = db
5142 .conn
5143 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005144 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5145 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5146 })?;
5147
5148 println!("Grant table rows:");
5149 for r in rows {
5150 let (id, gt, ki, av) = r.unwrap();
5151 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5152 }
5153 Ok(())
5154 }
5155
Joel Galenson0891bc12020-07-20 10:37:03 -07005156 // Use a custom random number generator that repeats each number once.
5157 // This allows us to test repeated elements.
5158
5159 thread_local! {
5160 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5161 }
5162
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005163 fn reset_random() {
5164 RANDOM_COUNTER.with(|counter| {
5165 *counter.borrow_mut() = 0;
5166 })
5167 }
5168
Joel Galenson0891bc12020-07-20 10:37:03 -07005169 pub fn random() -> i64 {
5170 RANDOM_COUNTER.with(|counter| {
5171 let result = *counter.borrow() / 2;
5172 *counter.borrow_mut() += 1;
5173 result
5174 })
5175 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005176
5177 #[test]
5178 fn test_last_off_body() -> Result<()> {
5179 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005180 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005181 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005182 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005183 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005184 let one_second = Duration::from_secs(1);
5185 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005186 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005187 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005188 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005189 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005190 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5191 Ok(())
5192 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005193
5194 #[test]
5195 fn test_unbind_keys_for_user() -> Result<()> {
5196 let mut db = new_test_db()?;
5197 db.unbind_keys_for_user(1, false)?;
5198
5199 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5200 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5201 db.unbind_keys_for_user(2, false)?;
5202
5203 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5204 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5205
5206 db.unbind_keys_for_user(1, true)?;
5207 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5208
5209 Ok(())
5210 }
5211
5212 #[test]
5213 fn test_store_super_key() -> Result<()> {
5214 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005215 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005216 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005217 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005218 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005219 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005220
5221 let (encrypted_super_key, metadata) =
5222 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005223 db.store_super_key(
5224 1,
5225 &USER_SUPER_KEY,
5226 &encrypted_super_key,
5227 &metadata,
5228 &KeyMetaData::new(),
5229 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005230
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005231 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005232 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005233
Paul Crowley7a658392021-03-18 17:08:20 -07005234 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005235 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5236 USER_SUPER_KEY.algorithm,
5237 key_entry,
5238 &pw,
5239 None,
5240 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005241
Paul Crowley7a658392021-03-18 17:08:20 -07005242 let decrypted_secret_bytes =
5243 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5244 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005245 Ok(())
5246 }
Seth Moore78c091f2021-04-09 21:38:30 +00005247
5248 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5249 vec![
5250 StatsdStorageType::KeyEntry,
5251 StatsdStorageType::KeyEntryIdIndex,
5252 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5253 StatsdStorageType::BlobEntry,
5254 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5255 StatsdStorageType::KeyParameter,
5256 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5257 StatsdStorageType::KeyMetadata,
5258 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5259 StatsdStorageType::Grant,
5260 StatsdStorageType::AuthToken,
5261 StatsdStorageType::BlobMetadata,
5262 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5263 ]
5264 }
5265
5266 /// Perform a simple check to ensure that we can query all the storage types
5267 /// that are supported by the DB. Check for reasonable values.
5268 #[test]
5269 fn test_query_all_valid_table_sizes() -> Result<()> {
5270 const PAGE_SIZE: i64 = 4096;
5271
5272 let mut db = new_test_db()?;
5273
5274 for t in get_valid_statsd_storage_types() {
5275 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005276 // AuthToken can be less than a page since it's in a btree, not sqlite
5277 // TODO(b/187474736) stop using if-let here
5278 if let StatsdStorageType::AuthToken = t {
5279 } else {
5280 assert!(stat.size >= PAGE_SIZE);
5281 }
Seth Moore78c091f2021-04-09 21:38:30 +00005282 assert!(stat.size >= stat.unused_size);
5283 }
5284
5285 Ok(())
5286 }
5287
5288 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5289 get_valid_statsd_storage_types()
5290 .into_iter()
5291 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5292 .collect()
5293 }
5294
5295 fn assert_storage_increased(
5296 db: &mut KeystoreDB,
5297 increased_storage_types: Vec<StatsdStorageType>,
5298 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5299 ) {
5300 for storage in increased_storage_types {
5301 // Verify the expected storage increased.
5302 let new = db.get_storage_stat(storage).unwrap();
5303 let storage = storage as i32;
5304 let old = &baseline[&storage];
5305 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5306 assert!(
5307 new.unused_size <= old.unused_size,
5308 "{}: {} <= {}",
5309 storage,
5310 new.unused_size,
5311 old.unused_size
5312 );
5313
5314 // Update the baseline with the new value so that it succeeds in the
5315 // later comparison.
5316 baseline.insert(storage, new);
5317 }
5318
5319 // Get an updated map of the storage and verify there were no unexpected changes.
5320 let updated_stats = get_storage_stats_map(db);
5321 assert_eq!(updated_stats.len(), baseline.len());
5322
5323 for &k in baseline.keys() {
5324 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5325 let mut s = String::new();
5326 for &k in map.keys() {
5327 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5328 .expect("string concat failed");
5329 }
5330 s
5331 };
5332
5333 assert!(
5334 updated_stats[&k].size == baseline[&k].size
5335 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5336 "updated_stats:\n{}\nbaseline:\n{}",
5337 stringify(&updated_stats),
5338 stringify(&baseline)
5339 );
5340 }
5341 }
5342
5343 #[test]
5344 fn test_verify_key_table_size_reporting() -> Result<()> {
5345 let mut db = new_test_db()?;
5346 let mut working_stats = get_storage_stats_map(&mut db);
5347
5348 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5349 assert_storage_increased(
5350 &mut db,
5351 vec![
5352 StatsdStorageType::KeyEntry,
5353 StatsdStorageType::KeyEntryIdIndex,
5354 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5355 ],
5356 &mut working_stats,
5357 );
5358
5359 let mut blob_metadata = BlobMetaData::new();
5360 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5361 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5362 assert_storage_increased(
5363 &mut db,
5364 vec![
5365 StatsdStorageType::BlobEntry,
5366 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5367 StatsdStorageType::BlobMetadata,
5368 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5369 ],
5370 &mut working_stats,
5371 );
5372
5373 let params = make_test_params(None);
5374 db.insert_keyparameter(&key_id, &params)?;
5375 assert_storage_increased(
5376 &mut db,
5377 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5378 &mut working_stats,
5379 );
5380
5381 let mut metadata = KeyMetaData::new();
5382 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5383 db.insert_key_metadata(&key_id, &metadata)?;
5384 assert_storage_increased(
5385 &mut db,
5386 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5387 &mut working_stats,
5388 );
5389
5390 let mut sum = 0;
5391 for stat in working_stats.values() {
5392 sum += stat.size;
5393 }
5394 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5395 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5396
5397 Ok(())
5398 }
5399
5400 #[test]
5401 fn test_verify_auth_table_size_reporting() -> Result<()> {
5402 let mut db = new_test_db()?;
5403 let mut working_stats = get_storage_stats_map(&mut db);
5404 db.insert_auth_token(&HardwareAuthToken {
5405 challenge: 123,
5406 userId: 456,
5407 authenticatorId: 789,
5408 authenticatorType: kmhw_authenticator_type::ANY,
5409 timestamp: Timestamp { milliSeconds: 10 },
5410 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005411 });
Seth Moore78c091f2021-04-09 21:38:30 +00005412 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5413 Ok(())
5414 }
5415
5416 #[test]
5417 fn test_verify_grant_table_size_reporting() -> Result<()> {
5418 const OWNER: i64 = 1;
5419 let mut db = new_test_db()?;
5420 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5421
5422 let mut working_stats = get_storage_stats_map(&mut db);
5423 db.grant(
5424 &KeyDescriptor {
5425 domain: Domain::APP,
5426 nspace: 0,
5427 alias: Some(TEST_ALIAS.to_string()),
5428 blob: None,
5429 },
5430 OWNER as u32,
5431 123,
5432 key_perm_set![KeyPerm::use_()],
5433 |_, _| Ok(()),
5434 )?;
5435
5436 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5437
5438 Ok(())
5439 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005440
5441 #[test]
5442 fn find_auth_token_entry_returns_latest() -> Result<()> {
5443 let mut db = new_test_db()?;
5444 db.insert_auth_token(&HardwareAuthToken {
5445 challenge: 123,
5446 userId: 456,
5447 authenticatorId: 789,
5448 authenticatorType: kmhw_authenticator_type::ANY,
5449 timestamp: Timestamp { milliSeconds: 10 },
5450 mac: b"mac0".to_vec(),
5451 });
5452 std::thread::sleep(std::time::Duration::from_millis(1));
5453 db.insert_auth_token(&HardwareAuthToken {
5454 challenge: 123,
5455 userId: 457,
5456 authenticatorId: 789,
5457 authenticatorType: kmhw_authenticator_type::ANY,
5458 timestamp: Timestamp { milliSeconds: 12 },
5459 mac: b"mac1".to_vec(),
5460 });
5461 std::thread::sleep(std::time::Duration::from_millis(1));
5462 db.insert_auth_token(&HardwareAuthToken {
5463 challenge: 123,
5464 userId: 458,
5465 authenticatorId: 789,
5466 authenticatorType: kmhw_authenticator_type::ANY,
5467 timestamp: Timestamp { milliSeconds: 3 },
5468 mac: b"mac2".to_vec(),
5469 });
5470 // All three entries are in the database
5471 assert_eq!(db.perboot.auth_tokens_len(), 3);
5472 // It selected the most recent timestamp
5473 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5474 Ok(())
5475 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005476}