blob: 4ab42582468d7b57b1ef0f50bd7953a17e8f32fa [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
Janis Danisevskis66784c42021-01-27 08:40:25 -0800854 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
855 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
856
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700857 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800858 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800859 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800860 })?;
861 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700862 }
863
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 fn init_tables(tx: &Transaction) -> Result<()> {
865 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700866 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700867 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800868 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700869 domain INTEGER,
870 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800871 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800872 state INTEGER,
873 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700874 NO_PARAMS,
875 )
876 .context("Failed to initialize \"keyentry\" table.")?;
877
Janis Danisevskis66784c42021-01-27 08:40:25 -0800878 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800879 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
880 ON keyentry(id);",
881 NO_PARAMS,
882 )
883 .context("Failed to create index keyentry_id_index.")?;
884
885 tx.execute(
886 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
887 ON keyentry(domain, namespace, alias);",
888 NO_PARAMS,
889 )
890 .context("Failed to create index keyentry_domain_namespace_index.")?;
891
892 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700893 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
894 id INTEGER PRIMARY KEY,
895 subcomponent_type INTEGER,
896 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800897 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700898 NO_PARAMS,
899 )
900 .context("Failed to initialize \"blobentry\" table.")?;
901
Janis Danisevskis66784c42021-01-27 08:40:25 -0800902 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800903 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
904 ON blobentry(keyentryid);",
905 NO_PARAMS,
906 )
907 .context("Failed to create index blobentry_keyentryid_index.")?;
908
909 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800910 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
911 id INTEGER PRIMARY KEY,
912 blobentryid INTEGER,
913 tag INTEGER,
914 data ANY,
915 UNIQUE (blobentryid, tag));",
916 NO_PARAMS,
917 )
918 .context("Failed to initialize \"blobmetadata\" table.")?;
919
920 tx.execute(
921 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
922 ON blobmetadata(blobentryid);",
923 NO_PARAMS,
924 )
925 .context("Failed to create index blobmetadata_blobentryid_index.")?;
926
927 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700928 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000929 keyentryid INTEGER,
930 tag INTEGER,
931 data ANY,
932 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700933 NO_PARAMS,
934 )
935 .context("Failed to initialize \"keyparameter\" table.")?;
936
Janis Danisevskis66784c42021-01-27 08:40:25 -0800937 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800938 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
939 ON keyparameter(keyentryid);",
940 NO_PARAMS,
941 )
942 .context("Failed to create index keyparameter_keyentryid_index.")?;
943
944 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800945 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
946 keyentryid INTEGER,
947 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000948 data ANY,
949 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800950 NO_PARAMS,
951 )
952 .context("Failed to initialize \"keymetadata\" table.")?;
953
Janis Danisevskis66784c42021-01-27 08:40:25 -0800954 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800955 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
956 ON keymetadata(keyentryid);",
957 NO_PARAMS,
958 )
959 .context("Failed to create index keymetadata_keyentryid_index.")?;
960
961 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800962 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700963 id INTEGER UNIQUE,
964 grantee INTEGER,
965 keyentryid INTEGER,
966 access_vector INTEGER);",
967 NO_PARAMS,
968 )
969 .context("Failed to initialize \"grant\" table.")?;
970
Joel Galenson0891bc12020-07-20 10:37:03 -0700971 Ok(())
972 }
973
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700974 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700975 let conn =
976 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
977
Janis Danisevskis66784c42021-01-27 08:40:25 -0800978 loop {
979 if let Err(e) = conn
980 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
981 .context("Failed to attach database persistent.")
982 {
983 if Self::is_locked_error(&e) {
984 std::thread::sleep(std::time::Duration::from_micros(500));
985 continue;
986 } else {
987 return Err(e);
988 }
989 }
990 break;
991 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700992
Matthew Maurer4fb19112021-05-06 15:40:44 -0700993 // Drop the cache size from default (2M) to 0.5M
994 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
995 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -0700996
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700997 Ok(conn)
998 }
999
Seth Moore78c091f2021-04-09 21:38:30 +00001000 fn do_table_size_query(
1001 &mut self,
1002 storage_type: StatsdStorageType,
1003 query: &str,
1004 params: &[&str],
1005 ) -> Result<Keystore2StorageStats> {
1006 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1007 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1008 .with_context(|| {
1009 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1010 })
1011 .no_gc()
1012 })?;
1013 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1014 }
1015
1016 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1017 self.do_table_size_query(
1018 StatsdStorageType::Database,
1019 "SELECT page_count * page_size, freelist_count * page_size
1020 FROM pragma_page_count('persistent'),
1021 pragma_page_size('persistent'),
1022 persistent.pragma_freelist_count();",
1023 &[],
1024 )
1025 }
1026
1027 fn get_table_size(
1028 &mut self,
1029 storage_type: StatsdStorageType,
1030 schema: &str,
1031 table: &str,
1032 ) -> Result<Keystore2StorageStats> {
1033 self.do_table_size_query(
1034 storage_type,
1035 "SELECT pgsize,unused FROM dbstat(?1)
1036 WHERE name=?2 AND aggregate=TRUE;",
1037 &[schema, table],
1038 )
1039 }
1040
1041 /// Fetches a storage statisitics atom for a given storage type. For storage
1042 /// types that map to a table, information about the table's storage is
1043 /// returned. Requests for storage types that are not DB tables return None.
1044 pub fn get_storage_stat(
1045 &mut self,
1046 storage_type: StatsdStorageType,
1047 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001048 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1049
Seth Moore78c091f2021-04-09 21:38:30 +00001050 match storage_type {
1051 StatsdStorageType::Database => self.get_total_size(),
1052 StatsdStorageType::KeyEntry => {
1053 self.get_table_size(storage_type, "persistent", "keyentry")
1054 }
1055 StatsdStorageType::KeyEntryIdIndex => {
1056 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1057 }
1058 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1059 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1060 }
1061 StatsdStorageType::BlobEntry => {
1062 self.get_table_size(storage_type, "persistent", "blobentry")
1063 }
1064 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1065 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1066 }
1067 StatsdStorageType::KeyParameter => {
1068 self.get_table_size(storage_type, "persistent", "keyparameter")
1069 }
1070 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1071 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1072 }
1073 StatsdStorageType::KeyMetadata => {
1074 self.get_table_size(storage_type, "persistent", "keymetadata")
1075 }
1076 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1077 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1078 }
1079 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1080 StatsdStorageType::AuthToken => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001081 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1082 // reportable
1083 // Size provided is only an approximation
1084 Ok(Keystore2StorageStats {
1085 storage_type,
1086 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1087 as i64,
1088 unused_size: 0,
1089 })
Seth Moore78c091f2021-04-09 21:38:30 +00001090 }
1091 StatsdStorageType::BlobMetadata => {
1092 self.get_table_size(storage_type, "persistent", "blobmetadata")
1093 }
1094 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1095 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1096 }
1097 _ => Err(anyhow::Error::msg(format!(
1098 "Unsupported storage type: {}",
1099 storage_type as i32
1100 ))),
1101 }
1102 }
1103
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001104 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001105 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1106 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001107 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1108 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001109 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001110 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001111 blob_ids_to_delete: &[i64],
1112 max_blobs: usize,
1113 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001114 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001115 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001116 // Delete the given blobs.
1117 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001118 tx.execute(
1119 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001120 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001121 )
1122 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001123 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1124 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001125 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001126
1127 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1128
Janis Danisevskis3395f862021-05-06 10:54:17 -07001129 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1130 let result: Vec<(i64, Vec<u8>)> = {
1131 let mut stmt = tx
1132 .prepare(
1133 "SELECT id, blob FROM persistent.blobentry
1134 WHERE subcomponent_type = ?
1135 AND (
1136 id NOT IN (
1137 SELECT MAX(id) FROM persistent.blobentry
1138 WHERE subcomponent_type = ?
1139 GROUP BY keyentryid, subcomponent_type
1140 )
1141 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1142 ) LIMIT ?;",
1143 )
1144 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001145
Janis Danisevskis3395f862021-05-06 10:54:17 -07001146 let rows = stmt
1147 .query_map(
1148 params![
1149 SubComponentType::KEY_BLOB,
1150 SubComponentType::KEY_BLOB,
1151 max_blobs as i64,
1152 ],
1153 |row| Ok((row.get(0)?, row.get(1)?)),
1154 )
1155 .context("Trying to query superseded blob.")?;
1156
1157 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1158 .context("Trying to extract superseded blobs.")?
1159 };
1160
1161 let result = result
1162 .into_iter()
1163 .map(|(blob_id, blob)| {
1164 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1165 })
1166 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1167 .context("Trying to load blob metadata.")?;
1168 if !result.is_empty() {
1169 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001170 }
1171
1172 // We did not find any superseded key blob, so let's remove other superseded blob in
1173 // one transaction.
1174 tx.execute(
1175 "DELETE FROM persistent.blobentry
1176 WHERE NOT subcomponent_type = ?
1177 AND (
1178 id NOT IN (
1179 SELECT MAX(id) FROM persistent.blobentry
1180 WHERE NOT subcomponent_type = ?
1181 GROUP BY keyentryid, subcomponent_type
1182 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1183 );",
1184 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1185 )
1186 .context("Trying to purge superseded blobs.")?;
1187
Janis Danisevskis3395f862021-05-06 10:54:17 -07001188 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001189 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001190 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001191 }
1192
1193 /// This maintenance function should be called only once before the database is used for the
1194 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1195 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1196 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1197 /// Keystore crashed at some point during key generation. Callers may want to log such
1198 /// occurrences.
1199 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1200 /// it to `KeyLifeCycle::Live` may have grants.
1201 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001202 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1203
Janis Danisevskis66784c42021-01-27 08:40:25 -08001204 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1205 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001206 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1207 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1208 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001209 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001210 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001211 })
1212 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001213 }
1214
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001215 /// Checks if a key exists with given key type and key descriptor properties.
1216 pub fn key_exists(
1217 &mut self,
1218 domain: Domain,
1219 nspace: i64,
1220 alias: &str,
1221 key_type: KeyType,
1222 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001223 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1224
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001225 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1226 let key_descriptor =
1227 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1228 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1229 match result {
1230 Ok(_) => Ok(true),
1231 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1232 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1233 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1234 },
1235 }
1236 .no_gc()
1237 })
1238 .context("In key_exists.")
1239 }
1240
Hasini Gunasingheda895552021-01-27 19:34:37 +00001241 /// Stores a super key in the database.
1242 pub fn store_super_key(
1243 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001244 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001245 key_type: &SuperKeyType,
1246 blob: &[u8],
1247 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001248 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001249 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001250 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1251
Hasini Gunasingheda895552021-01-27 19:34:37 +00001252 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1253 let key_id = Self::insert_with_retry(|id| {
1254 tx.execute(
1255 "INSERT into persistent.keyentry
1256 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001257 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001258 params![
1259 id,
1260 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001261 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001262 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001263 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001264 KeyLifeCycle::Live,
1265 &KEYSTORE_UUID,
1266 ],
1267 )
1268 })
1269 .context("Failed to insert into keyentry table.")?;
1270
Paul Crowley8d5b2532021-03-19 10:53:07 -07001271 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1272
Hasini Gunasingheda895552021-01-27 19:34:37 +00001273 Self::set_blob_internal(
1274 &tx,
1275 key_id,
1276 SubComponentType::KEY_BLOB,
1277 Some(blob),
1278 Some(blob_metadata),
1279 )
1280 .context("Failed to store key blob.")?;
1281
1282 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1283 .context("Trying to load key components.")
1284 .no_gc()
1285 })
1286 .context("In store_super_key.")
1287 }
1288
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001289 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001290 pub fn load_super_key(
1291 &mut self,
1292 key_type: &SuperKeyType,
1293 user_id: u32,
1294 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001295 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1296
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001297 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1298 let key_descriptor = KeyDescriptor {
1299 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001300 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001301 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001302 blob: None,
1303 };
1304 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1305 match id {
1306 Ok(id) => {
1307 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1308 .context("In load_super_key. Failed to load key entry.")?;
1309 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1310 }
1311 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1312 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1313 _ => Err(error).context("In load_super_key."),
1314 },
1315 }
1316 .no_gc()
1317 })
1318 .context("In load_super_key.")
1319 }
1320
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001321 /// Atomically loads a key entry and associated metadata or creates it using the
1322 /// callback create_new_key callback. The callback is called during a database
1323 /// transaction. This means that implementers should be mindful about using
1324 /// blocking operations such as IPC or grabbing mutexes.
1325 pub fn get_or_create_key_with<F>(
1326 &mut self,
1327 domain: Domain,
1328 namespace: i64,
1329 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001330 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001331 create_new_key: F,
1332 ) -> Result<(KeyIdGuard, KeyEntry)>
1333 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001334 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001335 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001336 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1337
Janis Danisevskis66784c42021-01-27 08:40:25 -08001338 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1339 let id = {
1340 let mut stmt = tx
1341 .prepare(
1342 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001343 WHERE
1344 key_type = ?
1345 AND domain = ?
1346 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001347 AND alias = ?
1348 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001349 )
1350 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1351 let mut rows = stmt
1352 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1353 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001354
Janis Danisevskis66784c42021-01-27 08:40:25 -08001355 db_utils::with_rows_extract_one(&mut rows, |row| {
1356 Ok(match row {
1357 Some(r) => r.get(0).context("Failed to unpack id.")?,
1358 None => None,
1359 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001360 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001361 .context("In get_or_create_key_with.")?
1362 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001363
Janis Danisevskis66784c42021-01-27 08:40:25 -08001364 let (id, entry) = match id {
1365 Some(id) => (
1366 id,
1367 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1368 .context("In get_or_create_key_with.")?,
1369 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001370
Janis Danisevskis66784c42021-01-27 08:40:25 -08001371 None => {
1372 let id = Self::insert_with_retry(|id| {
1373 tx.execute(
1374 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001375 (id, key_type, domain, namespace, alias, state, km_uuid)
1376 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001377 params![
1378 id,
1379 KeyType::Super,
1380 domain.0,
1381 namespace,
1382 alias,
1383 KeyLifeCycle::Live,
1384 km_uuid,
1385 ],
1386 )
1387 })
1388 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001389
Janis Danisevskis66784c42021-01-27 08:40:25 -08001390 let (blob, metadata) =
1391 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001392 Self::set_blob_internal(
1393 &tx,
1394 id,
1395 SubComponentType::KEY_BLOB,
1396 Some(&blob),
1397 Some(&metadata),
1398 )
Paul Crowley7a658392021-03-18 17:08:20 -07001399 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001401 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001402 KeyEntry {
1403 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001404 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001405 pure_cert: false,
1406 ..Default::default()
1407 },
1408 )
1409 }
1410 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001411 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 })
1413 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001414 }
1415
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1417 /// waiting for the database file to become available. This makes it
1418 /// impossible to successfully recover from a locked database when the
1419 /// transaction holding the device busy is in the same process on a
1420 /// different connection. As a result the busy handler has to time out and
1421 /// fail in order to make progress.
1422 ///
1423 /// Instead, we set the busy handler to None (return immediately). And catch
1424 /// Busy and Locked errors (the latter occur on in memory databases with
1425 /// shared cache, e.g., the per-boot database.) and restart the transaction
1426 /// after a grace period of half a millisecond.
1427 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001428 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001429 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1430 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001431 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1432 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001433 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001434 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001435 loop {
1436 match self
1437 .conn
1438 .transaction_with_behavior(behavior)
1439 .context("In with_transaction.")
1440 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1441 .and_then(|(result, tx)| {
1442 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1443 Ok(result)
1444 }) {
1445 Ok(result) => break Ok(result),
1446 Err(e) => {
1447 if Self::is_locked_error(&e) {
1448 std::thread::sleep(std::time::Duration::from_micros(500));
1449 continue;
1450 } else {
1451 return Err(e).context("In with_transaction.");
1452 }
1453 }
1454 }
1455 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001456 .map(|(need_gc, result)| {
1457 if need_gc {
1458 if let Some(ref gc) = self.gc {
1459 gc.notify_gc();
1460 }
1461 }
1462 result
1463 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001464 }
1465
1466 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001467 matches!(
1468 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1469 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1470 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1471 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001472 }
1473
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001474 /// Creates a new key entry and allocates a new randomized id for the new key.
1475 /// The key id gets associated with a domain and namespace but not with an alias.
1476 /// To complete key generation `rebind_alias` should be called after all of the
1477 /// key artifacts, i.e., blobs and parameters have been associated with the new
1478 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1479 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001480 pub fn create_key_entry(
1481 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001482 domain: &Domain,
1483 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001484 km_uuid: &Uuid,
1485 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001486 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1487
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001488 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001489 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001490 })
1491 .context("In create_key_entry.")
1492 }
1493
1494 fn create_key_entry_internal(
1495 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001496 domain: &Domain,
1497 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001498 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001499 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001500 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001501 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001502 _ => {
1503 return Err(KsError::sys())
1504 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1505 }
1506 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001507 Ok(KEY_ID_LOCK.get(
1508 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001509 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001510 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001511 (id, key_type, domain, namespace, alias, state, km_uuid)
1512 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001513 params![
1514 id,
1515 KeyType::Client,
1516 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001517 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001518 KeyLifeCycle::Existing,
1519 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001520 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001521 )
1522 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001523 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001524 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001525 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001526
Max Bires2b2e6562020-09-22 11:22:36 -07001527 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1528 /// The key id gets associated with a domain and namespace later but not with an alias. The
1529 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1530 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1531 /// a key.
1532 pub fn create_attestation_key_entry(
1533 &mut self,
1534 maced_public_key: &[u8],
1535 raw_public_key: &[u8],
1536 private_key: &[u8],
1537 km_uuid: &Uuid,
1538 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001539 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1540
Max Bires2b2e6562020-09-22 11:22:36 -07001541 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1542 let key_id = KEY_ID_LOCK.get(
1543 Self::insert_with_retry(|id| {
1544 tx.execute(
1545 "INSERT into persistent.keyentry
1546 (id, key_type, domain, namespace, alias, state, km_uuid)
1547 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1548 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1549 )
1550 })
1551 .context("In create_key_entry")?,
1552 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001553 Self::set_blob_internal(
1554 &tx,
1555 key_id.0,
1556 SubComponentType::KEY_BLOB,
1557 Some(private_key),
1558 None,
1559 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001560 let mut metadata = KeyMetaData::new();
1561 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1562 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1563 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001564 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001565 })
1566 .context("In create_attestation_key_entry")
1567 }
1568
Janis Danisevskis377d1002021-01-27 19:07:48 -08001569 /// Set a new blob and associates it with the given key id. Each blob
1570 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001571 /// Each key can have one of each sub component type associated. If more
1572 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001573 /// will get garbage collected.
1574 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1575 /// removed by setting blob to None.
1576 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001577 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001578 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001579 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001580 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001581 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001582 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001583 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1584
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001585 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001586 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001587 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001588 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001589 }
1590
Janis Danisevskiseed69842021-02-18 20:04:10 -08001591 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1592 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1593 /// We use this to insert key blobs into the database which can then be garbage collected
1594 /// lazily by the key garbage collector.
1595 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001596 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1597
Janis Danisevskiseed69842021-02-18 20:04:10 -08001598 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1599 Self::set_blob_internal(
1600 &tx,
1601 Self::UNASSIGNED_KEY_ID,
1602 SubComponentType::KEY_BLOB,
1603 Some(blob),
1604 Some(blob_metadata),
1605 )
1606 .need_gc()
1607 })
1608 .context("In set_deleted_blob.")
1609 }
1610
Janis Danisevskis377d1002021-01-27 19:07:48 -08001611 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001612 tx: &Transaction,
1613 key_id: i64,
1614 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001615 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001616 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001617 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001618 match (blob, sc_type) {
1619 (Some(blob), _) => {
1620 tx.execute(
1621 "INSERT INTO persistent.blobentry
1622 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1623 params![sc_type, key_id, blob],
1624 )
1625 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001626 if let Some(blob_metadata) = blob_metadata {
1627 let blob_id = tx
1628 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1629 row.get(0)
1630 })
1631 .context("In set_blob_internal: Failed to get new blob id.")?;
1632 blob_metadata
1633 .store_in_db(blob_id, tx)
1634 .context("In set_blob_internal: Trying to store blob metadata.")?;
1635 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001636 }
1637 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1638 tx.execute(
1639 "DELETE FROM persistent.blobentry
1640 WHERE subcomponent_type = ? AND keyentryid = ?;",
1641 params![sc_type, key_id],
1642 )
1643 .context("In set_blob_internal: Failed to delete blob.")?;
1644 }
1645 (None, _) => {
1646 return Err(KsError::sys())
1647 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1648 }
1649 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001650 Ok(())
1651 }
1652
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001653 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1654 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001655 #[cfg(test)]
1656 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001657 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001658 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001659 })
1660 .context("In insert_keyparameter.")
1661 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001662
Janis Danisevskis66784c42021-01-27 08:40:25 -08001663 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001664 tx: &Transaction,
1665 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001666 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001667 ) -> Result<()> {
1668 let mut stmt = tx
1669 .prepare(
1670 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1671 VALUES (?, ?, ?, ?);",
1672 )
1673 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1674
Janis Danisevskis66784c42021-01-27 08:40:25 -08001675 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001676 stmt.insert(params![
1677 key_id.0,
1678 p.get_tag().0,
1679 p.key_parameter_value(),
1680 p.security_level().0
1681 ])
1682 .with_context(|| {
1683 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1684 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001685 }
1686 Ok(())
1687 }
1688
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001689 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001690 #[cfg(test)]
1691 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001692 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001693 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001694 })
1695 .context("In insert_key_metadata.")
1696 }
1697
Max Bires2b2e6562020-09-22 11:22:36 -07001698 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1699 /// on the public key.
1700 pub fn store_signed_attestation_certificate_chain(
1701 &mut self,
1702 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001703 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001704 cert_chain: &[u8],
1705 expiration_date: i64,
1706 km_uuid: &Uuid,
1707 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001708 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1709
Max Bires2b2e6562020-09-22 11:22:36 -07001710 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1711 let mut stmt = tx
1712 .prepare(
1713 "SELECT keyentryid
1714 FROM persistent.keymetadata
1715 WHERE tag = ? AND data = ? AND keyentryid IN
1716 (SELECT id
1717 FROM persistent.keyentry
1718 WHERE
1719 alias IS NULL AND
1720 domain IS NULL AND
1721 namespace IS NULL AND
1722 key_type = ? AND
1723 km_uuid = ?);",
1724 )
1725 .context("Failed to store attestation certificate chain.")?;
1726 let mut rows = stmt
1727 .query(params![
1728 KeyMetaData::AttestationRawPubKey,
1729 raw_public_key,
1730 KeyType::Attestation,
1731 km_uuid
1732 ])
1733 .context("Failed to fetch keyid")?;
1734 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1735 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1736 .get(0)
1737 .context("Failed to unpack id.")
1738 })
1739 .context("Failed to get key_id.")?;
1740 let num_updated = tx
1741 .execute(
1742 "UPDATE persistent.keyentry
1743 SET alias = ?
1744 WHERE id = ?;",
1745 params!["signed", key_id],
1746 )
1747 .context("Failed to update alias.")?;
1748 if num_updated != 1 {
1749 return Err(KsError::sys()).context("Alias not updated for the key.");
1750 }
1751 let mut metadata = KeyMetaData::new();
1752 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1753 expiration_date,
1754 )));
1755 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001756 Self::set_blob_internal(
1757 &tx,
1758 key_id,
1759 SubComponentType::CERT_CHAIN,
1760 Some(cert_chain),
1761 None,
1762 )
1763 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001764 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1765 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001766 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001767 })
1768 .context("In store_signed_attestation_certificate_chain: ")
1769 }
1770
1771 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1772 /// currently have a key assigned to it.
1773 pub fn assign_attestation_key(
1774 &mut self,
1775 domain: Domain,
1776 namespace: i64,
1777 km_uuid: &Uuid,
1778 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001779 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1780
Max Bires2b2e6562020-09-22 11:22:36 -07001781 match domain {
1782 Domain::APP | Domain::SELINUX => {}
1783 _ => {
1784 return Err(KsError::sys()).context(format!(
1785 concat!(
1786 "In assign_attestation_key: Domain {:?} ",
1787 "must be either App or SELinux.",
1788 ),
1789 domain
1790 ));
1791 }
1792 }
1793 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1794 let result = tx
1795 .execute(
1796 "UPDATE persistent.keyentry
1797 SET domain=?1, namespace=?2
1798 WHERE
1799 id =
1800 (SELECT MIN(id)
1801 FROM persistent.keyentry
1802 WHERE ALIAS IS NOT NULL
1803 AND domain IS NULL
1804 AND key_type IS ?3
1805 AND state IS ?4
1806 AND km_uuid IS ?5)
1807 AND
1808 (SELECT COUNT(*)
1809 FROM persistent.keyentry
1810 WHERE domain=?1
1811 AND namespace=?2
1812 AND key_type IS ?3
1813 AND state IS ?4
1814 AND km_uuid IS ?5) = 0;",
1815 params![
1816 domain.0 as u32,
1817 namespace,
1818 KeyType::Attestation,
1819 KeyLifeCycle::Live,
1820 km_uuid,
1821 ],
1822 )
1823 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001824 if result == 0 {
1825 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1826 } else if result > 1 {
1827 return Err(KsError::sys())
1828 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001829 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001830 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001831 })
1832 .context("In assign_attestation_key: ")
1833 }
1834
1835 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1836 /// provisioning server, or the maximum number available if there are not num_keys number of
1837 /// entries in the table.
1838 pub fn fetch_unsigned_attestation_keys(
1839 &mut self,
1840 num_keys: i32,
1841 km_uuid: &Uuid,
1842 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001843 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1844
Max Bires2b2e6562020-09-22 11:22:36 -07001845 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1846 let mut stmt = tx
1847 .prepare(
1848 "SELECT data
1849 FROM persistent.keymetadata
1850 WHERE tag = ? AND keyentryid IN
1851 (SELECT id
1852 FROM persistent.keyentry
1853 WHERE
1854 alias IS NULL AND
1855 domain IS NULL AND
1856 namespace IS NULL AND
1857 key_type = ? AND
1858 km_uuid = ?
1859 LIMIT ?);",
1860 )
1861 .context("Failed to prepare statement")?;
1862 let rows = stmt
1863 .query_map(
1864 params![
1865 KeyMetaData::AttestationMacedPublicKey,
1866 KeyType::Attestation,
1867 km_uuid,
1868 num_keys
1869 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001870 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001871 )?
1872 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1873 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001874 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001875 })
1876 .context("In fetch_unsigned_attestation_keys")
1877 }
1878
1879 /// Removes any keys that have expired as of the current time. Returns the number of keys
1880 /// marked unreferenced that are bound to be garbage collected.
1881 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001882 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1883
Max Bires2b2e6562020-09-22 11:22:36 -07001884 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1885 let mut stmt = tx
1886 .prepare(
1887 "SELECT keyentryid, data
1888 FROM persistent.keymetadata
1889 WHERE tag = ? AND keyentryid IN
1890 (SELECT id
1891 FROM persistent.keyentry
1892 WHERE key_type = ?);",
1893 )
1894 .context("Failed to prepare query")?;
1895 let key_ids_to_check = stmt
1896 .query_map(
1897 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1898 |row| Ok((row.get(0)?, row.get(1)?)),
1899 )?
1900 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1901 .context("Failed to get date metadata")?;
1902 let curr_time = DateTime::from_millis_epoch(
1903 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1904 );
1905 let mut num_deleted = 0;
1906 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1907 if Self::mark_unreferenced(&tx, id)? {
1908 num_deleted += 1;
1909 }
1910 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001911 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001912 })
1913 .context("In delete_expired_attestation_keys: ")
1914 }
1915
Max Bires60d7ed12021-03-05 15:59:22 -08001916 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1917 /// they are in. This is useful primarily as a testing mechanism.
1918 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001919 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1920
Max Bires60d7ed12021-03-05 15:59:22 -08001921 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1922 let mut stmt = tx
1923 .prepare(
1924 "SELECT id FROM persistent.keyentry
1925 WHERE key_type IS ?;",
1926 )
1927 .context("Failed to prepare statement")?;
1928 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001929 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001930 .collect::<rusqlite::Result<Vec<i64>>>()
1931 .context("Failed to execute statement")?;
1932 let num_deleted = keys_to_delete
1933 .iter()
1934 .map(|id| Self::mark_unreferenced(&tx, *id))
1935 .collect::<Result<Vec<bool>>>()
1936 .context("Failed to execute mark_unreferenced on a keyid")?
1937 .into_iter()
1938 .filter(|result| *result)
1939 .count() as i64;
1940 Ok(num_deleted).do_gc(num_deleted != 0)
1941 })
1942 .context("In delete_all_attestation_keys: ")
1943 }
1944
Max Bires2b2e6562020-09-22 11:22:36 -07001945 /// Counts the number of keys that will expire by the provided epoch date and the number of
1946 /// keys not currently assigned to a domain.
1947 pub fn get_attestation_pool_status(
1948 &mut self,
1949 date: i64,
1950 km_uuid: &Uuid,
1951 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001952 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1953
Max Bires2b2e6562020-09-22 11:22:36 -07001954 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1955 let mut stmt = tx.prepare(
1956 "SELECT data
1957 FROM persistent.keymetadata
1958 WHERE tag = ? AND keyentryid IN
1959 (SELECT id
1960 FROM persistent.keyentry
1961 WHERE alias IS NOT NULL
1962 AND key_type = ?
1963 AND km_uuid = ?
1964 AND state = ?);",
1965 )?;
1966 let times = stmt
1967 .query_map(
1968 params![
1969 KeyMetaData::AttestationExpirationDate,
1970 KeyType::Attestation,
1971 km_uuid,
1972 KeyLifeCycle::Live
1973 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001974 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001975 )?
1976 .collect::<rusqlite::Result<Vec<DateTime>>>()
1977 .context("Failed to execute metadata statement")?;
1978 let expiring =
1979 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1980 as i32;
1981 stmt = tx.prepare(
1982 "SELECT alias, domain
1983 FROM persistent.keyentry
1984 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1985 )?;
1986 let rows = stmt
1987 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1988 Ok((row.get(0)?, row.get(1)?))
1989 })?
1990 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1991 .context("Failed to execute keyentry statement")?;
1992 let mut unassigned = 0i32;
1993 let mut attested = 0i32;
1994 let total = rows.len() as i32;
1995 for (alias, domain) in rows {
1996 match (alias, domain) {
1997 (Some(_alias), None) => {
1998 attested += 1;
1999 unassigned += 1;
2000 }
2001 (Some(_alias), Some(_domain)) => {
2002 attested += 1;
2003 }
2004 _ => {}
2005 }
2006 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002007 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002008 })
2009 .context("In get_attestation_pool_status: ")
2010 }
2011
2012 /// Fetches the private key and corresponding certificate chain assigned to a
2013 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2014 /// not assigned, or one CertificateChain.
2015 pub fn retrieve_attestation_key_and_cert_chain(
2016 &mut self,
2017 domain: Domain,
2018 namespace: i64,
2019 km_uuid: &Uuid,
2020 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002021 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2022
Max Bires2b2e6562020-09-22 11:22:36 -07002023 match domain {
2024 Domain::APP | Domain::SELINUX => {}
2025 _ => {
2026 return Err(KsError::sys())
2027 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2028 }
2029 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002030 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2031 let mut stmt = tx.prepare(
2032 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002033 FROM persistent.blobentry
2034 WHERE keyentryid IN
2035 (SELECT id
2036 FROM persistent.keyentry
2037 WHERE key_type = ?
2038 AND domain = ?
2039 AND namespace = ?
2040 AND state = ?
2041 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002042 )?;
2043 let rows = stmt
2044 .query_map(
2045 params![
2046 KeyType::Attestation,
2047 domain.0 as u32,
2048 namespace,
2049 KeyLifeCycle::Live,
2050 km_uuid
2051 ],
2052 |row| Ok((row.get(0)?, row.get(1)?)),
2053 )?
2054 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002055 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002056 if rows.is_empty() {
2057 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002058 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002059 return Err(KsError::sys()).context(format!(
2060 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002061 "Expected to get a single attestation",
2062 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2063 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002064 rows.len()
2065 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002066 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002067 let mut km_blob: Vec<u8> = Vec::new();
2068 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002069 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002070 for row in rows {
2071 let sub_type: SubComponentType = row.0;
2072 match sub_type {
2073 SubComponentType::KEY_BLOB => {
2074 km_blob = row.1;
2075 }
2076 SubComponentType::CERT_CHAIN => {
2077 cert_chain_blob = row.1;
2078 }
Max Biresb2e1d032021-02-08 21:35:05 -08002079 SubComponentType::CERT => {
2080 batch_cert_blob = row.1;
2081 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2083 }
2084 }
2085 Ok(Some(CertificateChain {
2086 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002087 batch_cert: batch_cert_blob,
2088 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002089 }))
2090 .no_gc()
2091 })
Max Biresb2e1d032021-02-08 21:35:05 -08002092 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002093 }
2094
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002095 /// Updates the alias column of the given key id `newid` with the given alias,
2096 /// and atomically, removes the alias, domain, and namespace from another row
2097 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002098 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2099 /// collector.
2100 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002101 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002102 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002103 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002104 domain: &Domain,
2105 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002106 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002107 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002108 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002109 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002110 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002111 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002112 domain
2113 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002114 }
2115 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002116 let updated = tx
2117 .execute(
2118 "UPDATE persistent.keyentry
2119 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002120 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002121 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2122 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002123 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002124 let result = tx
2125 .execute(
2126 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 SET alias = ?, state = ?
2128 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2129 params![
2130 alias,
2131 KeyLifeCycle::Live,
2132 newid.0,
2133 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002134 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002135 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002136 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002137 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002138 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002139 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002140 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002141 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002142 result
2143 ));
2144 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002145 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002146 }
2147
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002148 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2149 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2150 pub fn migrate_key_namespace(
2151 &mut self,
2152 key_id_guard: KeyIdGuard,
2153 destination: &KeyDescriptor,
2154 caller_uid: u32,
2155 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2156 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002157 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2158
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002159 let destination = match destination.domain {
2160 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2161 Domain::SELINUX => (*destination).clone(),
2162 domain => {
2163 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2164 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2165 }
2166 };
2167
2168 // Security critical: Must return immediately on failure. Do not remove the '?';
2169 check_permission(&destination)
2170 .context("In migrate_key_namespace: Trying to check permission.")?;
2171
2172 let alias = destination
2173 .alias
2174 .as_ref()
2175 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2176 .context("In migrate_key_namespace: Alias must be specified.")?;
2177
2178 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2179 // Query the destination location. If there is a key, the migration request fails.
2180 if tx
2181 .query_row(
2182 "SELECT id FROM persistent.keyentry
2183 WHERE alias = ? AND domain = ? AND namespace = ?;",
2184 params![alias, destination.domain.0, destination.nspace],
2185 |_| Ok(()),
2186 )
2187 .optional()
2188 .context("Failed to query destination.")?
2189 .is_some()
2190 {
2191 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2192 .context("Target already exists.");
2193 }
2194
2195 let updated = tx
2196 .execute(
2197 "UPDATE persistent.keyentry
2198 SET alias = ?, domain = ?, namespace = ?
2199 WHERE id = ?;",
2200 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2201 )
2202 .context("Failed to update key entry.")?;
2203
2204 if updated != 1 {
2205 return Err(KsError::sys())
2206 .context(format!("Update succeeded, but {} rows were updated.", updated));
2207 }
2208 Ok(()).no_gc()
2209 })
2210 .context("In migrate_key_namespace:")
2211 }
2212
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002213 /// Store a new key in a single transaction.
2214 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2215 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002216 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2217 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002218 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002219 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002220 key: &KeyDescriptor,
2221 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002222 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002223 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002224 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002225 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002226 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002227 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2228
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002229 let (alias, domain, namespace) = match key {
2230 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2231 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2232 (alias, key.domain, nspace)
2233 }
2234 _ => {
2235 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2236 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2237 }
2238 };
2239 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002240 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002241 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002242 let (blob, blob_metadata) = *blob_info;
2243 Self::set_blob_internal(
2244 tx,
2245 key_id.id(),
2246 SubComponentType::KEY_BLOB,
2247 Some(blob),
2248 Some(&blob_metadata),
2249 )
2250 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002251 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002252 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002253 .context("Trying to insert the certificate.")?;
2254 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002255 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002256 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002257 tx,
2258 key_id.id(),
2259 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002260 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002261 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002262 )
2263 .context("Trying to insert the certificate chain.")?;
2264 }
2265 Self::insert_keyparameter_internal(tx, &key_id, params)
2266 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002267 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002268 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002269 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002270 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 })
2272 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002273 }
2274
Janis Danisevskis377d1002021-01-27 19:07:48 -08002275 /// Store a new certificate
2276 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2277 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002278 pub fn store_new_certificate(
2279 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002280 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002281 cert: &[u8],
2282 km_uuid: &Uuid,
2283 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002284 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2285
Janis Danisevskis377d1002021-01-27 19:07:48 -08002286 let (alias, domain, namespace) = match key {
2287 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2288 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2289 (alias, key.domain, nspace)
2290 }
2291 _ => {
2292 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2293 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2294 )
2295 }
2296 };
2297 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002298 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002299 .context("Trying to create new key entry.")?;
2300
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002301 Self::set_blob_internal(
2302 tx,
2303 key_id.id(),
2304 SubComponentType::CERT_CHAIN,
2305 Some(cert),
2306 None,
2307 )
2308 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002309
2310 let mut metadata = KeyMetaData::new();
2311 metadata.add(KeyMetaEntry::CreationDate(
2312 DateTime::now().context("Trying to make creation time.")?,
2313 ));
2314
2315 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2316
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002317 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002318 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002319 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002320 })
2321 .context("In store_new_certificate.")
2322 }
2323
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002324 // Helper function loading the key_id given the key descriptor
2325 // tuple comprising domain, namespace, and alias.
2326 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002327 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002328 let alias = key
2329 .alias
2330 .as_ref()
2331 .map_or_else(|| Err(KsError::sys()), Ok)
2332 .context("In load_key_entry_id: Alias must be specified.")?;
2333 let mut stmt = tx
2334 .prepare(
2335 "SELECT id FROM persistent.keyentry
2336 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002337 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002338 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002339 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002340 AND alias = ?
2341 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002342 )
2343 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2344 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002345 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002346 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002347 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002348 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002349 .get(0)
2350 .context("Failed to unpack id.")
2351 })
2352 .context("In load_key_entry_id.")
2353 }
2354
2355 /// This helper function completes the access tuple of a key, which is required
2356 /// to perform access control. The strategy depends on the `domain` field in the
2357 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002358 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002359 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002360 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002361 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002362 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002363 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002364 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002365 /// `namespace`.
2366 /// In each case the information returned is sufficient to perform the access
2367 /// check and the key id can be used to load further key artifacts.
2368 fn load_access_tuple(
2369 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002370 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002371 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002372 caller_uid: u32,
2373 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2374 match key.domain {
2375 // Domain App or SELinux. In this case we load the key_id from
2376 // the keyentry database for further loading of key components.
2377 // We already have the full access tuple to perform access control.
2378 // The only distinction is that we use the caller_uid instead
2379 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002380 // Domain::APP.
2381 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002382 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002383 if access_key.domain == Domain::APP {
2384 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002385 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002386 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002387 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002388
2389 Ok((key_id, access_key, None))
2390 }
2391
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002392 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002393 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002394 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002395 let mut stmt = tx
2396 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002397 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002398 WHERE grantee = ? AND id = ?;",
2399 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002400 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002401 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002402 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002403 .context("Domain:Grant: query failed.")?;
2404 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002405 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002406 let r =
2407 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408 Ok((
2409 r.get(0).context("Failed to unpack key_id.")?,
2410 r.get(1).context("Failed to unpack access_vector.")?,
2411 ))
2412 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002413 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002414 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002415 }
2416
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002417 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002418 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002419 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002420 let (domain, namespace): (Domain, i64) = {
2421 let mut stmt = tx
2422 .prepare(
2423 "SELECT domain, namespace FROM persistent.keyentry
2424 WHERE
2425 id = ?
2426 AND state = ?;",
2427 )
2428 .context("Domain::KEY_ID: prepare statement failed")?;
2429 let mut rows = stmt
2430 .query(params![key.nspace, KeyLifeCycle::Live])
2431 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002432 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002433 let r =
2434 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002435 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002436 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002437 r.get(1).context("Failed to unpack namespace.")?,
2438 ))
2439 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002440 .context("Domain::KEY_ID.")?
2441 };
2442
2443 // We may use a key by id after loading it by grant.
2444 // In this case we have to check if the caller has a grant for this particular
2445 // key. We can skip this if we already know that the caller is the owner.
2446 // But we cannot know this if domain is anything but App. E.g. in the case
2447 // of Domain::SELINUX we have to speculatively check for grants because we have to
2448 // consult the SEPolicy before we know if the caller is the owner.
2449 let access_vector: Option<KeyPermSet> =
2450 if domain != Domain::APP || namespace != caller_uid as i64 {
2451 let access_vector: Option<i32> = tx
2452 .query_row(
2453 "SELECT access_vector FROM persistent.grant
2454 WHERE grantee = ? AND keyentryid = ?;",
2455 params![caller_uid as i64, key.nspace],
2456 |row| row.get(0),
2457 )
2458 .optional()
2459 .context("Domain::KEY_ID: query grant failed.")?;
2460 access_vector.map(|p| p.into())
2461 } else {
2462 None
2463 };
2464
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002465 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002466 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002467 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002468 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002469
Janis Danisevskis45760022021-01-19 16:34:10 -08002470 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002471 }
2472 _ => Err(anyhow!(KsError::sys())),
2473 }
2474 }
2475
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002476 fn load_blob_components(
2477 key_id: i64,
2478 load_bits: KeyEntryLoadBits,
2479 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002480 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002481 let mut stmt = tx
2482 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002483 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002484 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2485 )
2486 .context("In load_blob_components: prepare statement failed.")?;
2487
2488 let mut rows =
2489 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2490
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002491 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002492 let mut cert_blob: Option<Vec<u8>> = None;
2493 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002494 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002495 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002496 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002497 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002498 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002499 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2500 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002501 key_blob = Some((
2502 row.get(0).context("Failed to extract key blob id.")?,
2503 row.get(2).context("Failed to extract key blob.")?,
2504 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002505 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002506 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002507 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002508 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002509 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002510 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002511 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002512 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002513 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002514 (SubComponentType::CERT, _, _)
2515 | (SubComponentType::CERT_CHAIN, _, _)
2516 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002517 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2518 }
2519 Ok(())
2520 })
2521 .context("In load_blob_components.")?;
2522
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002523 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2524 Ok(Some((
2525 blob,
2526 BlobMetaData::load_from_db(blob_id, tx)
2527 .context("In load_blob_components: Trying to load blob_metadata.")?,
2528 )))
2529 })?;
2530
2531 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002532 }
2533
2534 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2535 let mut stmt = tx
2536 .prepare(
2537 "SELECT tag, data, security_level from persistent.keyparameter
2538 WHERE keyentryid = ?;",
2539 )
2540 .context("In load_key_parameters: prepare statement failed.")?;
2541
2542 let mut parameters: Vec<KeyParameter> = Vec::new();
2543
2544 let mut rows =
2545 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002546 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002547 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2548 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002549 parameters.push(
2550 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2551 .context("Failed to read KeyParameter.")?,
2552 );
2553 Ok(())
2554 })
2555 .context("In load_key_parameters.")?;
2556
2557 Ok(parameters)
2558 }
2559
Qi Wub9433b52020-12-01 14:52:46 +08002560 /// Decrements the usage count of a limited use key. This function first checks whether the
2561 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2562 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2563 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002564 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002565 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2566
Qi Wub9433b52020-12-01 14:52:46 +08002567 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2568 let limit: Option<i32> = tx
2569 .query_row(
2570 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2571 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2572 |row| row.get(0),
2573 )
2574 .optional()
2575 .context("Trying to load usage count")?;
2576
2577 let limit = limit
2578 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2579 .context("The Key no longer exists. Key is exhausted.")?;
2580
2581 tx.execute(
2582 "UPDATE persistent.keyparameter
2583 SET data = data - 1
2584 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2585 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2586 )
2587 .context("Failed to update key usage count.")?;
2588
2589 match limit {
2590 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002591 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002592 .context("Trying to mark limited use key for deletion."),
2593 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002594 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002595 }
2596 })
2597 .context("In check_and_update_key_usage_count.")
2598 }
2599
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002600 /// Load a key entry by the given key descriptor.
2601 /// It uses the `check_permission` callback to verify if the access is allowed
2602 /// given the key access tuple read from the database using `load_access_tuple`.
2603 /// With `load_bits` the caller may specify which blobs shall be loaded from
2604 /// the blob database.
2605 pub fn load_key_entry(
2606 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002607 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002608 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002609 load_bits: KeyEntryLoadBits,
2610 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002611 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2612 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002613 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2614
Janis Danisevskis66784c42021-01-27 08:40:25 -08002615 loop {
2616 match self.load_key_entry_internal(
2617 key,
2618 key_type,
2619 load_bits,
2620 caller_uid,
2621 &check_permission,
2622 ) {
2623 Ok(result) => break Ok(result),
2624 Err(e) => {
2625 if Self::is_locked_error(&e) {
2626 std::thread::sleep(std::time::Duration::from_micros(500));
2627 continue;
2628 } else {
2629 return Err(e).context("In load_key_entry.");
2630 }
2631 }
2632 }
2633 }
2634 }
2635
2636 fn load_key_entry_internal(
2637 &mut self,
2638 key: &KeyDescriptor,
2639 key_type: KeyType,
2640 load_bits: KeyEntryLoadBits,
2641 caller_uid: u32,
2642 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002643 ) -> Result<(KeyIdGuard, KeyEntry)> {
2644 // KEY ID LOCK 1/2
2645 // If we got a key descriptor with a key id we can get the lock right away.
2646 // Otherwise we have to defer it until we know the key id.
2647 let key_id_guard = match key.domain {
2648 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2649 _ => None,
2650 };
2651
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002652 let tx = self
2653 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002654 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002655 .context("In load_key_entry: Failed to initialize transaction.")?;
2656
2657 // Load the key_id and complete the access control tuple.
2658 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002659 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2660 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002661
2662 // Perform access control. It is vital that we return here if the permission is denied.
2663 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002664 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002665
Janis Danisevskisaec14592020-11-12 09:41:49 -08002666 // KEY ID LOCK 2/2
2667 // If we did not get a key id lock by now, it was because we got a key descriptor
2668 // without a key id. At this point we got the key id, so we can try and get a lock.
2669 // However, we cannot block here, because we are in the middle of the transaction.
2670 // So first we try to get the lock non blocking. If that fails, we roll back the
2671 // transaction and block until we get the lock. After we successfully got the lock,
2672 // we start a new transaction and load the access tuple again.
2673 //
2674 // We don't need to perform access control again, because we already established
2675 // that the caller had access to the given key. But we need to make sure that the
2676 // key id still exists. So we have to load the key entry by key id this time.
2677 let (key_id_guard, tx) = match key_id_guard {
2678 None => match KEY_ID_LOCK.try_get(key_id) {
2679 None => {
2680 // Roll back the transaction.
2681 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002682
Janis Danisevskisaec14592020-11-12 09:41:49 -08002683 // Block until we have a key id lock.
2684 let key_id_guard = KEY_ID_LOCK.get(key_id);
2685
2686 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002687 let tx = self
2688 .conn
2689 .unchecked_transaction()
2690 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002691
2692 Self::load_access_tuple(
2693 &tx,
2694 // This time we have to load the key by the retrieved key id, because the
2695 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002696 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002697 domain: Domain::KEY_ID,
2698 nspace: key_id,
2699 ..Default::default()
2700 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002701 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002702 caller_uid,
2703 )
2704 .context("In load_key_entry. (deferred key lock)")?;
2705 (key_id_guard, tx)
2706 }
2707 Some(l) => (l, tx),
2708 },
2709 Some(key_id_guard) => (key_id_guard, tx),
2710 };
2711
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002712 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2713 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002714
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002715 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2716
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002717 Ok((key_id_guard, key_entry))
2718 }
2719
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002720 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002721 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002722 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2723 .context("Trying to delete keyentry.")?;
2724 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2725 .context("Trying to delete keymetadata.")?;
2726 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2727 .context("Trying to delete keyparameters.")?;
2728 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2729 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002730 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002731 }
2732
2733 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002734 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002735 pub fn unbind_key(
2736 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002737 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002738 key_type: KeyType,
2739 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002740 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002741 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002742 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2743
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002744 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2745 let (key_id, access_key_descriptor, access_vector) =
2746 Self::load_access_tuple(tx, key, key_type, caller_uid)
2747 .context("Trying to get access tuple.")?;
2748
2749 // Perform access control. It is vital that we return here if the permission is denied.
2750 // So do not touch that '?' at the end.
2751 check_permission(&access_key_descriptor, access_vector)
2752 .context("While checking permission.")?;
2753
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002754 Self::mark_unreferenced(tx, key_id)
2755 .map(|need_gc| (need_gc, ()))
2756 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002757 })
2758 .context("In unbind_key.")
2759 }
2760
Max Bires8e93d2b2021-01-14 13:17:59 -08002761 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2762 tx.query_row(
2763 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2764 params![key_id],
2765 |row| row.get(0),
2766 )
2767 .context("In get_key_km_uuid.")
2768 }
2769
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002770 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2771 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2772 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002773 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2774
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002775 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2776 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2777 .context("In unbind_keys_for_namespace.");
2778 }
2779 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2780 tx.execute(
2781 "DELETE FROM persistent.keymetadata
2782 WHERE keyentryid IN (
2783 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002784 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002785 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002786 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002787 )
2788 .context("Trying to delete keymetadata.")?;
2789 tx.execute(
2790 "DELETE FROM persistent.keyparameter
2791 WHERE keyentryid IN (
2792 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002793 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002794 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002795 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002796 )
2797 .context("Trying to delete keyparameters.")?;
2798 tx.execute(
2799 "DELETE FROM persistent.grant
2800 WHERE keyentryid IN (
2801 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002802 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002803 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002804 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002805 )
2806 .context("Trying to delete grants.")?;
2807 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002808 "DELETE FROM persistent.keyentry
2809 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2810 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002811 )
2812 .context("Trying to delete keyentry.")?;
2813 Ok(()).need_gc()
2814 })
2815 .context("In unbind_keys_for_namespace")
2816 }
2817
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002818 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2819 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2820 {
2821 tx.execute(
2822 "DELETE FROM persistent.keymetadata
2823 WHERE keyentryid IN (
2824 SELECT id FROM persistent.keyentry
2825 WHERE state = ?
2826 );",
2827 params![KeyLifeCycle::Unreferenced],
2828 )
2829 .context("Trying to delete keymetadata.")?;
2830 tx.execute(
2831 "DELETE FROM persistent.keyparameter
2832 WHERE keyentryid IN (
2833 SELECT id FROM persistent.keyentry
2834 WHERE state = ?
2835 );",
2836 params![KeyLifeCycle::Unreferenced],
2837 )
2838 .context("Trying to delete keyparameters.")?;
2839 tx.execute(
2840 "DELETE FROM persistent.grant
2841 WHERE keyentryid IN (
2842 SELECT id FROM persistent.keyentry
2843 WHERE state = ?
2844 );",
2845 params![KeyLifeCycle::Unreferenced],
2846 )
2847 .context("Trying to delete grants.")?;
2848 tx.execute(
2849 "DELETE FROM persistent.keyentry
2850 WHERE state = ?;",
2851 params![KeyLifeCycle::Unreferenced],
2852 )
2853 .context("Trying to delete keyentry.")?;
2854 Result::<()>::Ok(())
2855 }
2856 .context("In cleanup_unreferenced")
2857 }
2858
Hasini Gunasingheda895552021-01-27 19:34:37 +00002859 /// Delete the keys created on behalf of the user, denoted by the user id.
2860 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2861 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2862 /// The caller of this function should notify the gc if the returned value is true.
2863 pub fn unbind_keys_for_user(
2864 &mut self,
2865 user_id: u32,
2866 keep_non_super_encrypted_keys: bool,
2867 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002868 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2869
Hasini Gunasingheda895552021-01-27 19:34:37 +00002870 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2871 let mut stmt = tx
2872 .prepare(&format!(
2873 "SELECT id from persistent.keyentry
2874 WHERE (
2875 key_type = ?
2876 AND domain = ?
2877 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2878 AND state = ?
2879 ) OR (
2880 key_type = ?
2881 AND namespace = ?
2882 AND alias = ?
2883 AND state = ?
2884 );",
2885 aid_user_offset = AID_USER_OFFSET
2886 ))
2887 .context(concat!(
2888 "In unbind_keys_for_user. ",
2889 "Failed to prepare the query to find the keys created by apps."
2890 ))?;
2891
2892 let mut rows = stmt
2893 .query(params![
2894 // WHERE client key:
2895 KeyType::Client,
2896 Domain::APP.0 as u32,
2897 user_id,
2898 KeyLifeCycle::Live,
2899 // OR super key:
2900 KeyType::Super,
2901 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002902 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002903 KeyLifeCycle::Live
2904 ])
2905 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2906
2907 let mut key_ids: Vec<i64> = Vec::new();
2908 db_utils::with_rows_extract_all(&mut rows, |row| {
2909 key_ids
2910 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2911 Ok(())
2912 })
2913 .context("In unbind_keys_for_user.")?;
2914
2915 let mut notify_gc = false;
2916 for key_id in key_ids {
2917 if keep_non_super_encrypted_keys {
2918 // Load metadata and filter out non-super-encrypted keys.
2919 if let (_, Some((_, blob_metadata)), _, _) =
2920 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2921 .context("In unbind_keys_for_user: Trying to load blob info.")?
2922 {
2923 if blob_metadata.encrypted_by().is_none() {
2924 continue;
2925 }
2926 }
2927 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002928 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002929 .context("In unbind_keys_for_user.")?
2930 || notify_gc;
2931 }
2932 Ok(()).do_gc(notify_gc)
2933 })
2934 .context("In unbind_keys_for_user.")
2935 }
2936
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002937 fn load_key_components(
2938 tx: &Transaction,
2939 load_bits: KeyEntryLoadBits,
2940 key_id: i64,
2941 ) -> Result<KeyEntry> {
2942 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2943
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002944 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002945 Self::load_blob_components(key_id, load_bits, &tx)
2946 .context("In load_key_components.")?;
2947
Max Bires8e93d2b2021-01-14 13:17:59 -08002948 let parameters = Self::load_key_parameters(key_id, &tx)
2949 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002950
Max Bires8e93d2b2021-01-14 13:17:59 -08002951 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2952 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002953
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002954 Ok(KeyEntry {
2955 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002956 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002957 cert: cert_blob,
2958 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002959 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002960 parameters,
2961 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002962 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002963 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002964 }
2965
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002966 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2967 /// The key descriptors will have the domain, nspace, and alias field set.
2968 /// Domain must be APP or SELINUX, the caller must make sure of that.
2969 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002970 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2971
Janis Danisevskis66784c42021-01-27 08:40:25 -08002972 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2973 let mut stmt = tx
2974 .prepare(
2975 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002976 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002977 )
2978 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002979
Janis Danisevskis66784c42021-01-27 08:40:25 -08002980 let mut rows = stmt
2981 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2982 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002983
Janis Danisevskis66784c42021-01-27 08:40:25 -08002984 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2985 db_utils::with_rows_extract_all(&mut rows, |row| {
2986 descriptors.push(KeyDescriptor {
2987 domain,
2988 nspace: namespace,
2989 alias: Some(row.get(0).context("Trying to extract alias.")?),
2990 blob: None,
2991 });
2992 Ok(())
2993 })
2994 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002995 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002996 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002997 }
2998
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002999 /// Adds a grant to the grant table.
3000 /// Like `load_key_entry` this function loads the access tuple before
3001 /// it uses the callback for a permission check. Upon success,
3002 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3003 /// grant table. The new row will have a randomized id, which is used as
3004 /// grant id in the namespace field of the resulting KeyDescriptor.
3005 pub fn grant(
3006 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003007 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003008 caller_uid: u32,
3009 grantee_uid: u32,
3010 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003011 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003012 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003013 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3014
Janis Danisevskis66784c42021-01-27 08:40:25 -08003015 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3016 // Load the key_id and complete the access control tuple.
3017 // We ignore the access vector here because grants cannot be granted.
3018 // The access vector returned here expresses the permissions the
3019 // grantee has if key.domain == Domain::GRANT. But this vector
3020 // cannot include the grant permission by design, so there is no way the
3021 // subsequent permission check can pass.
3022 // We could check key.domain == Domain::GRANT and fail early.
3023 // But even if we load the access tuple by grant here, the permission
3024 // check denies the attempt to create a grant by grant descriptor.
3025 let (key_id, access_key_descriptor, _) =
3026 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3027 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003028
Janis Danisevskis66784c42021-01-27 08:40:25 -08003029 // Perform access control. It is vital that we return here if the permission
3030 // was denied. So do not touch that '?' at the end of the line.
3031 // This permission check checks if the caller has the grant permission
3032 // for the given key and in addition to all of the permissions
3033 // expressed in `access_vector`.
3034 check_permission(&access_key_descriptor, &access_vector)
3035 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003036
Janis Danisevskis66784c42021-01-27 08:40:25 -08003037 let grant_id = if let Some(grant_id) = tx
3038 .query_row(
3039 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003040 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003041 params![key_id, grantee_uid],
3042 |row| row.get(0),
3043 )
3044 .optional()
3045 .context("In grant: Failed get optional existing grant id.")?
3046 {
3047 tx.execute(
3048 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003049 SET access_vector = ?
3050 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003051 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003052 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003053 .context("In grant: Failed to update existing grant.")?;
3054 grant_id
3055 } else {
3056 Self::insert_with_retry(|id| {
3057 tx.execute(
3058 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3059 VALUES (?, ?, ?, ?);",
3060 params![id, grantee_uid, key_id, i32::from(access_vector)],
3061 )
3062 })
3063 .context("In grant")?
3064 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003065
Janis Danisevskis66784c42021-01-27 08:40:25 -08003066 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003067 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003068 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003069 }
3070
3071 /// This function checks permissions like `grant` and `load_key_entry`
3072 /// before removing a grant from the grant table.
3073 pub fn ungrant(
3074 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003075 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003076 caller_uid: u32,
3077 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003079 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003080 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3081
Janis Danisevskis66784c42021-01-27 08:40:25 -08003082 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3083 // Load the key_id and complete the access control tuple.
3084 // We ignore the access vector here because grants cannot be granted.
3085 let (key_id, access_key_descriptor, _) =
3086 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3087 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003088
Janis Danisevskis66784c42021-01-27 08:40:25 -08003089 // Perform access control. We must return here if the permission
3090 // was denied. So do not touch the '?' at the end of this line.
3091 check_permission(&access_key_descriptor)
3092 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003093
Janis Danisevskis66784c42021-01-27 08:40:25 -08003094 tx.execute(
3095 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003096 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003097 params![key_id, grantee_uid],
3098 )
3099 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003100
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003101 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003102 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003103 }
3104
Joel Galenson845f74b2020-09-09 14:11:55 -07003105 // Generates a random id and passes it to the given function, which will
3106 // try to insert it into a database. If that insertion fails, retry;
3107 // otherwise return the id.
3108 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3109 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003110 let newid: i64 = match random() {
3111 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3112 i => i,
3113 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003114 match inserter(newid) {
3115 // If the id already existed, try again.
3116 Err(rusqlite::Error::SqliteFailure(
3117 libsqlite3_sys::Error {
3118 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3119 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3120 },
3121 _,
3122 )) => (),
3123 Err(e) => {
3124 return Err(e).context("In insert_with_retry: failed to insert into database.")
3125 }
3126 _ => return Ok(newid),
3127 }
3128 }
3129 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003130
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003131 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3132 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3133 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3134 auth_token.clone(),
3135 MonotonicRawTime::now(),
3136 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003137 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003138
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003139 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003140 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003141 where
3142 F: Fn(&AuthTokenEntry) -> bool,
3143 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003144 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003145 }
3146
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003147 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003148 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3149 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003150 }
3151
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003152 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003153 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3154 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003155 }
3156
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003157 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003158 fn get_last_off_body(&self) -> MonotonicRawTime {
3159 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003160 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003161}
3162
3163#[cfg(test)]
3164mod tests {
3165
3166 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003167 use crate::key_parameter::{
3168 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3169 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3170 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003171 use crate::key_perm_set;
3172 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003173 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003174 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003175 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3176 HardwareAuthToken::HardwareAuthToken,
3177 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003178 };
3179 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003180 Timestamp::Timestamp,
3181 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003182 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003183 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003184 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003185 use std::collections::BTreeMap;
3186 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003187 use std::sync::atomic::{AtomicU8, Ordering};
3188 use std::sync::Arc;
3189 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003190 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003191 #[cfg(disabled)]
3192 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003193
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003194 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003195 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003196
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003197 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003198 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003199 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003200 })?;
3201 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003202 }
3203
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003204 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3205 where
3206 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3207 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003208 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003209
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003210 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003211 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003212
Janis Danisevskis3395f862021-05-06 10:54:17 -07003213 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003214 }
3215
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003216 fn rebind_alias(
3217 db: &mut KeystoreDB,
3218 newid: &KeyIdGuard,
3219 alias: &str,
3220 domain: Domain,
3221 namespace: i64,
3222 ) -> Result<bool> {
3223 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003224 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003225 })
3226 .context("In rebind_alias.")
3227 }
3228
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003229 #[test]
3230 fn datetime() -> Result<()> {
3231 let conn = Connection::open_in_memory()?;
3232 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3233 let now = SystemTime::now();
3234 let duration = Duration::from_secs(1000);
3235 let then = now.checked_sub(duration).unwrap();
3236 let soon = now.checked_add(duration).unwrap();
3237 conn.execute(
3238 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3239 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3240 )?;
3241 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3242 let mut rows = stmt.query(NO_PARAMS)?;
3243 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3244 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3245 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3246 assert!(rows.next()?.is_none());
3247 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3248 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3249 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3250 Ok(())
3251 }
3252
Joel Galenson0891bc12020-07-20 10:37:03 -07003253 // Ensure that we're using the "injected" random function, not the real one.
3254 #[test]
3255 fn test_mocked_random() {
3256 let rand1 = random();
3257 let rand2 = random();
3258 let rand3 = random();
3259 if rand1 == rand2 {
3260 assert_eq!(rand2 + 1, rand3);
3261 } else {
3262 assert_eq!(rand1 + 1, rand2);
3263 assert_eq!(rand2, rand3);
3264 }
3265 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003266
Joel Galenson26f4d012020-07-17 14:57:21 -07003267 // Test that we have the correct tables.
3268 #[test]
3269 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003270 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003271 let tables = db
3272 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003273 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003274 .query_map(params![], |row| row.get(0))?
3275 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003276 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003277 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003278 assert_eq!(tables[1], "blobmetadata");
3279 assert_eq!(tables[2], "grant");
3280 assert_eq!(tables[3], "keyentry");
3281 assert_eq!(tables[4], "keymetadata");
3282 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003283 Ok(())
3284 }
3285
3286 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003287 fn test_auth_token_table_invariant() -> Result<()> {
3288 let mut db = new_test_db()?;
3289 let auth_token1 = 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: 500 },
3295 mac: String::from("mac").into_bytes(),
3296 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003297 db.insert_auth_token(&auth_token1);
3298 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003299 assert_eq!(auth_tokens_returned.len(), 1);
3300
3301 // insert another auth token with the same values for the columns in the UNIQUE constraint
3302 // of the auth token table and different value for timestamp
3303 let auth_token2 = HardwareAuthToken {
3304 challenge: i64::MAX,
3305 userId: 200,
3306 authenticatorId: 200,
3307 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3308 timestamp: Timestamp { milliSeconds: 600 },
3309 mac: String::from("mac").into_bytes(),
3310 };
3311
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003312 db.insert_auth_token(&auth_token2);
3313 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003314 assert_eq!(auth_tokens_returned.len(), 1);
3315
3316 if let Some(auth_token) = auth_tokens_returned.pop() {
3317 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3318 }
3319
3320 // insert another auth token with the different values for the columns in the UNIQUE
3321 // constraint of the auth token table
3322 let auth_token3 = HardwareAuthToken {
3323 challenge: i64::MAX,
3324 userId: 201,
3325 authenticatorId: 200,
3326 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3327 timestamp: Timestamp { milliSeconds: 600 },
3328 mac: String::from("mac").into_bytes(),
3329 };
3330
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003331 db.insert_auth_token(&auth_token3);
3332 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003333 assert_eq!(auth_tokens_returned.len(), 2);
3334
3335 Ok(())
3336 }
3337
3338 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003339 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3340 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003341 }
3342
3343 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003344 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003345 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003346 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003347
Janis Danisevskis66784c42021-01-27 08:40:25 -08003348 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003349 let entries = get_keyentry(&db)?;
3350 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003351
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003352 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003353
3354 let entries_new = get_keyentry(&db)?;
3355 assert_eq!(entries, entries_new);
3356 Ok(())
3357 }
3358
3359 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003360 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003361 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3362 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003363 }
3364
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003365 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003366
Janis Danisevskis66784c42021-01-27 08:40:25 -08003367 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3368 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003369
3370 let entries = get_keyentry(&db)?;
3371 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003372 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3373 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003374
3375 // Test that we must pass in a valid Domain.
3376 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003377 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003378 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003379 );
3380 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003381 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003382 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003383 );
3384 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003385 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003386 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003387 );
3388
3389 Ok(())
3390 }
3391
Joel Galenson33c04ad2020-08-03 11:04:38 -07003392 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003393 fn test_add_unsigned_key() -> Result<()> {
3394 let mut db = new_test_db()?;
3395 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3396 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3397 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3398 db.create_attestation_key_entry(
3399 &public_key,
3400 &raw_public_key,
3401 &private_key,
3402 &KEYSTORE_UUID,
3403 )?;
3404 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3405 assert_eq!(keys.len(), 1);
3406 assert_eq!(keys[0], public_key);
3407 Ok(())
3408 }
3409
3410 #[test]
3411 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3412 let mut db = new_test_db()?;
3413 let expiration_date: i64 = 20;
3414 let namespace: i64 = 30;
3415 let base_byte: u8 = 1;
3416 let loaded_values =
3417 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3418 let chain =
3419 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3420 assert_eq!(true, chain.is_some());
3421 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003422 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003423 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3424 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003425 Ok(())
3426 }
3427
3428 #[test]
3429 fn test_get_attestation_pool_status() -> Result<()> {
3430 let mut db = new_test_db()?;
3431 let namespace: i64 = 30;
3432 load_attestation_key_pool(
3433 &mut db, 10, /* expiration */
3434 namespace, 0x01, /* base_byte */
3435 )?;
3436 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3437 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3438 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3439 assert_eq!(status.expiring, 0);
3440 assert_eq!(status.attested, 3);
3441 assert_eq!(status.unassigned, 0);
3442 assert_eq!(status.total, 3);
3443 assert_eq!(
3444 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3445 1
3446 );
3447 assert_eq!(
3448 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3449 2
3450 );
3451 assert_eq!(
3452 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3453 3
3454 );
3455 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3456 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3457 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3458 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003459 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003460 db.create_attestation_key_entry(
3461 &public_key,
3462 &raw_public_key,
3463 &private_key,
3464 &KEYSTORE_UUID,
3465 )?;
3466 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3467 assert_eq!(status.attested, 3);
3468 assert_eq!(status.unassigned, 0);
3469 assert_eq!(status.total, 4);
3470 db.store_signed_attestation_certificate_chain(
3471 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003472 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003473 &cert_chain,
3474 20,
3475 &KEYSTORE_UUID,
3476 )?;
3477 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3478 assert_eq!(status.attested, 4);
3479 assert_eq!(status.unassigned, 1);
3480 assert_eq!(status.total, 4);
3481 Ok(())
3482 }
3483
3484 #[test]
3485 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003486 let temp_dir =
3487 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3488 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003489 let expiration_date: i64 =
3490 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3491 let namespace: i64 = 30;
3492 let namespace_del1: i64 = 45;
3493 let namespace_del2: i64 = 60;
3494 let entry_values = load_attestation_key_pool(
3495 &mut db,
3496 expiration_date,
3497 namespace,
3498 0x01, /* base_byte */
3499 )?;
3500 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3501 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003502
3503 let blob_entry_row_count: u32 = db
3504 .conn
3505 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3506 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003507 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3508 // one key, one certificate chain, and one certificate.
3509 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003510
Max Bires2b2e6562020-09-22 11:22:36 -07003511 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3512
3513 let mut cert_chain =
3514 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003515 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003516 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003517 assert_eq!(entry_values.batch_cert, value.batch_cert);
3518 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003519 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003520
3521 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3522 Domain::APP,
3523 namespace_del1,
3524 &KEYSTORE_UUID,
3525 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003526 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003527 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3528 Domain::APP,
3529 namespace_del2,
3530 &KEYSTORE_UUID,
3531 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003532 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003533
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003534 // Give the garbage collector half a second to catch up.
3535 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003536
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003537 let blob_entry_row_count: u32 = db
3538 .conn
3539 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3540 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003541 // There shound be 3 blob entries left, because we deleted two of the attestation
3542 // key entries with three blobs each.
3543 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003544
Max Bires2b2e6562020-09-22 11:22:36 -07003545 Ok(())
3546 }
3547
3548 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003549 fn test_delete_all_attestation_keys() -> Result<()> {
3550 let mut db = new_test_db()?;
3551 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3552 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3553 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3554 let result = db.delete_all_attestation_keys()?;
3555
3556 // Give the garbage collector half a second to catch up.
3557 std::thread::sleep(Duration::from_millis(500));
3558
3559 // Attestation keys should be deleted, and the regular key should remain.
3560 assert_eq!(result, 2);
3561
3562 Ok(())
3563 }
3564
3565 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003566 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003567 fn extractor(
3568 ke: &KeyEntryRow,
3569 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3570 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003571 }
3572
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003573 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003574 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3575 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003576 let entries = get_keyentry(&db)?;
3577 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003578 assert_eq!(
3579 extractor(&entries[0]),
3580 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3581 );
3582 assert_eq!(
3583 extractor(&entries[1]),
3584 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3585 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003586
3587 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003588 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003589 let entries = get_keyentry(&db)?;
3590 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003591 assert_eq!(
3592 extractor(&entries[0]),
3593 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3594 );
3595 assert_eq!(
3596 extractor(&entries[1]),
3597 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3598 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003599
3600 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003601 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003602 let entries = get_keyentry(&db)?;
3603 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003604 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3605 assert_eq!(
3606 extractor(&entries[1]),
3607 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3608 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003609
3610 // Test that we must pass in a valid Domain.
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::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003613 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003614 );
3615 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003616 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003617 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003618 );
3619 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003620 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003621 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003622 );
3623
3624 // Test that we correctly handle setting an alias for something that does not exist.
3625 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003626 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003627 "Expected to update a single entry but instead updated 0",
3628 );
3629 // Test that we correctly abort the transaction in this case.
3630 let entries = get_keyentry(&db)?;
3631 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003632 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3633 assert_eq!(
3634 extractor(&entries[1]),
3635 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3636 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003637
3638 Ok(())
3639 }
3640
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003641 #[test]
3642 fn test_grant_ungrant() -> Result<()> {
3643 const CALLER_UID: u32 = 15;
3644 const GRANTEE_UID: u32 = 12;
3645 const SELINUX_NAMESPACE: i64 = 7;
3646
3647 let mut db = new_test_db()?;
3648 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003649 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3650 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3651 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003652 )?;
3653 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003654 domain: super::Domain::APP,
3655 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003656 alias: Some("key".to_string()),
3657 blob: None,
3658 };
3659 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3660 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3661
3662 // Reset totally predictable random number generator in case we
3663 // are not the first test running on this thread.
3664 reset_random();
3665 let next_random = 0i64;
3666
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003667 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003668 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003669 assert_eq!(*a, PVEC1);
3670 assert_eq!(
3671 *k,
3672 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003673 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003674 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003675 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003676 alias: Some("key".to_string()),
3677 blob: None,
3678 }
3679 );
3680 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003681 })
3682 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003683
3684 assert_eq!(
3685 app_granted_key,
3686 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003687 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003688 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003689 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003690 alias: None,
3691 blob: None,
3692 }
3693 );
3694
3695 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003696 domain: super::Domain::SELINUX,
3697 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003698 alias: Some("yek".to_string()),
3699 blob: None,
3700 };
3701
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003702 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003703 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003704 assert_eq!(*a, PVEC1);
3705 assert_eq!(
3706 *k,
3707 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003708 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003709 // namespace must be the supplied SELinux
3710 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003711 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003712 alias: Some("yek".to_string()),
3713 blob: None,
3714 }
3715 );
3716 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003717 })
3718 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003719
3720 assert_eq!(
3721 selinux_granted_key,
3722 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003723 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003724 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003725 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003726 alias: None,
3727 blob: None,
3728 }
3729 );
3730
3731 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003732 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003733 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003734 assert_eq!(*a, PVEC2);
3735 assert_eq!(
3736 *k,
3737 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003738 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003739 // namespace must be the supplied SELinux
3740 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003741 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003742 alias: Some("yek".to_string()),
3743 blob: None,
3744 }
3745 );
3746 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003747 })
3748 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003749
3750 assert_eq!(
3751 selinux_granted_key,
3752 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003753 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003755 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003756 alias: None,
3757 blob: None,
3758 }
3759 );
3760
3761 {
3762 // Limiting scope of stmt, because it borrows db.
3763 let mut stmt = db
3764 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003765 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003766 let mut rows =
3767 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3768 Ok((
3769 row.get(0)?,
3770 row.get(1)?,
3771 row.get(2)?,
3772 KeyPermSet::from(row.get::<_, i32>(3)?),
3773 ))
3774 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775
3776 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003777 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003778 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003779 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003780 assert!(rows.next().is_none());
3781 }
3782
3783 debug_dump_keyentry_table(&mut db)?;
3784 println!("app_key {:?}", app_key);
3785 println!("selinux_key {:?}", selinux_key);
3786
Janis Danisevskis66784c42021-01-27 08:40:25 -08003787 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3788 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003789
3790 Ok(())
3791 }
3792
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003793 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003794 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3795 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3796
3797 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003798 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003799 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003800 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003801 let mut blob_metadata = BlobMetaData::new();
3802 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3803 db.set_blob(
3804 &key_id,
3805 SubComponentType::KEY_BLOB,
3806 Some(TEST_KEY_BLOB),
3807 Some(&blob_metadata),
3808 )?;
3809 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3810 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003811 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003812
3813 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003814 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003815 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003816 )?;
3817 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003818 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3819 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003820 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003821 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003822 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003823 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003824 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003825 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003826 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003827
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003828 drop(rows);
3829 drop(stmt);
3830
3831 assert_eq!(
3832 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3833 BlobMetaData::load_from_db(id, tx).no_gc()
3834 })
3835 .expect("Should find blob metadata."),
3836 blob_metadata
3837 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003838 Ok(())
3839 }
3840
3841 static TEST_ALIAS: &str = "my super duper key";
3842
3843 #[test]
3844 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3845 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003846 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003847 .context("test_insert_and_load_full_keyentry_domain_app")?
3848 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003849 let (_key_guard, key_entry) = db
3850 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003851 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003852 domain: Domain::APP,
3853 nspace: 0,
3854 alias: Some(TEST_ALIAS.to_string()),
3855 blob: None,
3856 },
3857 KeyType::Client,
3858 KeyEntryLoadBits::BOTH,
3859 1,
3860 |_k, _av| Ok(()),
3861 )
3862 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003863 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003864
3865 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003866 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003867 domain: Domain::APP,
3868 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003869 alias: Some(TEST_ALIAS.to_string()),
3870 blob: None,
3871 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003872 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003873 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003874 |_, _| Ok(()),
3875 )
3876 .unwrap();
3877
3878 assert_eq!(
3879 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3880 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003881 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003882 domain: Domain::APP,
3883 nspace: 0,
3884 alias: Some(TEST_ALIAS.to_string()),
3885 blob: None,
3886 },
3887 KeyType::Client,
3888 KeyEntryLoadBits::NONE,
3889 1,
3890 |_k, _av| Ok(()),
3891 )
3892 .unwrap_err()
3893 .root_cause()
3894 .downcast_ref::<KsError>()
3895 );
3896
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003897 Ok(())
3898 }
3899
3900 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003901 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3902 let mut db = new_test_db()?;
3903
3904 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003905 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003906 domain: Domain::APP,
3907 nspace: 1,
3908 alias: Some(TEST_ALIAS.to_string()),
3909 blob: None,
3910 },
3911 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003912 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003913 )
3914 .expect("Trying to insert cert.");
3915
3916 let (_key_guard, mut key_entry) = db
3917 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003918 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003919 domain: Domain::APP,
3920 nspace: 1,
3921 alias: Some(TEST_ALIAS.to_string()),
3922 blob: None,
3923 },
3924 KeyType::Client,
3925 KeyEntryLoadBits::PUBLIC,
3926 1,
3927 |_k, _av| Ok(()),
3928 )
3929 .expect("Trying to read certificate entry.");
3930
3931 assert!(key_entry.pure_cert());
3932 assert!(key_entry.cert().is_none());
3933 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3934
3935 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003936 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003937 domain: Domain::APP,
3938 nspace: 1,
3939 alias: Some(TEST_ALIAS.to_string()),
3940 blob: None,
3941 },
3942 KeyType::Client,
3943 1,
3944 |_, _| Ok(()),
3945 )
3946 .unwrap();
3947
3948 assert_eq!(
3949 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3950 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003951 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003952 domain: Domain::APP,
3953 nspace: 1,
3954 alias: Some(TEST_ALIAS.to_string()),
3955 blob: None,
3956 },
3957 KeyType::Client,
3958 KeyEntryLoadBits::NONE,
3959 1,
3960 |_k, _av| Ok(()),
3961 )
3962 .unwrap_err()
3963 .root_cause()
3964 .downcast_ref::<KsError>()
3965 );
3966
3967 Ok(())
3968 }
3969
3970 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003971 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3972 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003973 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003974 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3975 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003976 let (_key_guard, key_entry) = db
3977 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003978 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003979 domain: Domain::SELINUX,
3980 nspace: 1,
3981 alias: Some(TEST_ALIAS.to_string()),
3982 blob: None,
3983 },
3984 KeyType::Client,
3985 KeyEntryLoadBits::BOTH,
3986 1,
3987 |_k, _av| Ok(()),
3988 )
3989 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003990 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003991
3992 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003993 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003994 domain: Domain::SELINUX,
3995 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003996 alias: Some(TEST_ALIAS.to_string()),
3997 blob: None,
3998 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003999 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004000 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004001 |_, _| Ok(()),
4002 )
4003 .unwrap();
4004
4005 assert_eq!(
4006 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4007 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004008 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004009 domain: Domain::SELINUX,
4010 nspace: 1,
4011 alias: Some(TEST_ALIAS.to_string()),
4012 blob: None,
4013 },
4014 KeyType::Client,
4015 KeyEntryLoadBits::NONE,
4016 1,
4017 |_k, _av| Ok(()),
4018 )
4019 .unwrap_err()
4020 .root_cause()
4021 .downcast_ref::<KsError>()
4022 );
4023
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004024 Ok(())
4025 }
4026
4027 #[test]
4028 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4029 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004030 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004031 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4032 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004033 let (_, key_entry) = db
4034 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004035 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004036 KeyType::Client,
4037 KeyEntryLoadBits::BOTH,
4038 1,
4039 |_k, _av| Ok(()),
4040 )
4041 .unwrap();
4042
Qi Wub9433b52020-12-01 14:52:46 +08004043 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004044
4045 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004046 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004047 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004048 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004049 |_, _| Ok(()),
4050 )
4051 .unwrap();
4052
4053 assert_eq!(
4054 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4055 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004056 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004057 KeyType::Client,
4058 KeyEntryLoadBits::NONE,
4059 1,
4060 |_k, _av| Ok(()),
4061 )
4062 .unwrap_err()
4063 .root_cause()
4064 .downcast_ref::<KsError>()
4065 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004066
4067 Ok(())
4068 }
4069
4070 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004071 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4072 let mut db = new_test_db()?;
4073 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4074 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4075 .0;
4076 // Update the usage count of the limited use key.
4077 db.check_and_update_key_usage_count(key_id)?;
4078
4079 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004080 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004081 KeyType::Client,
4082 KeyEntryLoadBits::BOTH,
4083 1,
4084 |_k, _av| Ok(()),
4085 )?;
4086
4087 // The usage count is decremented now.
4088 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4089
4090 Ok(())
4091 }
4092
4093 #[test]
4094 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4095 let mut db = new_test_db()?;
4096 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4097 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4098 .0;
4099 // Update the usage count of the limited use key.
4100 db.check_and_update_key_usage_count(key_id).expect(concat!(
4101 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4102 "This should succeed."
4103 ));
4104
4105 // Try to update the exhausted limited use key.
4106 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4107 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4108 "This should fail."
4109 ));
4110 assert_eq!(
4111 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4112 e.root_cause().downcast_ref::<KsError>().unwrap()
4113 );
4114
4115 Ok(())
4116 }
4117
4118 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004119 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4120 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004121 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004122 .context("test_insert_and_load_full_keyentry_from_grant")?
4123 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004124
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004125 let granted_key = db
4126 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004127 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004128 domain: Domain::APP,
4129 nspace: 0,
4130 alias: Some(TEST_ALIAS.to_string()),
4131 blob: None,
4132 },
4133 1,
4134 2,
4135 key_perm_set![KeyPerm::use_()],
4136 |_k, _av| Ok(()),
4137 )
4138 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004139
4140 debug_dump_grant_table(&mut db)?;
4141
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004142 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004143 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4144 assert_eq!(Domain::GRANT, k.domain);
4145 assert!(av.unwrap().includes(KeyPerm::use_()));
4146 Ok(())
4147 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004148 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004149
Qi Wub9433b52020-12-01 14:52:46 +08004150 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004151
Janis Danisevskis66784c42021-01-27 08:40:25 -08004152 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004153
4154 assert_eq!(
4155 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4156 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004157 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004158 KeyType::Client,
4159 KeyEntryLoadBits::NONE,
4160 2,
4161 |_k, _av| Ok(()),
4162 )
4163 .unwrap_err()
4164 .root_cause()
4165 .downcast_ref::<KsError>()
4166 );
4167
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004168 Ok(())
4169 }
4170
Janis Danisevskis45760022021-01-19 16:34:10 -08004171 // This test attempts to load a key by key id while the caller is not the owner
4172 // but a grant exists for the given key and the caller.
4173 #[test]
4174 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4175 let mut db = new_test_db()?;
4176 const OWNER_UID: u32 = 1u32;
4177 const GRANTEE_UID: u32 = 2u32;
4178 const SOMEONE_ELSE_UID: u32 = 3u32;
4179 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4180 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4181 .0;
4182
4183 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004184 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004185 domain: Domain::APP,
4186 nspace: 0,
4187 alias: Some(TEST_ALIAS.to_string()),
4188 blob: None,
4189 },
4190 OWNER_UID,
4191 GRANTEE_UID,
4192 key_perm_set![KeyPerm::use_()],
4193 |_k, _av| Ok(()),
4194 )
4195 .unwrap();
4196
4197 debug_dump_grant_table(&mut db)?;
4198
4199 let id_descriptor =
4200 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4201
4202 let (_, key_entry) = db
4203 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004204 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004205 KeyType::Client,
4206 KeyEntryLoadBits::BOTH,
4207 GRANTEE_UID,
4208 |k, av| {
4209 assert_eq!(Domain::APP, k.domain);
4210 assert_eq!(OWNER_UID as i64, k.nspace);
4211 assert!(av.unwrap().includes(KeyPerm::use_()));
4212 Ok(())
4213 },
4214 )
4215 .unwrap();
4216
4217 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4218
4219 let (_, key_entry) = db
4220 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004221 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004222 KeyType::Client,
4223 KeyEntryLoadBits::BOTH,
4224 SOMEONE_ELSE_UID,
4225 |k, av| {
4226 assert_eq!(Domain::APP, k.domain);
4227 assert_eq!(OWNER_UID as i64, k.nspace);
4228 assert!(av.is_none());
4229 Ok(())
4230 },
4231 )
4232 .unwrap();
4233
4234 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4235
Janis Danisevskis66784c42021-01-27 08:40:25 -08004236 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004237
4238 assert_eq!(
4239 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4240 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004241 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004242 KeyType::Client,
4243 KeyEntryLoadBits::NONE,
4244 GRANTEE_UID,
4245 |_k, _av| Ok(()),
4246 )
4247 .unwrap_err()
4248 .root_cause()
4249 .downcast_ref::<KsError>()
4250 );
4251
4252 Ok(())
4253 }
4254
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004255 // Creates a key migrates it to a different location and then tries to access it by the old
4256 // and new location.
4257 #[test]
4258 fn test_migrate_key_app_to_app() -> Result<()> {
4259 let mut db = new_test_db()?;
4260 const SOURCE_UID: u32 = 1u32;
4261 const DESTINATION_UID: u32 = 2u32;
4262 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4263 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4264 let key_id_guard =
4265 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4266 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4267
4268 let source_descriptor: KeyDescriptor = KeyDescriptor {
4269 domain: Domain::APP,
4270 nspace: -1,
4271 alias: Some(SOURCE_ALIAS.to_string()),
4272 blob: None,
4273 };
4274
4275 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4276 domain: Domain::APP,
4277 nspace: -1,
4278 alias: Some(DESTINATION_ALIAS.to_string()),
4279 blob: None,
4280 };
4281
4282 let key_id = key_id_guard.id();
4283
4284 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4285 Ok(())
4286 })
4287 .unwrap();
4288
4289 let (_, key_entry) = db
4290 .load_key_entry(
4291 &destination_descriptor,
4292 KeyType::Client,
4293 KeyEntryLoadBits::BOTH,
4294 DESTINATION_UID,
4295 |k, av| {
4296 assert_eq!(Domain::APP, k.domain);
4297 assert_eq!(DESTINATION_UID as i64, k.nspace);
4298 assert!(av.is_none());
4299 Ok(())
4300 },
4301 )
4302 .unwrap();
4303
4304 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4305
4306 assert_eq!(
4307 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4308 db.load_key_entry(
4309 &source_descriptor,
4310 KeyType::Client,
4311 KeyEntryLoadBits::NONE,
4312 SOURCE_UID,
4313 |_k, _av| Ok(()),
4314 )
4315 .unwrap_err()
4316 .root_cause()
4317 .downcast_ref::<KsError>()
4318 );
4319
4320 Ok(())
4321 }
4322
4323 // Creates a key migrates it to a different location and then tries to access it by the old
4324 // and new location.
4325 #[test]
4326 fn test_migrate_key_app_to_selinux() -> Result<()> {
4327 let mut db = new_test_db()?;
4328 const SOURCE_UID: u32 = 1u32;
4329 const DESTINATION_UID: u32 = 2u32;
4330 const DESTINATION_NAMESPACE: i64 = 1000i64;
4331 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4332 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4333 let key_id_guard =
4334 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4335 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4336
4337 let source_descriptor: KeyDescriptor = KeyDescriptor {
4338 domain: Domain::APP,
4339 nspace: -1,
4340 alias: Some(SOURCE_ALIAS.to_string()),
4341 blob: None,
4342 };
4343
4344 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4345 domain: Domain::SELINUX,
4346 nspace: DESTINATION_NAMESPACE,
4347 alias: Some(DESTINATION_ALIAS.to_string()),
4348 blob: None,
4349 };
4350
4351 let key_id = key_id_guard.id();
4352
4353 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4354 Ok(())
4355 })
4356 .unwrap();
4357
4358 let (_, key_entry) = db
4359 .load_key_entry(
4360 &destination_descriptor,
4361 KeyType::Client,
4362 KeyEntryLoadBits::BOTH,
4363 DESTINATION_UID,
4364 |k, av| {
4365 assert_eq!(Domain::SELINUX, k.domain);
4366 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4367 assert!(av.is_none());
4368 Ok(())
4369 },
4370 )
4371 .unwrap();
4372
4373 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4374
4375 assert_eq!(
4376 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4377 db.load_key_entry(
4378 &source_descriptor,
4379 KeyType::Client,
4380 KeyEntryLoadBits::NONE,
4381 SOURCE_UID,
4382 |_k, _av| Ok(()),
4383 )
4384 .unwrap_err()
4385 .root_cause()
4386 .downcast_ref::<KsError>()
4387 );
4388
4389 Ok(())
4390 }
4391
4392 // Creates two keys and tries to migrate the first to the location of the second which
4393 // is expected to fail.
4394 #[test]
4395 fn test_migrate_key_destination_occupied() -> Result<()> {
4396 let mut db = new_test_db()?;
4397 const SOURCE_UID: u32 = 1u32;
4398 const DESTINATION_UID: u32 = 2u32;
4399 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4400 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4401 let key_id_guard =
4402 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4403 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4404 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4405 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4406
4407 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4408 domain: Domain::APP,
4409 nspace: -1,
4410 alias: Some(DESTINATION_ALIAS.to_string()),
4411 blob: None,
4412 };
4413
4414 assert_eq!(
4415 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4416 db.migrate_key_namespace(
4417 key_id_guard,
4418 &destination_descriptor,
4419 DESTINATION_UID,
4420 |_k| Ok(())
4421 )
4422 .unwrap_err()
4423 .root_cause()
4424 .downcast_ref::<KsError>()
4425 );
4426
4427 Ok(())
4428 }
4429
Janis Danisevskisaec14592020-11-12 09:41:49 -08004430 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4431
Janis Danisevskisaec14592020-11-12 09:41:49 -08004432 #[test]
4433 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4434 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004435 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4436 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004437 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004438 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004439 .context("test_insert_and_load_full_keyentry_domain_app")?
4440 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004441 let (_key_guard, key_entry) = db
4442 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004443 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004444 domain: Domain::APP,
4445 nspace: 0,
4446 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4447 blob: None,
4448 },
4449 KeyType::Client,
4450 KeyEntryLoadBits::BOTH,
4451 33,
4452 |_k, _av| Ok(()),
4453 )
4454 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004455 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004456 let state = Arc::new(AtomicU8::new(1));
4457 let state2 = state.clone();
4458
4459 // Spawning a second thread that attempts to acquire the key id lock
4460 // for the same key as the primary thread. The primary thread then
4461 // waits, thereby forcing the secondary thread into the second stage
4462 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4463 // The test succeeds if the secondary thread observes the transition
4464 // of `state` from 1 to 2, despite having a whole second to overtake
4465 // the primary thread.
4466 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004467 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004468 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004469 assert!(db
4470 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004471 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004472 domain: Domain::APP,
4473 nspace: 0,
4474 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4475 blob: None,
4476 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004477 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004478 KeyEntryLoadBits::BOTH,
4479 33,
4480 |_k, _av| Ok(()),
4481 )
4482 .is_ok());
4483 // We should only see a 2 here because we can only return
4484 // from load_key_entry when the `_key_guard` expires,
4485 // which happens at the end of the scope.
4486 assert_eq!(2, state2.load(Ordering::Relaxed));
4487 });
4488
4489 thread::sleep(std::time::Duration::from_millis(1000));
4490
4491 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4492
4493 // Return the handle from this scope so we can join with the
4494 // secondary thread after the key id lock has expired.
4495 handle
4496 // This is where the `_key_guard` goes out of scope,
4497 // which is the reason for concurrent load_key_entry on the same key
4498 // to unblock.
4499 };
4500 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4501 // main test thread. We will not see failing asserts in secondary threads otherwise.
4502 handle.join().unwrap();
4503 Ok(())
4504 }
4505
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004506 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004507 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004508 let temp_dir =
4509 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4510
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004511 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4512 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004513
4514 let _tx1 = db1
4515 .conn
4516 .transaction_with_behavior(TransactionBehavior::Immediate)
4517 .expect("Failed to create first transaction.");
4518
4519 let error = db2
4520 .conn
4521 .transaction_with_behavior(TransactionBehavior::Immediate)
4522 .context("Transaction begin failed.")
4523 .expect_err("This should fail.");
4524 let root_cause = error.root_cause();
4525 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4526 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4527 {
4528 return;
4529 }
4530 panic!(
4531 "Unexpected error {:?} \n{:?} \n{:?}",
4532 error,
4533 root_cause,
4534 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4535 )
4536 }
4537
4538 #[cfg(disabled)]
4539 #[test]
4540 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4541 let temp_dir = Arc::new(
4542 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4543 .expect("Failed to create temp dir."),
4544 );
4545
4546 let test_begin = Instant::now();
4547
4548 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4549 const KEY_COUNT: u32 = 500u32;
4550 const OPEN_DB_COUNT: u32 = 50u32;
4551
4552 let mut actual_key_count = KEY_COUNT;
4553 // First insert KEY_COUNT keys.
4554 for count in 0..KEY_COUNT {
4555 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4556 actual_key_count = count;
4557 break;
4558 }
4559 let alias = format!("test_alias_{}", count);
4560 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4561 .expect("Failed to make key entry.");
4562 }
4563
4564 // Insert more keys from a different thread and into a different namespace.
4565 let temp_dir1 = temp_dir.clone();
4566 let handle1 = thread::spawn(move || {
4567 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4568
4569 for count in 0..actual_key_count {
4570 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4571 return;
4572 }
4573 let alias = format!("test_alias_{}", count);
4574 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4575 .expect("Failed to make key entry.");
4576 }
4577
4578 // then unbind them again.
4579 for count in 0..actual_key_count {
4580 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4581 return;
4582 }
4583 let key = KeyDescriptor {
4584 domain: Domain::APP,
4585 nspace: -1,
4586 alias: Some(format!("test_alias_{}", count)),
4587 blob: None,
4588 };
4589 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4590 }
4591 });
4592
4593 // And start unbinding the first set of keys.
4594 let temp_dir2 = temp_dir.clone();
4595 let handle2 = thread::spawn(move || {
4596 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4597
4598 for count in 0..actual_key_count {
4599 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4600 return;
4601 }
4602 let key = KeyDescriptor {
4603 domain: Domain::APP,
4604 nspace: -1,
4605 alias: Some(format!("test_alias_{}", count)),
4606 blob: None,
4607 };
4608 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4609 }
4610 });
4611
4612 let stop_deleting = Arc::new(AtomicU8::new(0));
4613 let stop_deleting2 = stop_deleting.clone();
4614
4615 // And delete anything that is unreferenced keys.
4616 let temp_dir3 = temp_dir.clone();
4617 let handle3 = thread::spawn(move || {
4618 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4619
4620 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4621 while let Some((key_guard, _key)) =
4622 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4623 {
4624 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4625 return;
4626 }
4627 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4628 }
4629 std::thread::sleep(std::time::Duration::from_millis(100));
4630 }
4631 });
4632
4633 // While a lot of inserting and deleting is going on we have to open database connections
4634 // successfully and use them.
4635 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4636 // out of scope.
4637 #[allow(clippy::redundant_clone)]
4638 let temp_dir4 = temp_dir.clone();
4639 let handle4 = thread::spawn(move || {
4640 for count in 0..OPEN_DB_COUNT {
4641 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4642 return;
4643 }
4644 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4645
4646 let alias = format!("test_alias_{}", count);
4647 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4648 .expect("Failed to make key entry.");
4649 let key = KeyDescriptor {
4650 domain: Domain::APP,
4651 nspace: -1,
4652 alias: Some(alias),
4653 blob: None,
4654 };
4655 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4656 }
4657 });
4658
4659 handle1.join().expect("Thread 1 panicked.");
4660 handle2.join().expect("Thread 2 panicked.");
4661 handle4.join().expect("Thread 4 panicked.");
4662
4663 stop_deleting.store(1, Ordering::Relaxed);
4664 handle3.join().expect("Thread 3 panicked.");
4665
4666 Ok(())
4667 }
4668
4669 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004670 fn list() -> Result<()> {
4671 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004672 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004673 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4674 (Domain::APP, 1, "test1"),
4675 (Domain::APP, 1, "test2"),
4676 (Domain::APP, 1, "test3"),
4677 (Domain::APP, 1, "test4"),
4678 (Domain::APP, 1, "test5"),
4679 (Domain::APP, 1, "test6"),
4680 (Domain::APP, 1, "test7"),
4681 (Domain::APP, 2, "test1"),
4682 (Domain::APP, 2, "test2"),
4683 (Domain::APP, 2, "test3"),
4684 (Domain::APP, 2, "test4"),
4685 (Domain::APP, 2, "test5"),
4686 (Domain::APP, 2, "test6"),
4687 (Domain::APP, 2, "test8"),
4688 (Domain::SELINUX, 100, "test1"),
4689 (Domain::SELINUX, 100, "test2"),
4690 (Domain::SELINUX, 100, "test3"),
4691 (Domain::SELINUX, 100, "test4"),
4692 (Domain::SELINUX, 100, "test5"),
4693 (Domain::SELINUX, 100, "test6"),
4694 (Domain::SELINUX, 100, "test9"),
4695 ];
4696
4697 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4698 .iter()
4699 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004700 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4701 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004702 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4703 });
4704 (entry.id(), *ns)
4705 })
4706 .collect();
4707
4708 for (domain, namespace) in
4709 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4710 {
4711 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4712 .iter()
4713 .filter_map(|(domain, ns, alias)| match ns {
4714 ns if *ns == *namespace => Some(KeyDescriptor {
4715 domain: *domain,
4716 nspace: *ns,
4717 alias: Some(alias.to_string()),
4718 blob: None,
4719 }),
4720 _ => None,
4721 })
4722 .collect();
4723 list_o_descriptors.sort();
4724 let mut list_result = db.list(*domain, *namespace)?;
4725 list_result.sort();
4726 assert_eq!(list_o_descriptors, list_result);
4727
4728 let mut list_o_ids: Vec<i64> = list_o_descriptors
4729 .into_iter()
4730 .map(|d| {
4731 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004732 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004733 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004734 KeyType::Client,
4735 KeyEntryLoadBits::NONE,
4736 *namespace as u32,
4737 |_, _| Ok(()),
4738 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004739 .unwrap();
4740 entry.id()
4741 })
4742 .collect();
4743 list_o_ids.sort_unstable();
4744 let mut loaded_entries: Vec<i64> = list_o_keys
4745 .iter()
4746 .filter_map(|(id, ns)| match ns {
4747 ns if *ns == *namespace => Some(*id),
4748 _ => None,
4749 })
4750 .collect();
4751 loaded_entries.sort_unstable();
4752 assert_eq!(list_o_ids, loaded_entries);
4753 }
4754 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4755
4756 Ok(())
4757 }
4758
Joel Galenson0891bc12020-07-20 10:37:03 -07004759 // Helpers
4760
4761 // Checks that the given result is an error containing the given string.
4762 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4763 let error_str = format!(
4764 "{:#?}",
4765 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4766 );
4767 assert!(
4768 error_str.contains(target),
4769 "The string \"{}\" should contain \"{}\"",
4770 error_str,
4771 target
4772 );
4773 }
4774
Joel Galenson2aab4432020-07-22 15:27:57 -07004775 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004776 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004777 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004778 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004779 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004780 namespace: Option<i64>,
4781 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004782 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004783 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004784 }
4785
4786 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4787 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004788 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004789 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004790 Ok(KeyEntryRow {
4791 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004792 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004793 domain: match row.get(2)? {
4794 Some(i) => Some(Domain(i)),
4795 None => None,
4796 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004797 namespace: row.get(3)?,
4798 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004799 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004800 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004801 })
4802 })?
4803 .map(|r| r.context("Could not read keyentry row."))
4804 .collect::<Result<Vec<_>>>()
4805 }
4806
Max Biresb2e1d032021-02-08 21:35:05 -08004807 struct RemoteProvValues {
4808 cert_chain: Vec<u8>,
4809 priv_key: Vec<u8>,
4810 batch_cert: Vec<u8>,
4811 }
4812
Max Bires2b2e6562020-09-22 11:22:36 -07004813 fn load_attestation_key_pool(
4814 db: &mut KeystoreDB,
4815 expiration_date: i64,
4816 namespace: i64,
4817 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004818 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004819 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4820 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4821 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4822 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004823 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004824 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4825 db.store_signed_attestation_certificate_chain(
4826 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004827 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004828 &cert_chain,
4829 expiration_date,
4830 &KEYSTORE_UUID,
4831 )?;
4832 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004833 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004834 }
4835
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004836 // Note: The parameters and SecurityLevel associations are nonsensical. This
4837 // collection is only used to check if the parameters are preserved as expected by the
4838 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004839 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4840 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004841 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4842 KeyParameter::new(
4843 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4844 SecurityLevel::TRUSTED_ENVIRONMENT,
4845 ),
4846 KeyParameter::new(
4847 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4848 SecurityLevel::TRUSTED_ENVIRONMENT,
4849 ),
4850 KeyParameter::new(
4851 KeyParameterValue::Algorithm(Algorithm::RSA),
4852 SecurityLevel::TRUSTED_ENVIRONMENT,
4853 ),
4854 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4855 KeyParameter::new(
4856 KeyParameterValue::BlockMode(BlockMode::ECB),
4857 SecurityLevel::TRUSTED_ENVIRONMENT,
4858 ),
4859 KeyParameter::new(
4860 KeyParameterValue::BlockMode(BlockMode::GCM),
4861 SecurityLevel::TRUSTED_ENVIRONMENT,
4862 ),
4863 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4864 KeyParameter::new(
4865 KeyParameterValue::Digest(Digest::MD5),
4866 SecurityLevel::TRUSTED_ENVIRONMENT,
4867 ),
4868 KeyParameter::new(
4869 KeyParameterValue::Digest(Digest::SHA_2_224),
4870 SecurityLevel::TRUSTED_ENVIRONMENT,
4871 ),
4872 KeyParameter::new(
4873 KeyParameterValue::Digest(Digest::SHA_2_256),
4874 SecurityLevel::STRONGBOX,
4875 ),
4876 KeyParameter::new(
4877 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4878 SecurityLevel::TRUSTED_ENVIRONMENT,
4879 ),
4880 KeyParameter::new(
4881 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4882 SecurityLevel::TRUSTED_ENVIRONMENT,
4883 ),
4884 KeyParameter::new(
4885 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4886 SecurityLevel::STRONGBOX,
4887 ),
4888 KeyParameter::new(
4889 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4890 SecurityLevel::TRUSTED_ENVIRONMENT,
4891 ),
4892 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4893 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4894 KeyParameter::new(
4895 KeyParameterValue::EcCurve(EcCurve::P_224),
4896 SecurityLevel::TRUSTED_ENVIRONMENT,
4897 ),
4898 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4899 KeyParameter::new(
4900 KeyParameterValue::EcCurve(EcCurve::P_384),
4901 SecurityLevel::TRUSTED_ENVIRONMENT,
4902 ),
4903 KeyParameter::new(
4904 KeyParameterValue::EcCurve(EcCurve::P_521),
4905 SecurityLevel::TRUSTED_ENVIRONMENT,
4906 ),
4907 KeyParameter::new(
4908 KeyParameterValue::RSAPublicExponent(3),
4909 SecurityLevel::TRUSTED_ENVIRONMENT,
4910 ),
4911 KeyParameter::new(
4912 KeyParameterValue::IncludeUniqueID,
4913 SecurityLevel::TRUSTED_ENVIRONMENT,
4914 ),
4915 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4916 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4917 KeyParameter::new(
4918 KeyParameterValue::ActiveDateTime(1234567890),
4919 SecurityLevel::STRONGBOX,
4920 ),
4921 KeyParameter::new(
4922 KeyParameterValue::OriginationExpireDateTime(1234567890),
4923 SecurityLevel::TRUSTED_ENVIRONMENT,
4924 ),
4925 KeyParameter::new(
4926 KeyParameterValue::UsageExpireDateTime(1234567890),
4927 SecurityLevel::TRUSTED_ENVIRONMENT,
4928 ),
4929 KeyParameter::new(
4930 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4931 SecurityLevel::TRUSTED_ENVIRONMENT,
4932 ),
4933 KeyParameter::new(
4934 KeyParameterValue::MaxUsesPerBoot(1234567890),
4935 SecurityLevel::TRUSTED_ENVIRONMENT,
4936 ),
4937 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4938 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4939 KeyParameter::new(
4940 KeyParameterValue::NoAuthRequired,
4941 SecurityLevel::TRUSTED_ENVIRONMENT,
4942 ),
4943 KeyParameter::new(
4944 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4945 SecurityLevel::TRUSTED_ENVIRONMENT,
4946 ),
4947 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4948 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4949 KeyParameter::new(
4950 KeyParameterValue::TrustedUserPresenceRequired,
4951 SecurityLevel::TRUSTED_ENVIRONMENT,
4952 ),
4953 KeyParameter::new(
4954 KeyParameterValue::TrustedConfirmationRequired,
4955 SecurityLevel::TRUSTED_ENVIRONMENT,
4956 ),
4957 KeyParameter::new(
4958 KeyParameterValue::UnlockedDeviceRequired,
4959 SecurityLevel::TRUSTED_ENVIRONMENT,
4960 ),
4961 KeyParameter::new(
4962 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4963 SecurityLevel::SOFTWARE,
4964 ),
4965 KeyParameter::new(
4966 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4967 SecurityLevel::SOFTWARE,
4968 ),
4969 KeyParameter::new(
4970 KeyParameterValue::CreationDateTime(12345677890),
4971 SecurityLevel::SOFTWARE,
4972 ),
4973 KeyParameter::new(
4974 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4975 SecurityLevel::TRUSTED_ENVIRONMENT,
4976 ),
4977 KeyParameter::new(
4978 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4979 SecurityLevel::TRUSTED_ENVIRONMENT,
4980 ),
4981 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4982 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4983 KeyParameter::new(
4984 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4985 SecurityLevel::SOFTWARE,
4986 ),
4987 KeyParameter::new(
4988 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4989 SecurityLevel::TRUSTED_ENVIRONMENT,
4990 ),
4991 KeyParameter::new(
4992 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4993 SecurityLevel::TRUSTED_ENVIRONMENT,
4994 ),
4995 KeyParameter::new(
4996 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4997 SecurityLevel::TRUSTED_ENVIRONMENT,
4998 ),
4999 KeyParameter::new(
5000 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5001 SecurityLevel::TRUSTED_ENVIRONMENT,
5002 ),
5003 KeyParameter::new(
5004 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5005 SecurityLevel::TRUSTED_ENVIRONMENT,
5006 ),
5007 KeyParameter::new(
5008 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5009 SecurityLevel::TRUSTED_ENVIRONMENT,
5010 ),
5011 KeyParameter::new(
5012 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5013 SecurityLevel::TRUSTED_ENVIRONMENT,
5014 ),
5015 KeyParameter::new(
5016 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5017 SecurityLevel::TRUSTED_ENVIRONMENT,
5018 ),
5019 KeyParameter::new(
5020 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5021 SecurityLevel::TRUSTED_ENVIRONMENT,
5022 ),
5023 KeyParameter::new(
5024 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5025 SecurityLevel::TRUSTED_ENVIRONMENT,
5026 ),
5027 KeyParameter::new(
5028 KeyParameterValue::VendorPatchLevel(3),
5029 SecurityLevel::TRUSTED_ENVIRONMENT,
5030 ),
5031 KeyParameter::new(
5032 KeyParameterValue::BootPatchLevel(4),
5033 SecurityLevel::TRUSTED_ENVIRONMENT,
5034 ),
5035 KeyParameter::new(
5036 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5037 SecurityLevel::TRUSTED_ENVIRONMENT,
5038 ),
5039 KeyParameter::new(
5040 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5041 SecurityLevel::TRUSTED_ENVIRONMENT,
5042 ),
5043 KeyParameter::new(
5044 KeyParameterValue::MacLength(256),
5045 SecurityLevel::TRUSTED_ENVIRONMENT,
5046 ),
5047 KeyParameter::new(
5048 KeyParameterValue::ResetSinceIdRotation,
5049 SecurityLevel::TRUSTED_ENVIRONMENT,
5050 ),
5051 KeyParameter::new(
5052 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5053 SecurityLevel::TRUSTED_ENVIRONMENT,
5054 ),
Qi Wub9433b52020-12-01 14:52:46 +08005055 ];
5056 if let Some(value) = max_usage_count {
5057 params.push(KeyParameter::new(
5058 KeyParameterValue::UsageCountLimit(value),
5059 SecurityLevel::SOFTWARE,
5060 ));
5061 }
5062 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005063 }
5064
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005065 fn make_test_key_entry(
5066 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005067 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005068 namespace: i64,
5069 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005070 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005071 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005072 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005073 let mut blob_metadata = BlobMetaData::new();
5074 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5075 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5076 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5077 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5078 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5079
5080 db.set_blob(
5081 &key_id,
5082 SubComponentType::KEY_BLOB,
5083 Some(TEST_KEY_BLOB),
5084 Some(&blob_metadata),
5085 )?;
5086 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5087 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005088
5089 let params = make_test_params(max_usage_count);
5090 db.insert_keyparameter(&key_id, &params)?;
5091
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005092 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005093 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005094 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005095 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005096 Ok(key_id)
5097 }
5098
Qi Wub9433b52020-12-01 14:52:46 +08005099 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5100 let params = make_test_params(max_usage_count);
5101
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005102 let mut blob_metadata = BlobMetaData::new();
5103 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5104 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5105 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5106 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5107 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5108
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005109 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005110 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005111
5112 KeyEntry {
5113 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005114 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005115 cert: Some(TEST_CERT_BLOB.to_vec()),
5116 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005117 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005118 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005119 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005120 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005121 }
5122 }
5123
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005124 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005125 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005126 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005127 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005128 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005129 NO_PARAMS,
5130 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005131 Ok((
5132 row.get(0)?,
5133 row.get(1)?,
5134 row.get(2)?,
5135 row.get(3)?,
5136 row.get(4)?,
5137 row.get(5)?,
5138 row.get(6)?,
5139 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005140 },
5141 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005142
5143 println!("Key entry table rows:");
5144 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005145 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005146 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005147 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5148 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005149 );
5150 }
5151 Ok(())
5152 }
5153
5154 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005155 let mut stmt = db
5156 .conn
5157 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005158 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5159 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5160 })?;
5161
5162 println!("Grant table rows:");
5163 for r in rows {
5164 let (id, gt, ki, av) = r.unwrap();
5165 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5166 }
5167 Ok(())
5168 }
5169
Joel Galenson0891bc12020-07-20 10:37:03 -07005170 // Use a custom random number generator that repeats each number once.
5171 // This allows us to test repeated elements.
5172
5173 thread_local! {
5174 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5175 }
5176
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005177 fn reset_random() {
5178 RANDOM_COUNTER.with(|counter| {
5179 *counter.borrow_mut() = 0;
5180 })
5181 }
5182
Joel Galenson0891bc12020-07-20 10:37:03 -07005183 pub fn random() -> i64 {
5184 RANDOM_COUNTER.with(|counter| {
5185 let result = *counter.borrow() / 2;
5186 *counter.borrow_mut() += 1;
5187 result
5188 })
5189 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005190
5191 #[test]
5192 fn test_last_off_body() -> Result<()> {
5193 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005194 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005195 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005196 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005197 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005198 let one_second = Duration::from_secs(1);
5199 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005200 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005201 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005202 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005203 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005204 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5205 Ok(())
5206 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005207
5208 #[test]
5209 fn test_unbind_keys_for_user() -> Result<()> {
5210 let mut db = new_test_db()?;
5211 db.unbind_keys_for_user(1, false)?;
5212
5213 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5214 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5215 db.unbind_keys_for_user(2, false)?;
5216
5217 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5218 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5219
5220 db.unbind_keys_for_user(1, true)?;
5221 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5222
5223 Ok(())
5224 }
5225
5226 #[test]
5227 fn test_store_super_key() -> Result<()> {
5228 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005229 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005230 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005231 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005232 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005233 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005234
5235 let (encrypted_super_key, metadata) =
5236 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005237 db.store_super_key(
5238 1,
5239 &USER_SUPER_KEY,
5240 &encrypted_super_key,
5241 &metadata,
5242 &KeyMetaData::new(),
5243 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005244
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005245 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005246 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005247
Paul Crowley7a658392021-03-18 17:08:20 -07005248 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005249 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5250 USER_SUPER_KEY.algorithm,
5251 key_entry,
5252 &pw,
5253 None,
5254 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005255
Paul Crowley7a658392021-03-18 17:08:20 -07005256 let decrypted_secret_bytes =
5257 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5258 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005259 Ok(())
5260 }
Seth Moore78c091f2021-04-09 21:38:30 +00005261
5262 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5263 vec![
5264 StatsdStorageType::KeyEntry,
5265 StatsdStorageType::KeyEntryIdIndex,
5266 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5267 StatsdStorageType::BlobEntry,
5268 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5269 StatsdStorageType::KeyParameter,
5270 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5271 StatsdStorageType::KeyMetadata,
5272 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5273 StatsdStorageType::Grant,
5274 StatsdStorageType::AuthToken,
5275 StatsdStorageType::BlobMetadata,
5276 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5277 ]
5278 }
5279
5280 /// Perform a simple check to ensure that we can query all the storage types
5281 /// that are supported by the DB. Check for reasonable values.
5282 #[test]
5283 fn test_query_all_valid_table_sizes() -> Result<()> {
5284 const PAGE_SIZE: i64 = 4096;
5285
5286 let mut db = new_test_db()?;
5287
5288 for t in get_valid_statsd_storage_types() {
5289 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005290 // AuthToken can be less than a page since it's in a btree, not sqlite
5291 // TODO(b/187474736) stop using if-let here
5292 if let StatsdStorageType::AuthToken = t {
5293 } else {
5294 assert!(stat.size >= PAGE_SIZE);
5295 }
Seth Moore78c091f2021-04-09 21:38:30 +00005296 assert!(stat.size >= stat.unused_size);
5297 }
5298
5299 Ok(())
5300 }
5301
5302 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5303 get_valid_statsd_storage_types()
5304 .into_iter()
5305 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5306 .collect()
5307 }
5308
5309 fn assert_storage_increased(
5310 db: &mut KeystoreDB,
5311 increased_storage_types: Vec<StatsdStorageType>,
5312 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5313 ) {
5314 for storage in increased_storage_types {
5315 // Verify the expected storage increased.
5316 let new = db.get_storage_stat(storage).unwrap();
5317 let storage = storage as i32;
5318 let old = &baseline[&storage];
5319 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5320 assert!(
5321 new.unused_size <= old.unused_size,
5322 "{}: {} <= {}",
5323 storage,
5324 new.unused_size,
5325 old.unused_size
5326 );
5327
5328 // Update the baseline with the new value so that it succeeds in the
5329 // later comparison.
5330 baseline.insert(storage, new);
5331 }
5332
5333 // Get an updated map of the storage and verify there were no unexpected changes.
5334 let updated_stats = get_storage_stats_map(db);
5335 assert_eq!(updated_stats.len(), baseline.len());
5336
5337 for &k in baseline.keys() {
5338 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5339 let mut s = String::new();
5340 for &k in map.keys() {
5341 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5342 .expect("string concat failed");
5343 }
5344 s
5345 };
5346
5347 assert!(
5348 updated_stats[&k].size == baseline[&k].size
5349 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5350 "updated_stats:\n{}\nbaseline:\n{}",
5351 stringify(&updated_stats),
5352 stringify(&baseline)
5353 );
5354 }
5355 }
5356
5357 #[test]
5358 fn test_verify_key_table_size_reporting() -> Result<()> {
5359 let mut db = new_test_db()?;
5360 let mut working_stats = get_storage_stats_map(&mut db);
5361
5362 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5363 assert_storage_increased(
5364 &mut db,
5365 vec![
5366 StatsdStorageType::KeyEntry,
5367 StatsdStorageType::KeyEntryIdIndex,
5368 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5369 ],
5370 &mut working_stats,
5371 );
5372
5373 let mut blob_metadata = BlobMetaData::new();
5374 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5375 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5376 assert_storage_increased(
5377 &mut db,
5378 vec![
5379 StatsdStorageType::BlobEntry,
5380 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5381 StatsdStorageType::BlobMetadata,
5382 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5383 ],
5384 &mut working_stats,
5385 );
5386
5387 let params = make_test_params(None);
5388 db.insert_keyparameter(&key_id, &params)?;
5389 assert_storage_increased(
5390 &mut db,
5391 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5392 &mut working_stats,
5393 );
5394
5395 let mut metadata = KeyMetaData::new();
5396 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5397 db.insert_key_metadata(&key_id, &metadata)?;
5398 assert_storage_increased(
5399 &mut db,
5400 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5401 &mut working_stats,
5402 );
5403
5404 let mut sum = 0;
5405 for stat in working_stats.values() {
5406 sum += stat.size;
5407 }
5408 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5409 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5410
5411 Ok(())
5412 }
5413
5414 #[test]
5415 fn test_verify_auth_table_size_reporting() -> Result<()> {
5416 let mut db = new_test_db()?;
5417 let mut working_stats = get_storage_stats_map(&mut db);
5418 db.insert_auth_token(&HardwareAuthToken {
5419 challenge: 123,
5420 userId: 456,
5421 authenticatorId: 789,
5422 authenticatorType: kmhw_authenticator_type::ANY,
5423 timestamp: Timestamp { milliSeconds: 10 },
5424 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005425 });
Seth Moore78c091f2021-04-09 21:38:30 +00005426 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5427 Ok(())
5428 }
5429
5430 #[test]
5431 fn test_verify_grant_table_size_reporting() -> Result<()> {
5432 const OWNER: i64 = 1;
5433 let mut db = new_test_db()?;
5434 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5435
5436 let mut working_stats = get_storage_stats_map(&mut db);
5437 db.grant(
5438 &KeyDescriptor {
5439 domain: Domain::APP,
5440 nspace: 0,
5441 alias: Some(TEST_ALIAS.to_string()),
5442 blob: None,
5443 },
5444 OWNER as u32,
5445 123,
5446 key_perm_set![KeyPerm::use_()],
5447 |_, _| Ok(()),
5448 )?;
5449
5450 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5451
5452 Ok(())
5453 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005454
5455 #[test]
5456 fn find_auth_token_entry_returns_latest() -> Result<()> {
5457 let mut db = new_test_db()?;
5458 db.insert_auth_token(&HardwareAuthToken {
5459 challenge: 123,
5460 userId: 456,
5461 authenticatorId: 789,
5462 authenticatorType: kmhw_authenticator_type::ANY,
5463 timestamp: Timestamp { milliSeconds: 10 },
5464 mac: b"mac0".to_vec(),
5465 });
5466 std::thread::sleep(std::time::Duration::from_millis(1));
5467 db.insert_auth_token(&HardwareAuthToken {
5468 challenge: 123,
5469 userId: 457,
5470 authenticatorId: 789,
5471 authenticatorType: kmhw_authenticator_type::ANY,
5472 timestamp: Timestamp { milliSeconds: 12 },
5473 mac: b"mac1".to_vec(),
5474 });
5475 std::thread::sleep(std::time::Duration::from_millis(1));
5476 db.insert_auth_token(&HardwareAuthToken {
5477 challenge: 123,
5478 userId: 458,
5479 authenticatorId: 789,
5480 authenticatorType: kmhw_authenticator_type::ANY,
5481 timestamp: Timestamp { milliSeconds: 3 },
5482 mac: b"mac2".to_vec(),
5483 });
5484 // All three entries are in the database
5485 assert_eq!(db.perboot.auth_tokens_len(), 3);
5486 // It selected the most recent timestamp
5487 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5488 Ok(())
5489 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005490}