blob: 073799bae291a2c80435cf4e749ee94e1bed647e [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;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000049use crate::utils::{get_current_time_in_milliseconds, 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
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000741#[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 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000747 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000748 }
749
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000750 /// Returns the value of MonotonicRawTime in milliseconds as i64
751 pub fn milliseconds(&self) -> i64 {
752 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000757 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000758 }
759
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800760 /// Like i64::checked_sub.
761 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
762 self.0.checked_sub(other.0).map(Self)
763 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000764}
765
766impl ToSql for MonotonicRawTime {
767 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
768 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
769 }
770}
771
772impl FromSql for MonotonicRawTime {
773 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
774 Ok(Self(i64::column_result(value)?))
775 }
776}
777
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000778/// This struct encapsulates the information to be stored in the database about the auth tokens
779/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700780#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000781pub struct AuthTokenEntry {
782 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000783 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000784 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000785}
786
787impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000789 AuthTokenEntry { auth_token, time_received }
790 }
791
792 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800793 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000794 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800795 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
796 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 })
798 }
799
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800801 pub fn auth_token(&self) -> &HardwareAuthToken {
802 &self.auth_token
803 }
804
805 /// Returns the auth token wrapped by the AuthTokenEntry
806 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000807 self.auth_token
808 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800809
810 /// Returns the time that this auth token was received.
811 pub fn time_received(&self) -> MonotonicRawTime {
812 self.time_received
813 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000814
815 /// Returns the challenge value of the auth token.
816 pub fn challenge(&self) -> i64 {
817 self.auth_token.challenge
818 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000819}
820
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800821/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
822/// This object does not allow access to the database connection. But it keeps a database
823/// connection alive in order to keep the in memory per boot database alive.
824pub struct PerBootDbKeepAlive(Connection);
825
Joel Galenson26f4d012020-07-17 14:57:21 -0700826impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800827 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800828
Seth Moore78c091f2021-04-09 21:38:30 +0000829 /// Name of the file that holds the cross-boot persistent database.
830 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
831
Seth Moore472fcbb2021-05-12 10:07:51 -0700832 /// Set write-ahead logging mode on the persistent database found in `db_root`.
833 pub fn set_wal_mode(db_root: &Path) -> Result<()> {
834 let path = Self::make_persistent_path(&db_root)?;
835 let conn =
836 Connection::open(path).context("In KeystoreDB::set_wal_mode: Failed to open DB")?;
837 let mode: String = conn
838 .pragma_update_and_check(None, "journal_mode", &"WAL", |row| row.get(0))
839 .context("In KeystoreDB::set_wal_mode: Failed to set journal_mode")?;
840 match mode.as_str() {
841 "wal" => Ok(()),
842 _ => Err(anyhow!("Unable to set WAL mode, db is still in {} mode.", mode)),
843 }
844 }
845
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700846 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800847 /// files persistent.sqlite and perboot.sqlite in the given directory.
848 /// It also attempts to initialize all of the tables.
849 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700850 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700851 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700852 let _wp = wd::watch_millis("KeystoreDB::new", 500);
853
Seth Moore472fcbb2021-05-12 10:07:51 -0700854 let persistent_path = Self::make_persistent_path(&db_root)?;
855 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800856
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
Seth Moore472fcbb2021-05-12 10:07:51 -0700974 fn make_persistent_path(db_root: &Path) -> Result<String> {
975 // Build the path to the sqlite file.
976 let mut persistent_path = db_root.to_path_buf();
977 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
978
979 // Now convert them to strings prefixed with "file:"
980 let mut persistent_path_str = "file:".to_owned();
981 persistent_path_str.push_str(&persistent_path.to_string_lossy());
982
983 Ok(persistent_path_str)
984 }
985
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700986 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700987 let conn =
988 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
989
Janis Danisevskis66784c42021-01-27 08:40:25 -0800990 loop {
991 if let Err(e) = conn
992 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
993 .context("Failed to attach database persistent.")
994 {
995 if Self::is_locked_error(&e) {
996 std::thread::sleep(std::time::Duration::from_micros(500));
997 continue;
998 } else {
999 return Err(e);
1000 }
1001 }
1002 break;
1003 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001004
Matthew Maurer4fb19112021-05-06 15:40:44 -07001005 // Drop the cache size from default (2M) to 0.5M
1006 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1007 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001008
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001009 Ok(conn)
1010 }
1011
Seth Moore78c091f2021-04-09 21:38:30 +00001012 fn do_table_size_query(
1013 &mut self,
1014 storage_type: StatsdStorageType,
1015 query: &str,
1016 params: &[&str],
1017 ) -> Result<Keystore2StorageStats> {
1018 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1019 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1020 .with_context(|| {
1021 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1022 })
1023 .no_gc()
1024 })?;
1025 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1026 }
1027
1028 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1029 self.do_table_size_query(
1030 StatsdStorageType::Database,
1031 "SELECT page_count * page_size, freelist_count * page_size
1032 FROM pragma_page_count('persistent'),
1033 pragma_page_size('persistent'),
1034 persistent.pragma_freelist_count();",
1035 &[],
1036 )
1037 }
1038
1039 fn get_table_size(
1040 &mut self,
1041 storage_type: StatsdStorageType,
1042 schema: &str,
1043 table: &str,
1044 ) -> Result<Keystore2StorageStats> {
1045 self.do_table_size_query(
1046 storage_type,
1047 "SELECT pgsize,unused FROM dbstat(?1)
1048 WHERE name=?2 AND aggregate=TRUE;",
1049 &[schema, table],
1050 )
1051 }
1052
1053 /// Fetches a storage statisitics atom for a given storage type. For storage
1054 /// types that map to a table, information about the table's storage is
1055 /// returned. Requests for storage types that are not DB tables return None.
1056 pub fn get_storage_stat(
1057 &mut self,
1058 storage_type: StatsdStorageType,
1059 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001060 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1061
Seth Moore78c091f2021-04-09 21:38:30 +00001062 match storage_type {
1063 StatsdStorageType::Database => self.get_total_size(),
1064 StatsdStorageType::KeyEntry => {
1065 self.get_table_size(storage_type, "persistent", "keyentry")
1066 }
1067 StatsdStorageType::KeyEntryIdIndex => {
1068 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1069 }
1070 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1071 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1072 }
1073 StatsdStorageType::BlobEntry => {
1074 self.get_table_size(storage_type, "persistent", "blobentry")
1075 }
1076 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1077 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1078 }
1079 StatsdStorageType::KeyParameter => {
1080 self.get_table_size(storage_type, "persistent", "keyparameter")
1081 }
1082 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1083 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1084 }
1085 StatsdStorageType::KeyMetadata => {
1086 self.get_table_size(storage_type, "persistent", "keymetadata")
1087 }
1088 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1089 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1090 }
1091 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1092 StatsdStorageType::AuthToken => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001093 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1094 // reportable
1095 // Size provided is only an approximation
1096 Ok(Keystore2StorageStats {
1097 storage_type,
1098 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1099 as i64,
1100 unused_size: 0,
1101 })
Seth Moore78c091f2021-04-09 21:38:30 +00001102 }
1103 StatsdStorageType::BlobMetadata => {
1104 self.get_table_size(storage_type, "persistent", "blobmetadata")
1105 }
1106 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1107 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1108 }
1109 _ => Err(anyhow::Error::msg(format!(
1110 "Unsupported storage type: {}",
1111 storage_type as i32
1112 ))),
1113 }
1114 }
1115
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001116 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001117 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1118 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001119 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1120 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001121 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001122 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001123 blob_ids_to_delete: &[i64],
1124 max_blobs: usize,
1125 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001126 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001127 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001128 // Delete the given blobs.
1129 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001130 tx.execute(
1131 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001132 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001133 )
1134 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001135 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1136 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001137 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001138
1139 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1140
Janis Danisevskis3395f862021-05-06 10:54:17 -07001141 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1142 let result: Vec<(i64, Vec<u8>)> = {
1143 let mut stmt = tx
1144 .prepare(
1145 "SELECT id, blob FROM persistent.blobentry
1146 WHERE subcomponent_type = ?
1147 AND (
1148 id NOT IN (
1149 SELECT MAX(id) FROM persistent.blobentry
1150 WHERE subcomponent_type = ?
1151 GROUP BY keyentryid, subcomponent_type
1152 )
1153 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1154 ) LIMIT ?;",
1155 )
1156 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001157
Janis Danisevskis3395f862021-05-06 10:54:17 -07001158 let rows = stmt
1159 .query_map(
1160 params![
1161 SubComponentType::KEY_BLOB,
1162 SubComponentType::KEY_BLOB,
1163 max_blobs as i64,
1164 ],
1165 |row| Ok((row.get(0)?, row.get(1)?)),
1166 )
1167 .context("Trying to query superseded blob.")?;
1168
1169 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1170 .context("Trying to extract superseded blobs.")?
1171 };
1172
1173 let result = result
1174 .into_iter()
1175 .map(|(blob_id, blob)| {
1176 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1177 })
1178 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1179 .context("Trying to load blob metadata.")?;
1180 if !result.is_empty() {
1181 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001182 }
1183
1184 // We did not find any superseded key blob, so let's remove other superseded blob in
1185 // one transaction.
1186 tx.execute(
1187 "DELETE FROM persistent.blobentry
1188 WHERE NOT subcomponent_type = ?
1189 AND (
1190 id NOT IN (
1191 SELECT MAX(id) FROM persistent.blobentry
1192 WHERE NOT subcomponent_type = ?
1193 GROUP BY keyentryid, subcomponent_type
1194 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1195 );",
1196 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1197 )
1198 .context("Trying to purge superseded blobs.")?;
1199
Janis Danisevskis3395f862021-05-06 10:54:17 -07001200 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001201 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001202 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001203 }
1204
1205 /// This maintenance function should be called only once before the database is used for the
1206 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1207 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1208 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1209 /// Keystore crashed at some point during key generation. Callers may want to log such
1210 /// occurrences.
1211 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1212 /// it to `KeyLifeCycle::Live` may have grants.
1213 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001214 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1215
Janis Danisevskis66784c42021-01-27 08:40:25 -08001216 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1217 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001218 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1219 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1220 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001221 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001222 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001223 })
1224 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001225 }
1226
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001227 /// Checks if a key exists with given key type and key descriptor properties.
1228 pub fn key_exists(
1229 &mut self,
1230 domain: Domain,
1231 nspace: i64,
1232 alias: &str,
1233 key_type: KeyType,
1234 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001235 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1236
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001237 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1238 let key_descriptor =
1239 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1240 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1241 match result {
1242 Ok(_) => Ok(true),
1243 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1244 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1245 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1246 },
1247 }
1248 .no_gc()
1249 })
1250 .context("In key_exists.")
1251 }
1252
Hasini Gunasingheda895552021-01-27 19:34:37 +00001253 /// Stores a super key in the database.
1254 pub fn store_super_key(
1255 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001256 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001257 key_type: &SuperKeyType,
1258 blob: &[u8],
1259 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001260 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001261 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001262 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1263
Hasini Gunasingheda895552021-01-27 19:34:37 +00001264 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1265 let key_id = Self::insert_with_retry(|id| {
1266 tx.execute(
1267 "INSERT into persistent.keyentry
1268 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001269 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001270 params![
1271 id,
1272 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001273 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001274 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001275 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001276 KeyLifeCycle::Live,
1277 &KEYSTORE_UUID,
1278 ],
1279 )
1280 })
1281 .context("Failed to insert into keyentry table.")?;
1282
Paul Crowley8d5b2532021-03-19 10:53:07 -07001283 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1284
Hasini Gunasingheda895552021-01-27 19:34:37 +00001285 Self::set_blob_internal(
1286 &tx,
1287 key_id,
1288 SubComponentType::KEY_BLOB,
1289 Some(blob),
1290 Some(blob_metadata),
1291 )
1292 .context("Failed to store key blob.")?;
1293
1294 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1295 .context("Trying to load key components.")
1296 .no_gc()
1297 })
1298 .context("In store_super_key.")
1299 }
1300
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001301 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001302 pub fn load_super_key(
1303 &mut self,
1304 key_type: &SuperKeyType,
1305 user_id: u32,
1306 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001307 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1308
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001309 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1310 let key_descriptor = KeyDescriptor {
1311 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001312 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001313 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001314 blob: None,
1315 };
1316 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1317 match id {
1318 Ok(id) => {
1319 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1320 .context("In load_super_key. Failed to load key entry.")?;
1321 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1322 }
1323 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1324 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1325 _ => Err(error).context("In load_super_key."),
1326 },
1327 }
1328 .no_gc()
1329 })
1330 .context("In load_super_key.")
1331 }
1332
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001333 /// Atomically loads a key entry and associated metadata or creates it using the
1334 /// callback create_new_key callback. The callback is called during a database
1335 /// transaction. This means that implementers should be mindful about using
1336 /// blocking operations such as IPC or grabbing mutexes.
1337 pub fn get_or_create_key_with<F>(
1338 &mut self,
1339 domain: Domain,
1340 namespace: i64,
1341 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001342 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001343 create_new_key: F,
1344 ) -> Result<(KeyIdGuard, KeyEntry)>
1345 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001346 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001347 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001348 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1349
Janis Danisevskis66784c42021-01-27 08:40:25 -08001350 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1351 let id = {
1352 let mut stmt = tx
1353 .prepare(
1354 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001355 WHERE
1356 key_type = ?
1357 AND domain = ?
1358 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001359 AND alias = ?
1360 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001361 )
1362 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1363 let mut rows = stmt
1364 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1365 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001366
Janis Danisevskis66784c42021-01-27 08:40:25 -08001367 db_utils::with_rows_extract_one(&mut rows, |row| {
1368 Ok(match row {
1369 Some(r) => r.get(0).context("Failed to unpack id.")?,
1370 None => None,
1371 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001372 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001373 .context("In get_or_create_key_with.")?
1374 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001375
Janis Danisevskis66784c42021-01-27 08:40:25 -08001376 let (id, entry) = match id {
1377 Some(id) => (
1378 id,
1379 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1380 .context("In get_or_create_key_with.")?,
1381 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001382
Janis Danisevskis66784c42021-01-27 08:40:25 -08001383 None => {
1384 let id = Self::insert_with_retry(|id| {
1385 tx.execute(
1386 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001387 (id, key_type, domain, namespace, alias, state, km_uuid)
1388 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001389 params![
1390 id,
1391 KeyType::Super,
1392 domain.0,
1393 namespace,
1394 alias,
1395 KeyLifeCycle::Live,
1396 km_uuid,
1397 ],
1398 )
1399 })
1400 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001401
Janis Danisevskis66784c42021-01-27 08:40:25 -08001402 let (blob, metadata) =
1403 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001404 Self::set_blob_internal(
1405 &tx,
1406 id,
1407 SubComponentType::KEY_BLOB,
1408 Some(&blob),
1409 Some(&metadata),
1410 )
Paul Crowley7a658392021-03-18 17:08:20 -07001411 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001413 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001414 KeyEntry {
1415 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001416 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 pure_cert: false,
1418 ..Default::default()
1419 },
1420 )
1421 }
1422 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001423 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001424 })
1425 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001426 }
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
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002398 WHERE grantee = ? AND id = ? AND
2399 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002400 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002401 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002402 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002403 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002404 .context("Domain:Grant: query failed.")?;
2405 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002406 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002407 let r =
2408 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002409 Ok((
2410 r.get(0).context("Failed to unpack key_id.")?,
2411 r.get(1).context("Failed to unpack access_vector.")?,
2412 ))
2413 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002414 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002415 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002416 }
2417
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002418 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002420 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002421 let (domain, namespace): (Domain, i64) = {
2422 let mut stmt = tx
2423 .prepare(
2424 "SELECT domain, namespace FROM persistent.keyentry
2425 WHERE
2426 id = ?
2427 AND state = ?;",
2428 )
2429 .context("Domain::KEY_ID: prepare statement failed")?;
2430 let mut rows = stmt
2431 .query(params![key.nspace, KeyLifeCycle::Live])
2432 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002433 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002434 let r =
2435 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002436 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002437 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 r.get(1).context("Failed to unpack namespace.")?,
2439 ))
2440 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002441 .context("Domain::KEY_ID.")?
2442 };
2443
2444 // We may use a key by id after loading it by grant.
2445 // In this case we have to check if the caller has a grant for this particular
2446 // key. We can skip this if we already know that the caller is the owner.
2447 // But we cannot know this if domain is anything but App. E.g. in the case
2448 // of Domain::SELINUX we have to speculatively check for grants because we have to
2449 // consult the SEPolicy before we know if the caller is the owner.
2450 let access_vector: Option<KeyPermSet> =
2451 if domain != Domain::APP || namespace != caller_uid as i64 {
2452 let access_vector: Option<i32> = tx
2453 .query_row(
2454 "SELECT access_vector FROM persistent.grant
2455 WHERE grantee = ? AND keyentryid = ?;",
2456 params![caller_uid as i64, key.nspace],
2457 |row| row.get(0),
2458 )
2459 .optional()
2460 .context("Domain::KEY_ID: query grant failed.")?;
2461 access_vector.map(|p| p.into())
2462 } else {
2463 None
2464 };
2465
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002466 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002467 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002468 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002469 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002470
Janis Danisevskis45760022021-01-19 16:34:10 -08002471 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002472 }
2473 _ => Err(anyhow!(KsError::sys())),
2474 }
2475 }
2476
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002477 fn load_blob_components(
2478 key_id: i64,
2479 load_bits: KeyEntryLoadBits,
2480 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002481 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002482 let mut stmt = tx
2483 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002484 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002485 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2486 )
2487 .context("In load_blob_components: prepare statement failed.")?;
2488
2489 let mut rows =
2490 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2491
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002492 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002493 let mut cert_blob: Option<Vec<u8>> = None;
2494 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002495 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002496 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002497 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002498 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002499 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002500 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2501 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002502 key_blob = Some((
2503 row.get(0).context("Failed to extract key blob id.")?,
2504 row.get(2).context("Failed to extract key blob.")?,
2505 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002506 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002507 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002508 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002509 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002510 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002511 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002512 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002513 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002514 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002515 (SubComponentType::CERT, _, _)
2516 | (SubComponentType::CERT_CHAIN, _, _)
2517 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002518 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2519 }
2520 Ok(())
2521 })
2522 .context("In load_blob_components.")?;
2523
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002524 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2525 Ok(Some((
2526 blob,
2527 BlobMetaData::load_from_db(blob_id, tx)
2528 .context("In load_blob_components: Trying to load blob_metadata.")?,
2529 )))
2530 })?;
2531
2532 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002533 }
2534
2535 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2536 let mut stmt = tx
2537 .prepare(
2538 "SELECT tag, data, security_level from persistent.keyparameter
2539 WHERE keyentryid = ?;",
2540 )
2541 .context("In load_key_parameters: prepare statement failed.")?;
2542
2543 let mut parameters: Vec<KeyParameter> = Vec::new();
2544
2545 let mut rows =
2546 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002547 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002548 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2549 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002550 parameters.push(
2551 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2552 .context("Failed to read KeyParameter.")?,
2553 );
2554 Ok(())
2555 })
2556 .context("In load_key_parameters.")?;
2557
2558 Ok(parameters)
2559 }
2560
Qi Wub9433b52020-12-01 14:52:46 +08002561 /// Decrements the usage count of a limited use key. This function first checks whether the
2562 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2563 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2564 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002565 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002566 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2567
Qi Wub9433b52020-12-01 14:52:46 +08002568 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2569 let limit: Option<i32> = tx
2570 .query_row(
2571 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2572 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2573 |row| row.get(0),
2574 )
2575 .optional()
2576 .context("Trying to load usage count")?;
2577
2578 let limit = limit
2579 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2580 .context("The Key no longer exists. Key is exhausted.")?;
2581
2582 tx.execute(
2583 "UPDATE persistent.keyparameter
2584 SET data = data - 1
2585 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2586 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2587 )
2588 .context("Failed to update key usage count.")?;
2589
2590 match limit {
2591 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002592 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002593 .context("Trying to mark limited use key for deletion."),
2594 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002595 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002596 }
2597 })
2598 .context("In check_and_update_key_usage_count.")
2599 }
2600
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002601 /// Load a key entry by the given key descriptor.
2602 /// It uses the `check_permission` callback to verify if the access is allowed
2603 /// given the key access tuple read from the database using `load_access_tuple`.
2604 /// With `load_bits` the caller may specify which blobs shall be loaded from
2605 /// the blob database.
2606 pub fn load_key_entry(
2607 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002608 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002609 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002610 load_bits: KeyEntryLoadBits,
2611 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002612 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2613 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002614 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2615
Janis Danisevskis66784c42021-01-27 08:40:25 -08002616 loop {
2617 match self.load_key_entry_internal(
2618 key,
2619 key_type,
2620 load_bits,
2621 caller_uid,
2622 &check_permission,
2623 ) {
2624 Ok(result) => break Ok(result),
2625 Err(e) => {
2626 if Self::is_locked_error(&e) {
2627 std::thread::sleep(std::time::Duration::from_micros(500));
2628 continue;
2629 } else {
2630 return Err(e).context("In load_key_entry.");
2631 }
2632 }
2633 }
2634 }
2635 }
2636
2637 fn load_key_entry_internal(
2638 &mut self,
2639 key: &KeyDescriptor,
2640 key_type: KeyType,
2641 load_bits: KeyEntryLoadBits,
2642 caller_uid: u32,
2643 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002644 ) -> Result<(KeyIdGuard, KeyEntry)> {
2645 // KEY ID LOCK 1/2
2646 // If we got a key descriptor with a key id we can get the lock right away.
2647 // Otherwise we have to defer it until we know the key id.
2648 let key_id_guard = match key.domain {
2649 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2650 _ => None,
2651 };
2652
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002653 let tx = self
2654 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002655 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002656 .context("In load_key_entry: Failed to initialize transaction.")?;
2657
2658 // Load the key_id and complete the access control tuple.
2659 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002660 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2661 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002662
2663 // Perform access control. It is vital that we return here if the permission is denied.
2664 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002665 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002666
Janis Danisevskisaec14592020-11-12 09:41:49 -08002667 // KEY ID LOCK 2/2
2668 // If we did not get a key id lock by now, it was because we got a key descriptor
2669 // without a key id. At this point we got the key id, so we can try and get a lock.
2670 // However, we cannot block here, because we are in the middle of the transaction.
2671 // So first we try to get the lock non blocking. If that fails, we roll back the
2672 // transaction and block until we get the lock. After we successfully got the lock,
2673 // we start a new transaction and load the access tuple again.
2674 //
2675 // We don't need to perform access control again, because we already established
2676 // that the caller had access to the given key. But we need to make sure that the
2677 // key id still exists. So we have to load the key entry by key id this time.
2678 let (key_id_guard, tx) = match key_id_guard {
2679 None => match KEY_ID_LOCK.try_get(key_id) {
2680 None => {
2681 // Roll back the transaction.
2682 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002683
Janis Danisevskisaec14592020-11-12 09:41:49 -08002684 // Block until we have a key id lock.
2685 let key_id_guard = KEY_ID_LOCK.get(key_id);
2686
2687 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002688 let tx = self
2689 .conn
2690 .unchecked_transaction()
2691 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002692
2693 Self::load_access_tuple(
2694 &tx,
2695 // This time we have to load the key by the retrieved key id, because the
2696 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002697 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002698 domain: Domain::KEY_ID,
2699 nspace: key_id,
2700 ..Default::default()
2701 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002702 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002703 caller_uid,
2704 )
2705 .context("In load_key_entry. (deferred key lock)")?;
2706 (key_id_guard, tx)
2707 }
2708 Some(l) => (l, tx),
2709 },
2710 Some(key_id_guard) => (key_id_guard, tx),
2711 };
2712
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002713 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2714 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002715
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002716 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2717
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002718 Ok((key_id_guard, key_entry))
2719 }
2720
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002721 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002722 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002723 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2724 .context("Trying to delete keyentry.")?;
2725 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2726 .context("Trying to delete keymetadata.")?;
2727 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2728 .context("Trying to delete keyparameters.")?;
2729 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2730 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002731 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002732 }
2733
2734 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002735 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002736 pub fn unbind_key(
2737 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002738 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002739 key_type: KeyType,
2740 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002741 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002742 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002743 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2744
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002745 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2746 let (key_id, access_key_descriptor, access_vector) =
2747 Self::load_access_tuple(tx, key, key_type, caller_uid)
2748 .context("Trying to get access tuple.")?;
2749
2750 // Perform access control. It is vital that we return here if the permission is denied.
2751 // So do not touch that '?' at the end.
2752 check_permission(&access_key_descriptor, access_vector)
2753 .context("While checking permission.")?;
2754
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002755 Self::mark_unreferenced(tx, key_id)
2756 .map(|need_gc| (need_gc, ()))
2757 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002758 })
2759 .context("In unbind_key.")
2760 }
2761
Max Bires8e93d2b2021-01-14 13:17:59 -08002762 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2763 tx.query_row(
2764 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2765 params![key_id],
2766 |row| row.get(0),
2767 )
2768 .context("In get_key_km_uuid.")
2769 }
2770
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002771 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2772 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2773 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002774 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2775
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002776 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2777 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2778 .context("In unbind_keys_for_namespace.");
2779 }
2780 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2781 tx.execute(
2782 "DELETE FROM persistent.keymetadata
2783 WHERE keyentryid IN (
2784 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002785 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002786 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002787 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002788 )
2789 .context("Trying to delete keymetadata.")?;
2790 tx.execute(
2791 "DELETE FROM persistent.keyparameter
2792 WHERE keyentryid IN (
2793 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002794 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002795 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002796 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002797 )
2798 .context("Trying to delete keyparameters.")?;
2799 tx.execute(
2800 "DELETE FROM persistent.grant
2801 WHERE keyentryid IN (
2802 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002803 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002804 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002805 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002806 )
2807 .context("Trying to delete grants.")?;
2808 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002809 "DELETE FROM persistent.keyentry
2810 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2811 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002812 )
2813 .context("Trying to delete keyentry.")?;
2814 Ok(()).need_gc()
2815 })
2816 .context("In unbind_keys_for_namespace")
2817 }
2818
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002819 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2820 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2821 {
2822 tx.execute(
2823 "DELETE FROM persistent.keymetadata
2824 WHERE keyentryid IN (
2825 SELECT id FROM persistent.keyentry
2826 WHERE state = ?
2827 );",
2828 params![KeyLifeCycle::Unreferenced],
2829 )
2830 .context("Trying to delete keymetadata.")?;
2831 tx.execute(
2832 "DELETE FROM persistent.keyparameter
2833 WHERE keyentryid IN (
2834 SELECT id FROM persistent.keyentry
2835 WHERE state = ?
2836 );",
2837 params![KeyLifeCycle::Unreferenced],
2838 )
2839 .context("Trying to delete keyparameters.")?;
2840 tx.execute(
2841 "DELETE FROM persistent.grant
2842 WHERE keyentryid IN (
2843 SELECT id FROM persistent.keyentry
2844 WHERE state = ?
2845 );",
2846 params![KeyLifeCycle::Unreferenced],
2847 )
2848 .context("Trying to delete grants.")?;
2849 tx.execute(
2850 "DELETE FROM persistent.keyentry
2851 WHERE state = ?;",
2852 params![KeyLifeCycle::Unreferenced],
2853 )
2854 .context("Trying to delete keyentry.")?;
2855 Result::<()>::Ok(())
2856 }
2857 .context("In cleanup_unreferenced")
2858 }
2859
Hasini Gunasingheda895552021-01-27 19:34:37 +00002860 /// Delete the keys created on behalf of the user, denoted by the user id.
2861 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2862 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2863 /// The caller of this function should notify the gc if the returned value is true.
2864 pub fn unbind_keys_for_user(
2865 &mut self,
2866 user_id: u32,
2867 keep_non_super_encrypted_keys: bool,
2868 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002869 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2870
Hasini Gunasingheda895552021-01-27 19:34:37 +00002871 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2872 let mut stmt = tx
2873 .prepare(&format!(
2874 "SELECT id from persistent.keyentry
2875 WHERE (
2876 key_type = ?
2877 AND domain = ?
2878 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2879 AND state = ?
2880 ) OR (
2881 key_type = ?
2882 AND namespace = ?
2883 AND alias = ?
2884 AND state = ?
2885 );",
2886 aid_user_offset = AID_USER_OFFSET
2887 ))
2888 .context(concat!(
2889 "In unbind_keys_for_user. ",
2890 "Failed to prepare the query to find the keys created by apps."
2891 ))?;
2892
2893 let mut rows = stmt
2894 .query(params![
2895 // WHERE client key:
2896 KeyType::Client,
2897 Domain::APP.0 as u32,
2898 user_id,
2899 KeyLifeCycle::Live,
2900 // OR super key:
2901 KeyType::Super,
2902 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002903 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002904 KeyLifeCycle::Live
2905 ])
2906 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2907
2908 let mut key_ids: Vec<i64> = Vec::new();
2909 db_utils::with_rows_extract_all(&mut rows, |row| {
2910 key_ids
2911 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2912 Ok(())
2913 })
2914 .context("In unbind_keys_for_user.")?;
2915
2916 let mut notify_gc = false;
2917 for key_id in key_ids {
2918 if keep_non_super_encrypted_keys {
2919 // Load metadata and filter out non-super-encrypted keys.
2920 if let (_, Some((_, blob_metadata)), _, _) =
2921 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2922 .context("In unbind_keys_for_user: Trying to load blob info.")?
2923 {
2924 if blob_metadata.encrypted_by().is_none() {
2925 continue;
2926 }
2927 }
2928 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002929 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002930 .context("In unbind_keys_for_user.")?
2931 || notify_gc;
2932 }
2933 Ok(()).do_gc(notify_gc)
2934 })
2935 .context("In unbind_keys_for_user.")
2936 }
2937
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002938 fn load_key_components(
2939 tx: &Transaction,
2940 load_bits: KeyEntryLoadBits,
2941 key_id: i64,
2942 ) -> Result<KeyEntry> {
2943 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2944
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002945 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002946 Self::load_blob_components(key_id, load_bits, &tx)
2947 .context("In load_key_components.")?;
2948
Max Bires8e93d2b2021-01-14 13:17:59 -08002949 let parameters = Self::load_key_parameters(key_id, &tx)
2950 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002951
Max Bires8e93d2b2021-01-14 13:17:59 -08002952 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2953 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002954
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002955 Ok(KeyEntry {
2956 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002957 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002958 cert: cert_blob,
2959 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002960 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002961 parameters,
2962 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002963 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002964 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002965 }
2966
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002967 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2968 /// The key descriptors will have the domain, nspace, and alias field set.
2969 /// Domain must be APP or SELINUX, the caller must make sure of that.
2970 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002971 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2972
Janis Danisevskis66784c42021-01-27 08:40:25 -08002973 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2974 let mut stmt = tx
2975 .prepare(
2976 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002977 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002978 )
2979 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002980
Janis Danisevskis66784c42021-01-27 08:40:25 -08002981 let mut rows = stmt
2982 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2983 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002984
Janis Danisevskis66784c42021-01-27 08:40:25 -08002985 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2986 db_utils::with_rows_extract_all(&mut rows, |row| {
2987 descriptors.push(KeyDescriptor {
2988 domain,
2989 nspace: namespace,
2990 alias: Some(row.get(0).context("Trying to extract alias.")?),
2991 blob: None,
2992 });
2993 Ok(())
2994 })
2995 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002996 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002997 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002998 }
2999
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003000 /// Adds a grant to the grant table.
3001 /// Like `load_key_entry` this function loads the access tuple before
3002 /// it uses the callback for a permission check. Upon success,
3003 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3004 /// grant table. The new row will have a randomized id, which is used as
3005 /// grant id in the namespace field of the resulting KeyDescriptor.
3006 pub fn grant(
3007 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003008 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003009 caller_uid: u32,
3010 grantee_uid: u32,
3011 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003012 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003013 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003014 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3015
Janis Danisevskis66784c42021-01-27 08:40:25 -08003016 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3017 // Load the key_id and complete the access control tuple.
3018 // We ignore the access vector here because grants cannot be granted.
3019 // The access vector returned here expresses the permissions the
3020 // grantee has if key.domain == Domain::GRANT. But this vector
3021 // cannot include the grant permission by design, so there is no way the
3022 // subsequent permission check can pass.
3023 // We could check key.domain == Domain::GRANT and fail early.
3024 // But even if we load the access tuple by grant here, the permission
3025 // check denies the attempt to create a grant by grant descriptor.
3026 let (key_id, access_key_descriptor, _) =
3027 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3028 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003029
Janis Danisevskis66784c42021-01-27 08:40:25 -08003030 // Perform access control. It is vital that we return here if the permission
3031 // was denied. So do not touch that '?' at the end of the line.
3032 // This permission check checks if the caller has the grant permission
3033 // for the given key and in addition to all of the permissions
3034 // expressed in `access_vector`.
3035 check_permission(&access_key_descriptor, &access_vector)
3036 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003037
Janis Danisevskis66784c42021-01-27 08:40:25 -08003038 let grant_id = if let Some(grant_id) = tx
3039 .query_row(
3040 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003041 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003042 params![key_id, grantee_uid],
3043 |row| row.get(0),
3044 )
3045 .optional()
3046 .context("In grant: Failed get optional existing grant id.")?
3047 {
3048 tx.execute(
3049 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003050 SET access_vector = ?
3051 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003052 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003053 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003054 .context("In grant: Failed to update existing grant.")?;
3055 grant_id
3056 } else {
3057 Self::insert_with_retry(|id| {
3058 tx.execute(
3059 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3060 VALUES (?, ?, ?, ?);",
3061 params![id, grantee_uid, key_id, i32::from(access_vector)],
3062 )
3063 })
3064 .context("In grant")?
3065 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003066
Janis Danisevskis66784c42021-01-27 08:40:25 -08003067 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003068 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003069 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003070 }
3071
3072 /// This function checks permissions like `grant` and `load_key_entry`
3073 /// before removing a grant from the grant table.
3074 pub fn ungrant(
3075 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003076 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003077 caller_uid: u32,
3078 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003079 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003080 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003081 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3082
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3084 // Load the key_id and complete the access control tuple.
3085 // We ignore the access vector here because grants cannot be granted.
3086 let (key_id, access_key_descriptor, _) =
3087 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3088 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003089
Janis Danisevskis66784c42021-01-27 08:40:25 -08003090 // Perform access control. We must return here if the permission
3091 // was denied. So do not touch the '?' at the end of this line.
3092 check_permission(&access_key_descriptor)
3093 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003094
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 tx.execute(
3096 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003097 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003098 params![key_id, grantee_uid],
3099 )
3100 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003102 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003103 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003104 }
3105
Joel Galenson845f74b2020-09-09 14:11:55 -07003106 // Generates a random id and passes it to the given function, which will
3107 // try to insert it into a database. If that insertion fails, retry;
3108 // otherwise return the id.
3109 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3110 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003111 let newid: i64 = match random() {
3112 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3113 i => i,
3114 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003115 match inserter(newid) {
3116 // If the id already existed, try again.
3117 Err(rusqlite::Error::SqliteFailure(
3118 libsqlite3_sys::Error {
3119 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3120 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3121 },
3122 _,
3123 )) => (),
3124 Err(e) => {
3125 return Err(e).context("In insert_with_retry: failed to insert into database.")
3126 }
3127 _ => return Ok(newid),
3128 }
3129 }
3130 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003131
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003132 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3133 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3134 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3135 auth_token.clone(),
3136 MonotonicRawTime::now(),
3137 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003138 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003139
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003140 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003141 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003142 where
3143 F: Fn(&AuthTokenEntry) -> bool,
3144 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003145 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003146 }
3147
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003148 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003149 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3150 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003151 }
3152
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003153 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003154 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3155 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003156 }
3157
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003158 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003159 fn get_last_off_body(&self) -> MonotonicRawTime {
3160 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003161 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003162}
3163
3164#[cfg(test)]
3165mod tests {
3166
3167 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003168 use crate::key_parameter::{
3169 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3170 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3171 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003172 use crate::key_perm_set;
3173 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003174 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003175 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003176 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3177 HardwareAuthToken::HardwareAuthToken,
3178 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003179 };
3180 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003181 Timestamp::Timestamp,
3182 };
Seth Moore472fcbb2021-05-12 10:07:51 -07003183 use rusqlite::DatabaseName::Attached;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003184 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003185 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003186 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003187 use std::collections::BTreeMap;
3188 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003189 use std::sync::atomic::{AtomicU8, Ordering};
3190 use std::sync::Arc;
3191 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003192 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003193 #[cfg(disabled)]
3194 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003195
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003196 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003197 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003198
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003199 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003200 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003201 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003202 })?;
3203 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003204 }
3205
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003206 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3207 where
3208 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3209 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003210 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003211
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003212 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003213 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003214
Janis Danisevskis3395f862021-05-06 10:54:17 -07003215 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003216 }
3217
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003218 fn rebind_alias(
3219 db: &mut KeystoreDB,
3220 newid: &KeyIdGuard,
3221 alias: &str,
3222 domain: Domain,
3223 namespace: i64,
3224 ) -> Result<bool> {
3225 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003226 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003227 })
3228 .context("In rebind_alias.")
3229 }
3230
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003231 #[test]
3232 fn datetime() -> Result<()> {
3233 let conn = Connection::open_in_memory()?;
3234 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3235 let now = SystemTime::now();
3236 let duration = Duration::from_secs(1000);
3237 let then = now.checked_sub(duration).unwrap();
3238 let soon = now.checked_add(duration).unwrap();
3239 conn.execute(
3240 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3241 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3242 )?;
3243 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3244 let mut rows = stmt.query(NO_PARAMS)?;
3245 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3246 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3247 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3248 assert!(rows.next()?.is_none());
3249 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3250 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3251 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3252 Ok(())
3253 }
3254
Joel Galenson0891bc12020-07-20 10:37:03 -07003255 // Ensure that we're using the "injected" random function, not the real one.
3256 #[test]
3257 fn test_mocked_random() {
3258 let rand1 = random();
3259 let rand2 = random();
3260 let rand3 = random();
3261 if rand1 == rand2 {
3262 assert_eq!(rand2 + 1, rand3);
3263 } else {
3264 assert_eq!(rand1 + 1, rand2);
3265 assert_eq!(rand2, rand3);
3266 }
3267 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003268
Joel Galenson26f4d012020-07-17 14:57:21 -07003269 // Test that we have the correct tables.
3270 #[test]
3271 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003272 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003273 let tables = db
3274 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003275 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003276 .query_map(params![], |row| row.get(0))?
3277 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003278 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003279 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003280 assert_eq!(tables[1], "blobmetadata");
3281 assert_eq!(tables[2], "grant");
3282 assert_eq!(tables[3], "keyentry");
3283 assert_eq!(tables[4], "keymetadata");
3284 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003285 Ok(())
3286 }
3287
3288 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003289 fn test_auth_token_table_invariant() -> Result<()> {
3290 let mut db = new_test_db()?;
3291 let auth_token1 = HardwareAuthToken {
3292 challenge: i64::MAX,
3293 userId: 200,
3294 authenticatorId: 200,
3295 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3296 timestamp: Timestamp { milliSeconds: 500 },
3297 mac: String::from("mac").into_bytes(),
3298 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003299 db.insert_auth_token(&auth_token1);
3300 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003301 assert_eq!(auth_tokens_returned.len(), 1);
3302
3303 // insert another auth token with the same values for the columns in the UNIQUE constraint
3304 // of the auth token table and different value for timestamp
3305 let auth_token2 = HardwareAuthToken {
3306 challenge: i64::MAX,
3307 userId: 200,
3308 authenticatorId: 200,
3309 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3310 timestamp: Timestamp { milliSeconds: 600 },
3311 mac: String::from("mac").into_bytes(),
3312 };
3313
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003314 db.insert_auth_token(&auth_token2);
3315 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003316 assert_eq!(auth_tokens_returned.len(), 1);
3317
3318 if let Some(auth_token) = auth_tokens_returned.pop() {
3319 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3320 }
3321
3322 // insert another auth token with the different values for the columns in the UNIQUE
3323 // constraint of the auth token table
3324 let auth_token3 = HardwareAuthToken {
3325 challenge: i64::MAX,
3326 userId: 201,
3327 authenticatorId: 200,
3328 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3329 timestamp: Timestamp { milliSeconds: 600 },
3330 mac: String::from("mac").into_bytes(),
3331 };
3332
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003333 db.insert_auth_token(&auth_token3);
3334 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003335 assert_eq!(auth_tokens_returned.len(), 2);
3336
3337 Ok(())
3338 }
3339
3340 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003341 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3342 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003343 }
3344
3345 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003346 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003347 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003348 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003349
Janis Danisevskis66784c42021-01-27 08:40:25 -08003350 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003351 let entries = get_keyentry(&db)?;
3352 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003353
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003354 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003355
3356 let entries_new = get_keyentry(&db)?;
3357 assert_eq!(entries, entries_new);
3358 Ok(())
3359 }
3360
3361 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003362 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003363 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3364 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003365 }
3366
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003367 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003368
Janis Danisevskis66784c42021-01-27 08:40:25 -08003369 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3370 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003371
3372 let entries = get_keyentry(&db)?;
3373 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003374 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3375 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003376
3377 // Test that we must pass in a valid Domain.
3378 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003379 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003380 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003381 );
3382 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003383 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003384 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003385 );
3386 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003387 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003388 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003389 );
3390
3391 Ok(())
3392 }
3393
Joel Galenson33c04ad2020-08-03 11:04:38 -07003394 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003395 fn test_add_unsigned_key() -> Result<()> {
3396 let mut db = new_test_db()?;
3397 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3398 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3399 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3400 db.create_attestation_key_entry(
3401 &public_key,
3402 &raw_public_key,
3403 &private_key,
3404 &KEYSTORE_UUID,
3405 )?;
3406 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3407 assert_eq!(keys.len(), 1);
3408 assert_eq!(keys[0], public_key);
3409 Ok(())
3410 }
3411
3412 #[test]
3413 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3414 let mut db = new_test_db()?;
3415 let expiration_date: i64 = 20;
3416 let namespace: i64 = 30;
3417 let base_byte: u8 = 1;
3418 let loaded_values =
3419 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3420 let chain =
3421 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3422 assert_eq!(true, chain.is_some());
3423 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003424 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003425 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3426 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003427 Ok(())
3428 }
3429
3430 #[test]
3431 fn test_get_attestation_pool_status() -> Result<()> {
3432 let mut db = new_test_db()?;
3433 let namespace: i64 = 30;
3434 load_attestation_key_pool(
3435 &mut db, 10, /* expiration */
3436 namespace, 0x01, /* base_byte */
3437 )?;
3438 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3439 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3440 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3441 assert_eq!(status.expiring, 0);
3442 assert_eq!(status.attested, 3);
3443 assert_eq!(status.unassigned, 0);
3444 assert_eq!(status.total, 3);
3445 assert_eq!(
3446 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3447 1
3448 );
3449 assert_eq!(
3450 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3451 2
3452 );
3453 assert_eq!(
3454 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3455 3
3456 );
3457 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3458 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3459 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3460 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003461 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003462 db.create_attestation_key_entry(
3463 &public_key,
3464 &raw_public_key,
3465 &private_key,
3466 &KEYSTORE_UUID,
3467 )?;
3468 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3469 assert_eq!(status.attested, 3);
3470 assert_eq!(status.unassigned, 0);
3471 assert_eq!(status.total, 4);
3472 db.store_signed_attestation_certificate_chain(
3473 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003474 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003475 &cert_chain,
3476 20,
3477 &KEYSTORE_UUID,
3478 )?;
3479 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3480 assert_eq!(status.attested, 4);
3481 assert_eq!(status.unassigned, 1);
3482 assert_eq!(status.total, 4);
3483 Ok(())
3484 }
3485
3486 #[test]
3487 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003488 let temp_dir =
3489 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3490 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003491 let expiration_date: i64 =
3492 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3493 let namespace: i64 = 30;
3494 let namespace_del1: i64 = 45;
3495 let namespace_del2: i64 = 60;
3496 let entry_values = load_attestation_key_pool(
3497 &mut db,
3498 expiration_date,
3499 namespace,
3500 0x01, /* base_byte */
3501 )?;
3502 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3503 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003504
3505 let blob_entry_row_count: u32 = db
3506 .conn
3507 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3508 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003509 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3510 // one key, one certificate chain, and one certificate.
3511 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003512
Max Bires2b2e6562020-09-22 11:22:36 -07003513 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3514
3515 let mut cert_chain =
3516 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003517 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003518 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003519 assert_eq!(entry_values.batch_cert, value.batch_cert);
3520 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003521 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003522
3523 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3524 Domain::APP,
3525 namespace_del1,
3526 &KEYSTORE_UUID,
3527 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003528 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003529 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3530 Domain::APP,
3531 namespace_del2,
3532 &KEYSTORE_UUID,
3533 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003534 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003535
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003536 // Give the garbage collector half a second to catch up.
3537 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003538
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003539 let blob_entry_row_count: u32 = db
3540 .conn
3541 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3542 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003543 // There shound be 3 blob entries left, because we deleted two of the attestation
3544 // key entries with three blobs each.
3545 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003546
Max Bires2b2e6562020-09-22 11:22:36 -07003547 Ok(())
3548 }
3549
3550 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003551 fn test_delete_all_attestation_keys() -> Result<()> {
3552 let mut db = new_test_db()?;
3553 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3554 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3555 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3556 let result = db.delete_all_attestation_keys()?;
3557
3558 // Give the garbage collector half a second to catch up.
3559 std::thread::sleep(Duration::from_millis(500));
3560
3561 // Attestation keys should be deleted, and the regular key should remain.
3562 assert_eq!(result, 2);
3563
3564 Ok(())
3565 }
3566
3567 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003568 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003569 fn extractor(
3570 ke: &KeyEntryRow,
3571 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3572 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003573 }
3574
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003575 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003576 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3577 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003578 let entries = get_keyentry(&db)?;
3579 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003580 assert_eq!(
3581 extractor(&entries[0]),
3582 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3583 );
3584 assert_eq!(
3585 extractor(&entries[1]),
3586 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3587 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003588
3589 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003590 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003591 let entries = get_keyentry(&db)?;
3592 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003593 assert_eq!(
3594 extractor(&entries[0]),
3595 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3596 );
3597 assert_eq!(
3598 extractor(&entries[1]),
3599 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3600 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003601
3602 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003603 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003604 let entries = get_keyentry(&db)?;
3605 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003606 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3607 assert_eq!(
3608 extractor(&entries[1]),
3609 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3610 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003611
3612 // Test that we must pass in a valid Domain.
3613 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003614 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003615 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003616 );
3617 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003618 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003619 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003620 );
3621 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003622 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003623 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003624 );
3625
3626 // Test that we correctly handle setting an alias for something that does not exist.
3627 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003628 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003629 "Expected to update a single entry but instead updated 0",
3630 );
3631 // Test that we correctly abort the transaction in this case.
3632 let entries = get_keyentry(&db)?;
3633 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003634 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3635 assert_eq!(
3636 extractor(&entries[1]),
3637 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3638 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003639
3640 Ok(())
3641 }
3642
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003643 #[test]
3644 fn test_grant_ungrant() -> Result<()> {
3645 const CALLER_UID: u32 = 15;
3646 const GRANTEE_UID: u32 = 12;
3647 const SELINUX_NAMESPACE: i64 = 7;
3648
3649 let mut db = new_test_db()?;
3650 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003651 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3652 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3653 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003654 )?;
3655 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003656 domain: super::Domain::APP,
3657 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003658 alias: Some("key".to_string()),
3659 blob: None,
3660 };
3661 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3662 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3663
3664 // Reset totally predictable random number generator in case we
3665 // are not the first test running on this thread.
3666 reset_random();
3667 let next_random = 0i64;
3668
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003669 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003670 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003671 assert_eq!(*a, PVEC1);
3672 assert_eq!(
3673 *k,
3674 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003675 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003676 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003677 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003678 alias: Some("key".to_string()),
3679 blob: None,
3680 }
3681 );
3682 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003683 })
3684 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003685
3686 assert_eq!(
3687 app_granted_key,
3688 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003689 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003690 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003691 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003692 alias: None,
3693 blob: None,
3694 }
3695 );
3696
3697 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003698 domain: super::Domain::SELINUX,
3699 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003700 alias: Some("yek".to_string()),
3701 blob: None,
3702 };
3703
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003704 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003705 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003706 assert_eq!(*a, PVEC1);
3707 assert_eq!(
3708 *k,
3709 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003710 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003711 // namespace must be the supplied SELinux
3712 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003713 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003714 alias: Some("yek".to_string()),
3715 blob: None,
3716 }
3717 );
3718 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003719 })
3720 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003721
3722 assert_eq!(
3723 selinux_granted_key,
3724 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003725 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003726 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003727 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003728 alias: None,
3729 blob: None,
3730 }
3731 );
3732
3733 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003734 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003735 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003736 assert_eq!(*a, PVEC2);
3737 assert_eq!(
3738 *k,
3739 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003740 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003741 // namespace must be the supplied SELinux
3742 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003743 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003744 alias: Some("yek".to_string()),
3745 blob: None,
3746 }
3747 );
3748 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003749 })
3750 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003751
3752 assert_eq!(
3753 selinux_granted_key,
3754 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003755 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003756 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003757 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003758 alias: None,
3759 blob: None,
3760 }
3761 );
3762
3763 {
3764 // Limiting scope of stmt, because it borrows db.
3765 let mut stmt = db
3766 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003767 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003768 let mut rows =
3769 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3770 Ok((
3771 row.get(0)?,
3772 row.get(1)?,
3773 row.get(2)?,
3774 KeyPermSet::from(row.get::<_, i32>(3)?),
3775 ))
3776 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003777
3778 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003779 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003780 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003781 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003782 assert!(rows.next().is_none());
3783 }
3784
3785 debug_dump_keyentry_table(&mut db)?;
3786 println!("app_key {:?}", app_key);
3787 println!("selinux_key {:?}", selinux_key);
3788
Janis Danisevskis66784c42021-01-27 08:40:25 -08003789 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3790 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003791
3792 Ok(())
3793 }
3794
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003795 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003796 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3797 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3798
3799 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003800 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003801 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003802 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003803 let mut blob_metadata = BlobMetaData::new();
3804 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3805 db.set_blob(
3806 &key_id,
3807 SubComponentType::KEY_BLOB,
3808 Some(TEST_KEY_BLOB),
3809 Some(&blob_metadata),
3810 )?;
3811 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3812 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003813 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003814
3815 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003816 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003817 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003818 )?;
3819 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003820 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3821 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003822 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003823 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003824 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_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, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003827 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003828 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003829
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003830 drop(rows);
3831 drop(stmt);
3832
3833 assert_eq!(
3834 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3835 BlobMetaData::load_from_db(id, tx).no_gc()
3836 })
3837 .expect("Should find blob metadata."),
3838 blob_metadata
3839 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003840 Ok(())
3841 }
3842
3843 static TEST_ALIAS: &str = "my super duper key";
3844
3845 #[test]
3846 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3847 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003848 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003849 .context("test_insert_and_load_full_keyentry_domain_app")?
3850 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003851 let (_key_guard, key_entry) = db
3852 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003853 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003854 domain: Domain::APP,
3855 nspace: 0,
3856 alias: Some(TEST_ALIAS.to_string()),
3857 blob: None,
3858 },
3859 KeyType::Client,
3860 KeyEntryLoadBits::BOTH,
3861 1,
3862 |_k, _av| Ok(()),
3863 )
3864 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003865 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003866
3867 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003868 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003869 domain: Domain::APP,
3870 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003871 alias: Some(TEST_ALIAS.to_string()),
3872 blob: None,
3873 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003874 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003875 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003876 |_, _| Ok(()),
3877 )
3878 .unwrap();
3879
3880 assert_eq!(
3881 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3882 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003883 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003884 domain: Domain::APP,
3885 nspace: 0,
3886 alias: Some(TEST_ALIAS.to_string()),
3887 blob: None,
3888 },
3889 KeyType::Client,
3890 KeyEntryLoadBits::NONE,
3891 1,
3892 |_k, _av| Ok(()),
3893 )
3894 .unwrap_err()
3895 .root_cause()
3896 .downcast_ref::<KsError>()
3897 );
3898
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003899 Ok(())
3900 }
3901
3902 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003903 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3904 let mut db = new_test_db()?;
3905
3906 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003907 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003908 domain: Domain::APP,
3909 nspace: 1,
3910 alias: Some(TEST_ALIAS.to_string()),
3911 blob: None,
3912 },
3913 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003914 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003915 )
3916 .expect("Trying to insert cert.");
3917
3918 let (_key_guard, mut key_entry) = db
3919 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003920 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003921 domain: Domain::APP,
3922 nspace: 1,
3923 alias: Some(TEST_ALIAS.to_string()),
3924 blob: None,
3925 },
3926 KeyType::Client,
3927 KeyEntryLoadBits::PUBLIC,
3928 1,
3929 |_k, _av| Ok(()),
3930 )
3931 .expect("Trying to read certificate entry.");
3932
3933 assert!(key_entry.pure_cert());
3934 assert!(key_entry.cert().is_none());
3935 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3936
3937 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003938 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003939 domain: Domain::APP,
3940 nspace: 1,
3941 alias: Some(TEST_ALIAS.to_string()),
3942 blob: None,
3943 },
3944 KeyType::Client,
3945 1,
3946 |_, _| Ok(()),
3947 )
3948 .unwrap();
3949
3950 assert_eq!(
3951 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3952 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003953 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003954 domain: Domain::APP,
3955 nspace: 1,
3956 alias: Some(TEST_ALIAS.to_string()),
3957 blob: None,
3958 },
3959 KeyType::Client,
3960 KeyEntryLoadBits::NONE,
3961 1,
3962 |_k, _av| Ok(()),
3963 )
3964 .unwrap_err()
3965 .root_cause()
3966 .downcast_ref::<KsError>()
3967 );
3968
3969 Ok(())
3970 }
3971
3972 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003973 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3974 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003975 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003976 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3977 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003978 let (_key_guard, key_entry) = db
3979 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003980 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003981 domain: Domain::SELINUX,
3982 nspace: 1,
3983 alias: Some(TEST_ALIAS.to_string()),
3984 blob: None,
3985 },
3986 KeyType::Client,
3987 KeyEntryLoadBits::BOTH,
3988 1,
3989 |_k, _av| Ok(()),
3990 )
3991 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003992 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003993
3994 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003995 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003996 domain: Domain::SELINUX,
3997 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003998 alias: Some(TEST_ALIAS.to_string()),
3999 blob: None,
4000 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004001 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004002 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004003 |_, _| Ok(()),
4004 )
4005 .unwrap();
4006
4007 assert_eq!(
4008 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4009 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004010 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004011 domain: Domain::SELINUX,
4012 nspace: 1,
4013 alias: Some(TEST_ALIAS.to_string()),
4014 blob: None,
4015 },
4016 KeyType::Client,
4017 KeyEntryLoadBits::NONE,
4018 1,
4019 |_k, _av| Ok(()),
4020 )
4021 .unwrap_err()
4022 .root_cause()
4023 .downcast_ref::<KsError>()
4024 );
4025
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004026 Ok(())
4027 }
4028
4029 #[test]
4030 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4031 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004032 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004033 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4034 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004035 let (_, key_entry) = db
4036 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004037 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004038 KeyType::Client,
4039 KeyEntryLoadBits::BOTH,
4040 1,
4041 |_k, _av| Ok(()),
4042 )
4043 .unwrap();
4044
Qi Wub9433b52020-12-01 14:52:46 +08004045 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004046
4047 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004048 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004049 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004050 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004051 |_, _| Ok(()),
4052 )
4053 .unwrap();
4054
4055 assert_eq!(
4056 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4057 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004058 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004059 KeyType::Client,
4060 KeyEntryLoadBits::NONE,
4061 1,
4062 |_k, _av| Ok(()),
4063 )
4064 .unwrap_err()
4065 .root_cause()
4066 .downcast_ref::<KsError>()
4067 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004068
4069 Ok(())
4070 }
4071
4072 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004073 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4074 let mut db = new_test_db()?;
4075 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4076 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4077 .0;
4078 // Update the usage count of the limited use key.
4079 db.check_and_update_key_usage_count(key_id)?;
4080
4081 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004082 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004083 KeyType::Client,
4084 KeyEntryLoadBits::BOTH,
4085 1,
4086 |_k, _av| Ok(()),
4087 )?;
4088
4089 // The usage count is decremented now.
4090 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4091
4092 Ok(())
4093 }
4094
4095 #[test]
4096 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4097 let mut db = new_test_db()?;
4098 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4099 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4100 .0;
4101 // Update the usage count of the limited use key.
4102 db.check_and_update_key_usage_count(key_id).expect(concat!(
4103 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4104 "This should succeed."
4105 ));
4106
4107 // Try to update the exhausted limited use key.
4108 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4109 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4110 "This should fail."
4111 ));
4112 assert_eq!(
4113 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4114 e.root_cause().downcast_ref::<KsError>().unwrap()
4115 );
4116
4117 Ok(())
4118 }
4119
4120 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004121 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4122 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004123 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004124 .context("test_insert_and_load_full_keyentry_from_grant")?
4125 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004126
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004127 let granted_key = db
4128 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004129 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004130 domain: Domain::APP,
4131 nspace: 0,
4132 alias: Some(TEST_ALIAS.to_string()),
4133 blob: None,
4134 },
4135 1,
4136 2,
4137 key_perm_set![KeyPerm::use_()],
4138 |_k, _av| Ok(()),
4139 )
4140 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004141
4142 debug_dump_grant_table(&mut db)?;
4143
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004144 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004145 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4146 assert_eq!(Domain::GRANT, k.domain);
4147 assert!(av.unwrap().includes(KeyPerm::use_()));
4148 Ok(())
4149 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004150 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004151
Qi Wub9433b52020-12-01 14:52:46 +08004152 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004153
Janis Danisevskis66784c42021-01-27 08:40:25 -08004154 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004155
4156 assert_eq!(
4157 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4158 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004159 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004160 KeyType::Client,
4161 KeyEntryLoadBits::NONE,
4162 2,
4163 |_k, _av| Ok(()),
4164 )
4165 .unwrap_err()
4166 .root_cause()
4167 .downcast_ref::<KsError>()
4168 );
4169
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004170 Ok(())
4171 }
4172
Janis Danisevskis45760022021-01-19 16:34:10 -08004173 // This test attempts to load a key by key id while the caller is not the owner
4174 // but a grant exists for the given key and the caller.
4175 #[test]
4176 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4177 let mut db = new_test_db()?;
4178 const OWNER_UID: u32 = 1u32;
4179 const GRANTEE_UID: u32 = 2u32;
4180 const SOMEONE_ELSE_UID: u32 = 3u32;
4181 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4182 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4183 .0;
4184
4185 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004186 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004187 domain: Domain::APP,
4188 nspace: 0,
4189 alias: Some(TEST_ALIAS.to_string()),
4190 blob: None,
4191 },
4192 OWNER_UID,
4193 GRANTEE_UID,
4194 key_perm_set![KeyPerm::use_()],
4195 |_k, _av| Ok(()),
4196 )
4197 .unwrap();
4198
4199 debug_dump_grant_table(&mut db)?;
4200
4201 let id_descriptor =
4202 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4203
4204 let (_, key_entry) = db
4205 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004206 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004207 KeyType::Client,
4208 KeyEntryLoadBits::BOTH,
4209 GRANTEE_UID,
4210 |k, av| {
4211 assert_eq!(Domain::APP, k.domain);
4212 assert_eq!(OWNER_UID as i64, k.nspace);
4213 assert!(av.unwrap().includes(KeyPerm::use_()));
4214 Ok(())
4215 },
4216 )
4217 .unwrap();
4218
4219 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4220
4221 let (_, key_entry) = db
4222 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004223 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004224 KeyType::Client,
4225 KeyEntryLoadBits::BOTH,
4226 SOMEONE_ELSE_UID,
4227 |k, av| {
4228 assert_eq!(Domain::APP, k.domain);
4229 assert_eq!(OWNER_UID as i64, k.nspace);
4230 assert!(av.is_none());
4231 Ok(())
4232 },
4233 )
4234 .unwrap();
4235
4236 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4237
Janis Danisevskis66784c42021-01-27 08:40:25 -08004238 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004239
4240 assert_eq!(
4241 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4242 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004243 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004244 KeyType::Client,
4245 KeyEntryLoadBits::NONE,
4246 GRANTEE_UID,
4247 |_k, _av| Ok(()),
4248 )
4249 .unwrap_err()
4250 .root_cause()
4251 .downcast_ref::<KsError>()
4252 );
4253
4254 Ok(())
4255 }
4256
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004257 // Creates a key migrates it to a different location and then tries to access it by the old
4258 // and new location.
4259 #[test]
4260 fn test_migrate_key_app_to_app() -> Result<()> {
4261 let mut db = new_test_db()?;
4262 const SOURCE_UID: u32 = 1u32;
4263 const DESTINATION_UID: u32 = 2u32;
4264 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4265 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4266 let key_id_guard =
4267 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4268 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4269
4270 let source_descriptor: KeyDescriptor = KeyDescriptor {
4271 domain: Domain::APP,
4272 nspace: -1,
4273 alias: Some(SOURCE_ALIAS.to_string()),
4274 blob: None,
4275 };
4276
4277 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4278 domain: Domain::APP,
4279 nspace: -1,
4280 alias: Some(DESTINATION_ALIAS.to_string()),
4281 blob: None,
4282 };
4283
4284 let key_id = key_id_guard.id();
4285
4286 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4287 Ok(())
4288 })
4289 .unwrap();
4290
4291 let (_, key_entry) = db
4292 .load_key_entry(
4293 &destination_descriptor,
4294 KeyType::Client,
4295 KeyEntryLoadBits::BOTH,
4296 DESTINATION_UID,
4297 |k, av| {
4298 assert_eq!(Domain::APP, k.domain);
4299 assert_eq!(DESTINATION_UID as i64, k.nspace);
4300 assert!(av.is_none());
4301 Ok(())
4302 },
4303 )
4304 .unwrap();
4305
4306 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4307
4308 assert_eq!(
4309 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4310 db.load_key_entry(
4311 &source_descriptor,
4312 KeyType::Client,
4313 KeyEntryLoadBits::NONE,
4314 SOURCE_UID,
4315 |_k, _av| Ok(()),
4316 )
4317 .unwrap_err()
4318 .root_cause()
4319 .downcast_ref::<KsError>()
4320 );
4321
4322 Ok(())
4323 }
4324
4325 // Creates a key migrates it to a different location and then tries to access it by the old
4326 // and new location.
4327 #[test]
4328 fn test_migrate_key_app_to_selinux() -> Result<()> {
4329 let mut db = new_test_db()?;
4330 const SOURCE_UID: u32 = 1u32;
4331 const DESTINATION_UID: u32 = 2u32;
4332 const DESTINATION_NAMESPACE: i64 = 1000i64;
4333 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4334 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4335 let key_id_guard =
4336 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4337 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4338
4339 let source_descriptor: KeyDescriptor = KeyDescriptor {
4340 domain: Domain::APP,
4341 nspace: -1,
4342 alias: Some(SOURCE_ALIAS.to_string()),
4343 blob: None,
4344 };
4345
4346 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4347 domain: Domain::SELINUX,
4348 nspace: DESTINATION_NAMESPACE,
4349 alias: Some(DESTINATION_ALIAS.to_string()),
4350 blob: None,
4351 };
4352
4353 let key_id = key_id_guard.id();
4354
4355 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4356 Ok(())
4357 })
4358 .unwrap();
4359
4360 let (_, key_entry) = db
4361 .load_key_entry(
4362 &destination_descriptor,
4363 KeyType::Client,
4364 KeyEntryLoadBits::BOTH,
4365 DESTINATION_UID,
4366 |k, av| {
4367 assert_eq!(Domain::SELINUX, k.domain);
4368 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4369 assert!(av.is_none());
4370 Ok(())
4371 },
4372 )
4373 .unwrap();
4374
4375 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4376
4377 assert_eq!(
4378 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4379 db.load_key_entry(
4380 &source_descriptor,
4381 KeyType::Client,
4382 KeyEntryLoadBits::NONE,
4383 SOURCE_UID,
4384 |_k, _av| Ok(()),
4385 )
4386 .unwrap_err()
4387 .root_cause()
4388 .downcast_ref::<KsError>()
4389 );
4390
4391 Ok(())
4392 }
4393
4394 // Creates two keys and tries to migrate the first to the location of the second which
4395 // is expected to fail.
4396 #[test]
4397 fn test_migrate_key_destination_occupied() -> Result<()> {
4398 let mut db = new_test_db()?;
4399 const SOURCE_UID: u32 = 1u32;
4400 const DESTINATION_UID: u32 = 2u32;
4401 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4402 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4403 let key_id_guard =
4404 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4405 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4406 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4407 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4408
4409 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4410 domain: Domain::APP,
4411 nspace: -1,
4412 alias: Some(DESTINATION_ALIAS.to_string()),
4413 blob: None,
4414 };
4415
4416 assert_eq!(
4417 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4418 db.migrate_key_namespace(
4419 key_id_guard,
4420 &destination_descriptor,
4421 DESTINATION_UID,
4422 |_k| Ok(())
4423 )
4424 .unwrap_err()
4425 .root_cause()
4426 .downcast_ref::<KsError>()
4427 );
4428
4429 Ok(())
4430 }
4431
Janis Danisevskisaec14592020-11-12 09:41:49 -08004432 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4433
Janis Danisevskisaec14592020-11-12 09:41:49 -08004434 #[test]
4435 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4436 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004437 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4438 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004439 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004440 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004441 .context("test_insert_and_load_full_keyentry_domain_app")?
4442 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004443 let (_key_guard, key_entry) = db
4444 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004445 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004446 domain: Domain::APP,
4447 nspace: 0,
4448 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4449 blob: None,
4450 },
4451 KeyType::Client,
4452 KeyEntryLoadBits::BOTH,
4453 33,
4454 |_k, _av| Ok(()),
4455 )
4456 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004457 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004458 let state = Arc::new(AtomicU8::new(1));
4459 let state2 = state.clone();
4460
4461 // Spawning a second thread that attempts to acquire the key id lock
4462 // for the same key as the primary thread. The primary thread then
4463 // waits, thereby forcing the secondary thread into the second stage
4464 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4465 // The test succeeds if the secondary thread observes the transition
4466 // of `state` from 1 to 2, despite having a whole second to overtake
4467 // the primary thread.
4468 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004469 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004470 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004471 assert!(db
4472 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004473 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004474 domain: Domain::APP,
4475 nspace: 0,
4476 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4477 blob: None,
4478 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004479 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004480 KeyEntryLoadBits::BOTH,
4481 33,
4482 |_k, _av| Ok(()),
4483 )
4484 .is_ok());
4485 // We should only see a 2 here because we can only return
4486 // from load_key_entry when the `_key_guard` expires,
4487 // which happens at the end of the scope.
4488 assert_eq!(2, state2.load(Ordering::Relaxed));
4489 });
4490
4491 thread::sleep(std::time::Duration::from_millis(1000));
4492
4493 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4494
4495 // Return the handle from this scope so we can join with the
4496 // secondary thread after the key id lock has expired.
4497 handle
4498 // This is where the `_key_guard` goes out of scope,
4499 // which is the reason for concurrent load_key_entry on the same key
4500 // to unblock.
4501 };
4502 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4503 // main test thread. We will not see failing asserts in secondary threads otherwise.
4504 handle.join().unwrap();
4505 Ok(())
4506 }
4507
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004508 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004509 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004510 let temp_dir =
4511 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4512
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004513 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4514 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004515
4516 let _tx1 = db1
4517 .conn
4518 .transaction_with_behavior(TransactionBehavior::Immediate)
4519 .expect("Failed to create first transaction.");
4520
4521 let error = db2
4522 .conn
4523 .transaction_with_behavior(TransactionBehavior::Immediate)
4524 .context("Transaction begin failed.")
4525 .expect_err("This should fail.");
4526 let root_cause = error.root_cause();
4527 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4528 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4529 {
4530 return;
4531 }
4532 panic!(
4533 "Unexpected error {:?} \n{:?} \n{:?}",
4534 error,
4535 root_cause,
4536 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4537 )
4538 }
4539
4540 #[cfg(disabled)]
4541 #[test]
4542 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4543 let temp_dir = Arc::new(
4544 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4545 .expect("Failed to create temp dir."),
4546 );
4547
4548 let test_begin = Instant::now();
4549
4550 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4551 const KEY_COUNT: u32 = 500u32;
4552 const OPEN_DB_COUNT: u32 = 50u32;
4553
4554 let mut actual_key_count = KEY_COUNT;
4555 // First insert KEY_COUNT keys.
4556 for count in 0..KEY_COUNT {
4557 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4558 actual_key_count = count;
4559 break;
4560 }
4561 let alias = format!("test_alias_{}", count);
4562 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4563 .expect("Failed to make key entry.");
4564 }
4565
4566 // Insert more keys from a different thread and into a different namespace.
4567 let temp_dir1 = temp_dir.clone();
4568 let handle1 = thread::spawn(move || {
4569 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4570
4571 for count in 0..actual_key_count {
4572 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4573 return;
4574 }
4575 let alias = format!("test_alias_{}", count);
4576 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4577 .expect("Failed to make key entry.");
4578 }
4579
4580 // then unbind them again.
4581 for count in 0..actual_key_count {
4582 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4583 return;
4584 }
4585 let key = KeyDescriptor {
4586 domain: Domain::APP,
4587 nspace: -1,
4588 alias: Some(format!("test_alias_{}", count)),
4589 blob: None,
4590 };
4591 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4592 }
4593 });
4594
4595 // And start unbinding the first set of keys.
4596 let temp_dir2 = temp_dir.clone();
4597 let handle2 = thread::spawn(move || {
4598 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4599
4600 for count in 0..actual_key_count {
4601 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4602 return;
4603 }
4604 let key = KeyDescriptor {
4605 domain: Domain::APP,
4606 nspace: -1,
4607 alias: Some(format!("test_alias_{}", count)),
4608 blob: None,
4609 };
4610 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4611 }
4612 });
4613
4614 let stop_deleting = Arc::new(AtomicU8::new(0));
4615 let stop_deleting2 = stop_deleting.clone();
4616
4617 // And delete anything that is unreferenced keys.
4618 let temp_dir3 = temp_dir.clone();
4619 let handle3 = thread::spawn(move || {
4620 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4621
4622 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4623 while let Some((key_guard, _key)) =
4624 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4625 {
4626 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4627 return;
4628 }
4629 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4630 }
4631 std::thread::sleep(std::time::Duration::from_millis(100));
4632 }
4633 });
4634
4635 // While a lot of inserting and deleting is going on we have to open database connections
4636 // successfully and use them.
4637 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4638 // out of scope.
4639 #[allow(clippy::redundant_clone)]
4640 let temp_dir4 = temp_dir.clone();
4641 let handle4 = thread::spawn(move || {
4642 for count in 0..OPEN_DB_COUNT {
4643 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4644 return;
4645 }
4646 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4647
4648 let alias = format!("test_alias_{}", count);
4649 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4650 .expect("Failed to make key entry.");
4651 let key = KeyDescriptor {
4652 domain: Domain::APP,
4653 nspace: -1,
4654 alias: Some(alias),
4655 blob: None,
4656 };
4657 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4658 }
4659 });
4660
4661 handle1.join().expect("Thread 1 panicked.");
4662 handle2.join().expect("Thread 2 panicked.");
4663 handle4.join().expect("Thread 4 panicked.");
4664
4665 stop_deleting.store(1, Ordering::Relaxed);
4666 handle3.join().expect("Thread 3 panicked.");
4667
4668 Ok(())
4669 }
4670
4671 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004672 fn list() -> Result<()> {
4673 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004674 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004675 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4676 (Domain::APP, 1, "test1"),
4677 (Domain::APP, 1, "test2"),
4678 (Domain::APP, 1, "test3"),
4679 (Domain::APP, 1, "test4"),
4680 (Domain::APP, 1, "test5"),
4681 (Domain::APP, 1, "test6"),
4682 (Domain::APP, 1, "test7"),
4683 (Domain::APP, 2, "test1"),
4684 (Domain::APP, 2, "test2"),
4685 (Domain::APP, 2, "test3"),
4686 (Domain::APP, 2, "test4"),
4687 (Domain::APP, 2, "test5"),
4688 (Domain::APP, 2, "test6"),
4689 (Domain::APP, 2, "test8"),
4690 (Domain::SELINUX, 100, "test1"),
4691 (Domain::SELINUX, 100, "test2"),
4692 (Domain::SELINUX, 100, "test3"),
4693 (Domain::SELINUX, 100, "test4"),
4694 (Domain::SELINUX, 100, "test5"),
4695 (Domain::SELINUX, 100, "test6"),
4696 (Domain::SELINUX, 100, "test9"),
4697 ];
4698
4699 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4700 .iter()
4701 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004702 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4703 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004704 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4705 });
4706 (entry.id(), *ns)
4707 })
4708 .collect();
4709
4710 for (domain, namespace) in
4711 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4712 {
4713 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4714 .iter()
4715 .filter_map(|(domain, ns, alias)| match ns {
4716 ns if *ns == *namespace => Some(KeyDescriptor {
4717 domain: *domain,
4718 nspace: *ns,
4719 alias: Some(alias.to_string()),
4720 blob: None,
4721 }),
4722 _ => None,
4723 })
4724 .collect();
4725 list_o_descriptors.sort();
4726 let mut list_result = db.list(*domain, *namespace)?;
4727 list_result.sort();
4728 assert_eq!(list_o_descriptors, list_result);
4729
4730 let mut list_o_ids: Vec<i64> = list_o_descriptors
4731 .into_iter()
4732 .map(|d| {
4733 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004734 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004735 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004736 KeyType::Client,
4737 KeyEntryLoadBits::NONE,
4738 *namespace as u32,
4739 |_, _| Ok(()),
4740 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004741 .unwrap();
4742 entry.id()
4743 })
4744 .collect();
4745 list_o_ids.sort_unstable();
4746 let mut loaded_entries: Vec<i64> = list_o_keys
4747 .iter()
4748 .filter_map(|(id, ns)| match ns {
4749 ns if *ns == *namespace => Some(*id),
4750 _ => None,
4751 })
4752 .collect();
4753 loaded_entries.sort_unstable();
4754 assert_eq!(list_o_ids, loaded_entries);
4755 }
4756 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4757
4758 Ok(())
4759 }
4760
Joel Galenson0891bc12020-07-20 10:37:03 -07004761 // Helpers
4762
4763 // Checks that the given result is an error containing the given string.
4764 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4765 let error_str = format!(
4766 "{:#?}",
4767 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4768 );
4769 assert!(
4770 error_str.contains(target),
4771 "The string \"{}\" should contain \"{}\"",
4772 error_str,
4773 target
4774 );
4775 }
4776
Joel Galenson2aab4432020-07-22 15:27:57 -07004777 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004778 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004779 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004780 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004781 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004782 namespace: Option<i64>,
4783 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004784 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004785 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004786 }
4787
4788 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4789 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004790 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004791 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004792 Ok(KeyEntryRow {
4793 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004794 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004795 domain: match row.get(2)? {
4796 Some(i) => Some(Domain(i)),
4797 None => None,
4798 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004799 namespace: row.get(3)?,
4800 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004801 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004802 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004803 })
4804 })?
4805 .map(|r| r.context("Could not read keyentry row."))
4806 .collect::<Result<Vec<_>>>()
4807 }
4808
Max Biresb2e1d032021-02-08 21:35:05 -08004809 struct RemoteProvValues {
4810 cert_chain: Vec<u8>,
4811 priv_key: Vec<u8>,
4812 batch_cert: Vec<u8>,
4813 }
4814
Max Bires2b2e6562020-09-22 11:22:36 -07004815 fn load_attestation_key_pool(
4816 db: &mut KeystoreDB,
4817 expiration_date: i64,
4818 namespace: i64,
4819 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004820 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004821 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4822 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4823 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4824 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004825 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004826 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4827 db.store_signed_attestation_certificate_chain(
4828 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004829 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004830 &cert_chain,
4831 expiration_date,
4832 &KEYSTORE_UUID,
4833 )?;
4834 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004835 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004836 }
4837
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004838 // Note: The parameters and SecurityLevel associations are nonsensical. This
4839 // collection is only used to check if the parameters are preserved as expected by the
4840 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004841 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4842 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004843 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4844 KeyParameter::new(
4845 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4846 SecurityLevel::TRUSTED_ENVIRONMENT,
4847 ),
4848 KeyParameter::new(
4849 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4850 SecurityLevel::TRUSTED_ENVIRONMENT,
4851 ),
4852 KeyParameter::new(
4853 KeyParameterValue::Algorithm(Algorithm::RSA),
4854 SecurityLevel::TRUSTED_ENVIRONMENT,
4855 ),
4856 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4857 KeyParameter::new(
4858 KeyParameterValue::BlockMode(BlockMode::ECB),
4859 SecurityLevel::TRUSTED_ENVIRONMENT,
4860 ),
4861 KeyParameter::new(
4862 KeyParameterValue::BlockMode(BlockMode::GCM),
4863 SecurityLevel::TRUSTED_ENVIRONMENT,
4864 ),
4865 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4866 KeyParameter::new(
4867 KeyParameterValue::Digest(Digest::MD5),
4868 SecurityLevel::TRUSTED_ENVIRONMENT,
4869 ),
4870 KeyParameter::new(
4871 KeyParameterValue::Digest(Digest::SHA_2_224),
4872 SecurityLevel::TRUSTED_ENVIRONMENT,
4873 ),
4874 KeyParameter::new(
4875 KeyParameterValue::Digest(Digest::SHA_2_256),
4876 SecurityLevel::STRONGBOX,
4877 ),
4878 KeyParameter::new(
4879 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4880 SecurityLevel::TRUSTED_ENVIRONMENT,
4881 ),
4882 KeyParameter::new(
4883 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4884 SecurityLevel::TRUSTED_ENVIRONMENT,
4885 ),
4886 KeyParameter::new(
4887 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4888 SecurityLevel::STRONGBOX,
4889 ),
4890 KeyParameter::new(
4891 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4892 SecurityLevel::TRUSTED_ENVIRONMENT,
4893 ),
4894 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4895 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4896 KeyParameter::new(
4897 KeyParameterValue::EcCurve(EcCurve::P_224),
4898 SecurityLevel::TRUSTED_ENVIRONMENT,
4899 ),
4900 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4901 KeyParameter::new(
4902 KeyParameterValue::EcCurve(EcCurve::P_384),
4903 SecurityLevel::TRUSTED_ENVIRONMENT,
4904 ),
4905 KeyParameter::new(
4906 KeyParameterValue::EcCurve(EcCurve::P_521),
4907 SecurityLevel::TRUSTED_ENVIRONMENT,
4908 ),
4909 KeyParameter::new(
4910 KeyParameterValue::RSAPublicExponent(3),
4911 SecurityLevel::TRUSTED_ENVIRONMENT,
4912 ),
4913 KeyParameter::new(
4914 KeyParameterValue::IncludeUniqueID,
4915 SecurityLevel::TRUSTED_ENVIRONMENT,
4916 ),
4917 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4918 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4919 KeyParameter::new(
4920 KeyParameterValue::ActiveDateTime(1234567890),
4921 SecurityLevel::STRONGBOX,
4922 ),
4923 KeyParameter::new(
4924 KeyParameterValue::OriginationExpireDateTime(1234567890),
4925 SecurityLevel::TRUSTED_ENVIRONMENT,
4926 ),
4927 KeyParameter::new(
4928 KeyParameterValue::UsageExpireDateTime(1234567890),
4929 SecurityLevel::TRUSTED_ENVIRONMENT,
4930 ),
4931 KeyParameter::new(
4932 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4933 SecurityLevel::TRUSTED_ENVIRONMENT,
4934 ),
4935 KeyParameter::new(
4936 KeyParameterValue::MaxUsesPerBoot(1234567890),
4937 SecurityLevel::TRUSTED_ENVIRONMENT,
4938 ),
4939 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4940 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4941 KeyParameter::new(
4942 KeyParameterValue::NoAuthRequired,
4943 SecurityLevel::TRUSTED_ENVIRONMENT,
4944 ),
4945 KeyParameter::new(
4946 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4947 SecurityLevel::TRUSTED_ENVIRONMENT,
4948 ),
4949 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4950 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4951 KeyParameter::new(
4952 KeyParameterValue::TrustedUserPresenceRequired,
4953 SecurityLevel::TRUSTED_ENVIRONMENT,
4954 ),
4955 KeyParameter::new(
4956 KeyParameterValue::TrustedConfirmationRequired,
4957 SecurityLevel::TRUSTED_ENVIRONMENT,
4958 ),
4959 KeyParameter::new(
4960 KeyParameterValue::UnlockedDeviceRequired,
4961 SecurityLevel::TRUSTED_ENVIRONMENT,
4962 ),
4963 KeyParameter::new(
4964 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4965 SecurityLevel::SOFTWARE,
4966 ),
4967 KeyParameter::new(
4968 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4969 SecurityLevel::SOFTWARE,
4970 ),
4971 KeyParameter::new(
4972 KeyParameterValue::CreationDateTime(12345677890),
4973 SecurityLevel::SOFTWARE,
4974 ),
4975 KeyParameter::new(
4976 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4977 SecurityLevel::TRUSTED_ENVIRONMENT,
4978 ),
4979 KeyParameter::new(
4980 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4981 SecurityLevel::TRUSTED_ENVIRONMENT,
4982 ),
4983 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4984 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4985 KeyParameter::new(
4986 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4987 SecurityLevel::SOFTWARE,
4988 ),
4989 KeyParameter::new(
4990 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4991 SecurityLevel::TRUSTED_ENVIRONMENT,
4992 ),
4993 KeyParameter::new(
4994 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4995 SecurityLevel::TRUSTED_ENVIRONMENT,
4996 ),
4997 KeyParameter::new(
4998 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4999 SecurityLevel::TRUSTED_ENVIRONMENT,
5000 ),
5001 KeyParameter::new(
5002 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5003 SecurityLevel::TRUSTED_ENVIRONMENT,
5004 ),
5005 KeyParameter::new(
5006 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5007 SecurityLevel::TRUSTED_ENVIRONMENT,
5008 ),
5009 KeyParameter::new(
5010 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5011 SecurityLevel::TRUSTED_ENVIRONMENT,
5012 ),
5013 KeyParameter::new(
5014 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5015 SecurityLevel::TRUSTED_ENVIRONMENT,
5016 ),
5017 KeyParameter::new(
5018 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5019 SecurityLevel::TRUSTED_ENVIRONMENT,
5020 ),
5021 KeyParameter::new(
5022 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5023 SecurityLevel::TRUSTED_ENVIRONMENT,
5024 ),
5025 KeyParameter::new(
5026 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5027 SecurityLevel::TRUSTED_ENVIRONMENT,
5028 ),
5029 KeyParameter::new(
5030 KeyParameterValue::VendorPatchLevel(3),
5031 SecurityLevel::TRUSTED_ENVIRONMENT,
5032 ),
5033 KeyParameter::new(
5034 KeyParameterValue::BootPatchLevel(4),
5035 SecurityLevel::TRUSTED_ENVIRONMENT,
5036 ),
5037 KeyParameter::new(
5038 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5039 SecurityLevel::TRUSTED_ENVIRONMENT,
5040 ),
5041 KeyParameter::new(
5042 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5043 SecurityLevel::TRUSTED_ENVIRONMENT,
5044 ),
5045 KeyParameter::new(
5046 KeyParameterValue::MacLength(256),
5047 SecurityLevel::TRUSTED_ENVIRONMENT,
5048 ),
5049 KeyParameter::new(
5050 KeyParameterValue::ResetSinceIdRotation,
5051 SecurityLevel::TRUSTED_ENVIRONMENT,
5052 ),
5053 KeyParameter::new(
5054 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5055 SecurityLevel::TRUSTED_ENVIRONMENT,
5056 ),
Qi Wub9433b52020-12-01 14:52:46 +08005057 ];
5058 if let Some(value) = max_usage_count {
5059 params.push(KeyParameter::new(
5060 KeyParameterValue::UsageCountLimit(value),
5061 SecurityLevel::SOFTWARE,
5062 ));
5063 }
5064 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005065 }
5066
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005067 fn make_test_key_entry(
5068 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005069 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005070 namespace: i64,
5071 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005072 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005073 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005074 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005075 let mut blob_metadata = BlobMetaData::new();
5076 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5077 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5078 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5079 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5080 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5081
5082 db.set_blob(
5083 &key_id,
5084 SubComponentType::KEY_BLOB,
5085 Some(TEST_KEY_BLOB),
5086 Some(&blob_metadata),
5087 )?;
5088 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5089 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005090
5091 let params = make_test_params(max_usage_count);
5092 db.insert_keyparameter(&key_id, &params)?;
5093
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005094 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005095 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005096 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005097 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005098 Ok(key_id)
5099 }
5100
Qi Wub9433b52020-12-01 14:52:46 +08005101 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5102 let params = make_test_params(max_usage_count);
5103
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005104 let mut blob_metadata = BlobMetaData::new();
5105 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5106 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5107 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5108 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5109 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5110
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005111 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005112 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005113
5114 KeyEntry {
5115 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005116 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005117 cert: Some(TEST_CERT_BLOB.to_vec()),
5118 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005119 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005120 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005121 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005122 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005123 }
5124 }
5125
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005126 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005127 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005128 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005129 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005130 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005131 NO_PARAMS,
5132 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005133 Ok((
5134 row.get(0)?,
5135 row.get(1)?,
5136 row.get(2)?,
5137 row.get(3)?,
5138 row.get(4)?,
5139 row.get(5)?,
5140 row.get(6)?,
5141 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005142 },
5143 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005144
5145 println!("Key entry table rows:");
5146 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005147 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005148 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005149 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5150 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005151 );
5152 }
5153 Ok(())
5154 }
5155
5156 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005157 let mut stmt = db
5158 .conn
5159 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005160 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5161 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5162 })?;
5163
5164 println!("Grant table rows:");
5165 for r in rows {
5166 let (id, gt, ki, av) = r.unwrap();
5167 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5168 }
5169 Ok(())
5170 }
5171
Joel Galenson0891bc12020-07-20 10:37:03 -07005172 // Use a custom random number generator that repeats each number once.
5173 // This allows us to test repeated elements.
5174
5175 thread_local! {
5176 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5177 }
5178
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005179 fn reset_random() {
5180 RANDOM_COUNTER.with(|counter| {
5181 *counter.borrow_mut() = 0;
5182 })
5183 }
5184
Joel Galenson0891bc12020-07-20 10:37:03 -07005185 pub fn random() -> i64 {
5186 RANDOM_COUNTER.with(|counter| {
5187 let result = *counter.borrow() / 2;
5188 *counter.borrow_mut() += 1;
5189 result
5190 })
5191 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005192
5193 #[test]
5194 fn test_last_off_body() -> Result<()> {
5195 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005196 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005197 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005198 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005199 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005200 let one_second = Duration::from_secs(1);
5201 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005202 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005203 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005204 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005205 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005206 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005207 Ok(())
5208 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005209
5210 #[test]
5211 fn test_unbind_keys_for_user() -> Result<()> {
5212 let mut db = new_test_db()?;
5213 db.unbind_keys_for_user(1, false)?;
5214
5215 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5216 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5217 db.unbind_keys_for_user(2, false)?;
5218
5219 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5220 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5221
5222 db.unbind_keys_for_user(1, true)?;
5223 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5224
5225 Ok(())
5226 }
5227
5228 #[test]
5229 fn test_store_super_key() -> Result<()> {
5230 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005231 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005232 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005233 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005234 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005235 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005236
5237 let (encrypted_super_key, metadata) =
5238 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005239 db.store_super_key(
5240 1,
5241 &USER_SUPER_KEY,
5242 &encrypted_super_key,
5243 &metadata,
5244 &KeyMetaData::new(),
5245 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005246
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005247 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005248 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005249
Paul Crowley7a658392021-03-18 17:08:20 -07005250 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005251 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5252 USER_SUPER_KEY.algorithm,
5253 key_entry,
5254 &pw,
5255 None,
5256 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005257
Paul Crowley7a658392021-03-18 17:08:20 -07005258 let decrypted_secret_bytes =
5259 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5260 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005261 Ok(())
5262 }
Seth Moore78c091f2021-04-09 21:38:30 +00005263
5264 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5265 vec![
5266 StatsdStorageType::KeyEntry,
5267 StatsdStorageType::KeyEntryIdIndex,
5268 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5269 StatsdStorageType::BlobEntry,
5270 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5271 StatsdStorageType::KeyParameter,
5272 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5273 StatsdStorageType::KeyMetadata,
5274 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5275 StatsdStorageType::Grant,
5276 StatsdStorageType::AuthToken,
5277 StatsdStorageType::BlobMetadata,
5278 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5279 ]
5280 }
5281
5282 /// Perform a simple check to ensure that we can query all the storage types
5283 /// that are supported by the DB. Check for reasonable values.
5284 #[test]
5285 fn test_query_all_valid_table_sizes() -> Result<()> {
5286 const PAGE_SIZE: i64 = 4096;
5287
5288 let mut db = new_test_db()?;
5289
5290 for t in get_valid_statsd_storage_types() {
5291 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005292 // AuthToken can be less than a page since it's in a btree, not sqlite
5293 // TODO(b/187474736) stop using if-let here
5294 if let StatsdStorageType::AuthToken = t {
5295 } else {
5296 assert!(stat.size >= PAGE_SIZE);
5297 }
Seth Moore78c091f2021-04-09 21:38:30 +00005298 assert!(stat.size >= stat.unused_size);
5299 }
5300
5301 Ok(())
5302 }
5303
5304 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5305 get_valid_statsd_storage_types()
5306 .into_iter()
5307 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5308 .collect()
5309 }
5310
5311 fn assert_storage_increased(
5312 db: &mut KeystoreDB,
5313 increased_storage_types: Vec<StatsdStorageType>,
5314 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5315 ) {
5316 for storage in increased_storage_types {
5317 // Verify the expected storage increased.
5318 let new = db.get_storage_stat(storage).unwrap();
5319 let storage = storage as i32;
5320 let old = &baseline[&storage];
5321 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5322 assert!(
5323 new.unused_size <= old.unused_size,
5324 "{}: {} <= {}",
5325 storage,
5326 new.unused_size,
5327 old.unused_size
5328 );
5329
5330 // Update the baseline with the new value so that it succeeds in the
5331 // later comparison.
5332 baseline.insert(storage, new);
5333 }
5334
5335 // Get an updated map of the storage and verify there were no unexpected changes.
5336 let updated_stats = get_storage_stats_map(db);
5337 assert_eq!(updated_stats.len(), baseline.len());
5338
5339 for &k in baseline.keys() {
5340 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5341 let mut s = String::new();
5342 for &k in map.keys() {
5343 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5344 .expect("string concat failed");
5345 }
5346 s
5347 };
5348
5349 assert!(
5350 updated_stats[&k].size == baseline[&k].size
5351 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5352 "updated_stats:\n{}\nbaseline:\n{}",
5353 stringify(&updated_stats),
5354 stringify(&baseline)
5355 );
5356 }
5357 }
5358
5359 #[test]
5360 fn test_verify_key_table_size_reporting() -> Result<()> {
5361 let mut db = new_test_db()?;
5362 let mut working_stats = get_storage_stats_map(&mut db);
5363
5364 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5365 assert_storage_increased(
5366 &mut db,
5367 vec![
5368 StatsdStorageType::KeyEntry,
5369 StatsdStorageType::KeyEntryIdIndex,
5370 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5371 ],
5372 &mut working_stats,
5373 );
5374
5375 let mut blob_metadata = BlobMetaData::new();
5376 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5377 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5378 assert_storage_increased(
5379 &mut db,
5380 vec![
5381 StatsdStorageType::BlobEntry,
5382 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5383 StatsdStorageType::BlobMetadata,
5384 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5385 ],
5386 &mut working_stats,
5387 );
5388
5389 let params = make_test_params(None);
5390 db.insert_keyparameter(&key_id, &params)?;
5391 assert_storage_increased(
5392 &mut db,
5393 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5394 &mut working_stats,
5395 );
5396
5397 let mut metadata = KeyMetaData::new();
5398 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5399 db.insert_key_metadata(&key_id, &metadata)?;
5400 assert_storage_increased(
5401 &mut db,
5402 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5403 &mut working_stats,
5404 );
5405
5406 let mut sum = 0;
5407 for stat in working_stats.values() {
5408 sum += stat.size;
5409 }
5410 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5411 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5412
5413 Ok(())
5414 }
5415
5416 #[test]
5417 fn test_verify_auth_table_size_reporting() -> Result<()> {
5418 let mut db = new_test_db()?;
5419 let mut working_stats = get_storage_stats_map(&mut db);
5420 db.insert_auth_token(&HardwareAuthToken {
5421 challenge: 123,
5422 userId: 456,
5423 authenticatorId: 789,
5424 authenticatorType: kmhw_authenticator_type::ANY,
5425 timestamp: Timestamp { milliSeconds: 10 },
5426 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005427 });
Seth Moore78c091f2021-04-09 21:38:30 +00005428 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5429 Ok(())
5430 }
5431
5432 #[test]
5433 fn test_verify_grant_table_size_reporting() -> Result<()> {
5434 const OWNER: i64 = 1;
5435 let mut db = new_test_db()?;
5436 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5437
5438 let mut working_stats = get_storage_stats_map(&mut db);
5439 db.grant(
5440 &KeyDescriptor {
5441 domain: Domain::APP,
5442 nspace: 0,
5443 alias: Some(TEST_ALIAS.to_string()),
5444 blob: None,
5445 },
5446 OWNER as u32,
5447 123,
5448 key_perm_set![KeyPerm::use_()],
5449 |_, _| Ok(()),
5450 )?;
5451
5452 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5453
5454 Ok(())
5455 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005456
5457 #[test]
5458 fn find_auth_token_entry_returns_latest() -> Result<()> {
5459 let mut db = new_test_db()?;
5460 db.insert_auth_token(&HardwareAuthToken {
5461 challenge: 123,
5462 userId: 456,
5463 authenticatorId: 789,
5464 authenticatorType: kmhw_authenticator_type::ANY,
5465 timestamp: Timestamp { milliSeconds: 10 },
5466 mac: b"mac0".to_vec(),
5467 });
5468 std::thread::sleep(std::time::Duration::from_millis(1));
5469 db.insert_auth_token(&HardwareAuthToken {
5470 challenge: 123,
5471 userId: 457,
5472 authenticatorId: 789,
5473 authenticatorType: kmhw_authenticator_type::ANY,
5474 timestamp: Timestamp { milliSeconds: 12 },
5475 mac: b"mac1".to_vec(),
5476 });
5477 std::thread::sleep(std::time::Duration::from_millis(1));
5478 db.insert_auth_token(&HardwareAuthToken {
5479 challenge: 123,
5480 userId: 458,
5481 authenticatorId: 789,
5482 authenticatorType: kmhw_authenticator_type::ANY,
5483 timestamp: Timestamp { milliSeconds: 3 },
5484 mac: b"mac2".to_vec(),
5485 });
5486 // All three entries are in the database
5487 assert_eq!(db.perboot.auth_tokens_len(), 3);
5488 // It selected the most recent timestamp
5489 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5490 Ok(())
5491 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005492
5493 #[test]
5494 fn test_set_wal_mode() -> Result<()> {
5495 let temp_dir = TempDir::new("test_set_wal_mode")?;
5496 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5497 let mode: String =
5498 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5499 row.get(0)
5500 })?;
5501 assert_eq!(mode, "delete");
5502 db.conn.close().expect("Close didn't work");
5503
5504 KeystoreDB::set_wal_mode(temp_dir.path())?;
5505
5506 db = KeystoreDB::new(temp_dir.path(), None)?;
5507 let mode: String =
5508 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5509 row.get(0)
5510 })?;
5511 assert_eq!(mode, "wal");
5512 Ok(())
5513 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005514}