blob: 29301624d67747c71410b2c387c7c5be69eeb27f [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.
Janis Danisevskis18313832021-05-17 13:30:32 -07002970 pub fn list(
2971 &mut self,
2972 domain: Domain,
2973 namespace: i64,
2974 key_type: KeyType,
2975 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002976 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2977
Janis Danisevskis66784c42021-01-27 08:40:25 -08002978 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2979 let mut stmt = tx
2980 .prepare(
2981 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002982 WHERE domain = ?
2983 AND namespace = ?
2984 AND alias IS NOT NULL
2985 AND state = ?
2986 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002987 )
2988 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002989
Janis Danisevskis66784c42021-01-27 08:40:25 -08002990 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07002991 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08002992 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002993
Janis Danisevskis66784c42021-01-27 08:40:25 -08002994 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2995 db_utils::with_rows_extract_all(&mut rows, |row| {
2996 descriptors.push(KeyDescriptor {
2997 domain,
2998 nspace: namespace,
2999 alias: Some(row.get(0).context("Trying to extract alias.")?),
3000 blob: None,
3001 });
3002 Ok(())
3003 })
3004 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003005 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003006 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003007 }
3008
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003009 /// Adds a grant to the grant table.
3010 /// Like `load_key_entry` this function loads the access tuple before
3011 /// it uses the callback for a permission check. Upon success,
3012 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3013 /// grant table. The new row will have a randomized id, which is used as
3014 /// grant id in the namespace field of the resulting KeyDescriptor.
3015 pub fn grant(
3016 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003017 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003018 caller_uid: u32,
3019 grantee_uid: u32,
3020 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003021 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003022 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003023 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3024
Janis Danisevskis66784c42021-01-27 08:40:25 -08003025 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3026 // Load the key_id and complete the access control tuple.
3027 // We ignore the access vector here because grants cannot be granted.
3028 // The access vector returned here expresses the permissions the
3029 // grantee has if key.domain == Domain::GRANT. But this vector
3030 // cannot include the grant permission by design, so there is no way the
3031 // subsequent permission check can pass.
3032 // We could check key.domain == Domain::GRANT and fail early.
3033 // But even if we load the access tuple by grant here, the permission
3034 // check denies the attempt to create a grant by grant descriptor.
3035 let (key_id, access_key_descriptor, _) =
3036 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3037 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003038
Janis Danisevskis66784c42021-01-27 08:40:25 -08003039 // Perform access control. It is vital that we return here if the permission
3040 // was denied. So do not touch that '?' at the end of the line.
3041 // This permission check checks if the caller has the grant permission
3042 // for the given key and in addition to all of the permissions
3043 // expressed in `access_vector`.
3044 check_permission(&access_key_descriptor, &access_vector)
3045 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003046
Janis Danisevskis66784c42021-01-27 08:40:25 -08003047 let grant_id = if let Some(grant_id) = tx
3048 .query_row(
3049 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003050 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003051 params![key_id, grantee_uid],
3052 |row| row.get(0),
3053 )
3054 .optional()
3055 .context("In grant: Failed get optional existing grant id.")?
3056 {
3057 tx.execute(
3058 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003059 SET access_vector = ?
3060 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003061 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003062 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003063 .context("In grant: Failed to update existing grant.")?;
3064 grant_id
3065 } else {
3066 Self::insert_with_retry(|id| {
3067 tx.execute(
3068 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3069 VALUES (?, ?, ?, ?);",
3070 params![id, grantee_uid, key_id, i32::from(access_vector)],
3071 )
3072 })
3073 .context("In grant")?
3074 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003075
Janis Danisevskis66784c42021-01-27 08:40:25 -08003076 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003077 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003079 }
3080
3081 /// This function checks permissions like `grant` and `load_key_entry`
3082 /// before removing a grant from the grant table.
3083 pub fn ungrant(
3084 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003085 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003086 caller_uid: u32,
3087 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003088 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003089 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003090 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3091
Janis Danisevskis66784c42021-01-27 08:40:25 -08003092 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3093 // Load the key_id and complete the access control tuple.
3094 // We ignore the access vector here because grants cannot be granted.
3095 let (key_id, access_key_descriptor, _) =
3096 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3097 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003098
Janis Danisevskis66784c42021-01-27 08:40:25 -08003099 // Perform access control. We must return here if the permission
3100 // was denied. So do not touch the '?' at the end of this line.
3101 check_permission(&access_key_descriptor)
3102 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003103
Janis Danisevskis66784c42021-01-27 08:40:25 -08003104 tx.execute(
3105 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003106 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003107 params![key_id, grantee_uid],
3108 )
3109 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003110
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003111 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003112 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003113 }
3114
Joel Galenson845f74b2020-09-09 14:11:55 -07003115 // Generates a random id and passes it to the given function, which will
3116 // try to insert it into a database. If that insertion fails, retry;
3117 // otherwise return the id.
3118 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3119 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003120 let newid: i64 = match random() {
3121 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3122 i => i,
3123 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003124 match inserter(newid) {
3125 // If the id already existed, try again.
3126 Err(rusqlite::Error::SqliteFailure(
3127 libsqlite3_sys::Error {
3128 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3129 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3130 },
3131 _,
3132 )) => (),
3133 Err(e) => {
3134 return Err(e).context("In insert_with_retry: failed to insert into database.")
3135 }
3136 _ => return Ok(newid),
3137 }
3138 }
3139 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003140
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003141 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3142 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3143 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3144 auth_token.clone(),
3145 MonotonicRawTime::now(),
3146 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003147 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003148
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003149 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003150 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003151 where
3152 F: Fn(&AuthTokenEntry) -> bool,
3153 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003154 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003155 }
3156
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003157 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003158 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3159 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003160 }
3161
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003162 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003163 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3164 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003165 }
3166
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003167 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003168 fn get_last_off_body(&self) -> MonotonicRawTime {
3169 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003170 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003171
3172 /// Load descriptor of a key by key id
3173 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3174 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3175
3176 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3177 tx.query_row(
3178 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3179 params![key_id],
3180 |row| {
3181 Ok(KeyDescriptor {
3182 domain: Domain(row.get(0)?),
3183 nspace: row.get(1)?,
3184 alias: row.get(2)?,
3185 blob: None,
3186 })
3187 },
3188 )
3189 .optional()
3190 .context("Trying to load key descriptor")
3191 .no_gc()
3192 })
3193 .context("In load_key_descriptor.")
3194 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003195}
3196
3197#[cfg(test)]
3198mod tests {
3199
3200 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003201 use crate::key_parameter::{
3202 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3203 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3204 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003205 use crate::key_perm_set;
3206 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003207 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003208 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003209 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3210 HardwareAuthToken::HardwareAuthToken,
3211 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003212 };
3213 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003214 Timestamp::Timestamp,
3215 };
Seth Moore472fcbb2021-05-12 10:07:51 -07003216 use rusqlite::DatabaseName::Attached;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003217 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003218 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003219 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003220 use std::collections::BTreeMap;
3221 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003222 use std::sync::atomic::{AtomicU8, Ordering};
3223 use std::sync::Arc;
3224 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003225 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003226 #[cfg(disabled)]
3227 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003228
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003229 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003230 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003231
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003232 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003233 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003234 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003235 })?;
3236 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003237 }
3238
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003239 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3240 where
3241 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3242 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003243 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003244
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003245 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003246 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003247
Janis Danisevskis3395f862021-05-06 10:54:17 -07003248 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003249 }
3250
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003251 fn rebind_alias(
3252 db: &mut KeystoreDB,
3253 newid: &KeyIdGuard,
3254 alias: &str,
3255 domain: Domain,
3256 namespace: i64,
3257 ) -> Result<bool> {
3258 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003259 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003260 })
3261 .context("In rebind_alias.")
3262 }
3263
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003264 #[test]
3265 fn datetime() -> Result<()> {
3266 let conn = Connection::open_in_memory()?;
3267 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3268 let now = SystemTime::now();
3269 let duration = Duration::from_secs(1000);
3270 let then = now.checked_sub(duration).unwrap();
3271 let soon = now.checked_add(duration).unwrap();
3272 conn.execute(
3273 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3274 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3275 )?;
3276 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3277 let mut rows = stmt.query(NO_PARAMS)?;
3278 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3279 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3280 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3281 assert!(rows.next()?.is_none());
3282 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3283 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3284 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3285 Ok(())
3286 }
3287
Joel Galenson0891bc12020-07-20 10:37:03 -07003288 // Ensure that we're using the "injected" random function, not the real one.
3289 #[test]
3290 fn test_mocked_random() {
3291 let rand1 = random();
3292 let rand2 = random();
3293 let rand3 = random();
3294 if rand1 == rand2 {
3295 assert_eq!(rand2 + 1, rand3);
3296 } else {
3297 assert_eq!(rand1 + 1, rand2);
3298 assert_eq!(rand2, rand3);
3299 }
3300 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003301
Joel Galenson26f4d012020-07-17 14:57:21 -07003302 // Test that we have the correct tables.
3303 #[test]
3304 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003305 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003306 let tables = db
3307 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003308 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003309 .query_map(params![], |row| row.get(0))?
3310 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003311 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003312 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003313 assert_eq!(tables[1], "blobmetadata");
3314 assert_eq!(tables[2], "grant");
3315 assert_eq!(tables[3], "keyentry");
3316 assert_eq!(tables[4], "keymetadata");
3317 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003318 Ok(())
3319 }
3320
3321 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003322 fn test_auth_token_table_invariant() -> Result<()> {
3323 let mut db = new_test_db()?;
3324 let auth_token1 = HardwareAuthToken {
3325 challenge: i64::MAX,
3326 userId: 200,
3327 authenticatorId: 200,
3328 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3329 timestamp: Timestamp { milliSeconds: 500 },
3330 mac: String::from("mac").into_bytes(),
3331 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003332 db.insert_auth_token(&auth_token1);
3333 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003334 assert_eq!(auth_tokens_returned.len(), 1);
3335
3336 // insert another auth token with the same values for the columns in the UNIQUE constraint
3337 // of the auth token table and different value for timestamp
3338 let auth_token2 = HardwareAuthToken {
3339 challenge: i64::MAX,
3340 userId: 200,
3341 authenticatorId: 200,
3342 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3343 timestamp: Timestamp { milliSeconds: 600 },
3344 mac: String::from("mac").into_bytes(),
3345 };
3346
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003347 db.insert_auth_token(&auth_token2);
3348 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003349 assert_eq!(auth_tokens_returned.len(), 1);
3350
3351 if let Some(auth_token) = auth_tokens_returned.pop() {
3352 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3353 }
3354
3355 // insert another auth token with the different values for the columns in the UNIQUE
3356 // constraint of the auth token table
3357 let auth_token3 = HardwareAuthToken {
3358 challenge: i64::MAX,
3359 userId: 201,
3360 authenticatorId: 200,
3361 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3362 timestamp: Timestamp { milliSeconds: 600 },
3363 mac: String::from("mac").into_bytes(),
3364 };
3365
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003366 db.insert_auth_token(&auth_token3);
3367 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003368 assert_eq!(auth_tokens_returned.len(), 2);
3369
3370 Ok(())
3371 }
3372
3373 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003374 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3375 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003376 }
3377
3378 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003379 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003380 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003381 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003382
Janis Danisevskis66784c42021-01-27 08:40:25 -08003383 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003384 let entries = get_keyentry(&db)?;
3385 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003386
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003387 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003388
3389 let entries_new = get_keyentry(&db)?;
3390 assert_eq!(entries, entries_new);
3391 Ok(())
3392 }
3393
3394 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003395 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003396 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3397 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003398 }
3399
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003400 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003401
Janis Danisevskis66784c42021-01-27 08:40:25 -08003402 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3403 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003404
3405 let entries = get_keyentry(&db)?;
3406 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003407 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3408 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003409
3410 // Test that we must pass in a valid Domain.
3411 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003412 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003413 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003414 );
3415 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003416 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003417 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003418 );
3419 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003420 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003421 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003422 );
3423
3424 Ok(())
3425 }
3426
Joel Galenson33c04ad2020-08-03 11:04:38 -07003427 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003428 fn test_add_unsigned_key() -> Result<()> {
3429 let mut db = new_test_db()?;
3430 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3431 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3432 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3433 db.create_attestation_key_entry(
3434 &public_key,
3435 &raw_public_key,
3436 &private_key,
3437 &KEYSTORE_UUID,
3438 )?;
3439 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3440 assert_eq!(keys.len(), 1);
3441 assert_eq!(keys[0], public_key);
3442 Ok(())
3443 }
3444
3445 #[test]
3446 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3447 let mut db = new_test_db()?;
3448 let expiration_date: i64 = 20;
3449 let namespace: i64 = 30;
3450 let base_byte: u8 = 1;
3451 let loaded_values =
3452 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3453 let chain =
3454 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3455 assert_eq!(true, chain.is_some());
3456 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003457 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003458 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3459 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003460 Ok(())
3461 }
3462
3463 #[test]
3464 fn test_get_attestation_pool_status() -> Result<()> {
3465 let mut db = new_test_db()?;
3466 let namespace: i64 = 30;
3467 load_attestation_key_pool(
3468 &mut db, 10, /* expiration */
3469 namespace, 0x01, /* base_byte */
3470 )?;
3471 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3472 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3473 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3474 assert_eq!(status.expiring, 0);
3475 assert_eq!(status.attested, 3);
3476 assert_eq!(status.unassigned, 0);
3477 assert_eq!(status.total, 3);
3478 assert_eq!(
3479 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3480 1
3481 );
3482 assert_eq!(
3483 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3484 2
3485 );
3486 assert_eq!(
3487 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3488 3
3489 );
3490 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3491 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3492 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3493 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003494 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003495 db.create_attestation_key_entry(
3496 &public_key,
3497 &raw_public_key,
3498 &private_key,
3499 &KEYSTORE_UUID,
3500 )?;
3501 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3502 assert_eq!(status.attested, 3);
3503 assert_eq!(status.unassigned, 0);
3504 assert_eq!(status.total, 4);
3505 db.store_signed_attestation_certificate_chain(
3506 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003507 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003508 &cert_chain,
3509 20,
3510 &KEYSTORE_UUID,
3511 )?;
3512 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3513 assert_eq!(status.attested, 4);
3514 assert_eq!(status.unassigned, 1);
3515 assert_eq!(status.total, 4);
3516 Ok(())
3517 }
3518
3519 #[test]
3520 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003521 let temp_dir =
3522 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3523 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003524 let expiration_date: i64 =
3525 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3526 let namespace: i64 = 30;
3527 let namespace_del1: i64 = 45;
3528 let namespace_del2: i64 = 60;
3529 let entry_values = load_attestation_key_pool(
3530 &mut db,
3531 expiration_date,
3532 namespace,
3533 0x01, /* base_byte */
3534 )?;
3535 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3536 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003537
3538 let blob_entry_row_count: u32 = db
3539 .conn
3540 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3541 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003542 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3543 // one key, one certificate chain, and one certificate.
3544 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003545
Max Bires2b2e6562020-09-22 11:22:36 -07003546 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3547
3548 let mut cert_chain =
3549 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003550 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003551 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003552 assert_eq!(entry_values.batch_cert, value.batch_cert);
3553 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003554 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003555
3556 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3557 Domain::APP,
3558 namespace_del1,
3559 &KEYSTORE_UUID,
3560 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003561 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003562 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3563 Domain::APP,
3564 namespace_del2,
3565 &KEYSTORE_UUID,
3566 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003567 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003568
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003569 // Give the garbage collector half a second to catch up.
3570 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003571
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003572 let blob_entry_row_count: u32 = db
3573 .conn
3574 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3575 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003576 // There shound be 3 blob entries left, because we deleted two of the attestation
3577 // key entries with three blobs each.
3578 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003579
Max Bires2b2e6562020-09-22 11:22:36 -07003580 Ok(())
3581 }
3582
3583 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003584 fn test_delete_all_attestation_keys() -> Result<()> {
3585 let mut db = new_test_db()?;
3586 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3587 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3588 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3589 let result = db.delete_all_attestation_keys()?;
3590
3591 // Give the garbage collector half a second to catch up.
3592 std::thread::sleep(Duration::from_millis(500));
3593
3594 // Attestation keys should be deleted, and the regular key should remain.
3595 assert_eq!(result, 2);
3596
3597 Ok(())
3598 }
3599
3600 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003601 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003602 fn extractor(
3603 ke: &KeyEntryRow,
3604 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3605 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003606 }
3607
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003608 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003609 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3610 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003611 let entries = get_keyentry(&db)?;
3612 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003613 assert_eq!(
3614 extractor(&entries[0]),
3615 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3616 );
3617 assert_eq!(
3618 extractor(&entries[1]),
3619 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3620 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003621
3622 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003623 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003624 let entries = get_keyentry(&db)?;
3625 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003626 assert_eq!(
3627 extractor(&entries[0]),
3628 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3629 );
3630 assert_eq!(
3631 extractor(&entries[1]),
3632 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3633 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003634
3635 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003636 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003637 let entries = get_keyentry(&db)?;
3638 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003639 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3640 assert_eq!(
3641 extractor(&entries[1]),
3642 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3643 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003644
3645 // Test that we must pass in a valid Domain.
3646 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003647 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003648 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003649 );
3650 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003651 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003652 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003653 );
3654 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003655 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003656 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003657 );
3658
3659 // Test that we correctly handle setting an alias for something that does not exist.
3660 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003661 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003662 "Expected to update a single entry but instead updated 0",
3663 );
3664 // Test that we correctly abort the transaction in this case.
3665 let entries = get_keyentry(&db)?;
3666 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003667 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3668 assert_eq!(
3669 extractor(&entries[1]),
3670 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3671 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003672
3673 Ok(())
3674 }
3675
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003676 #[test]
3677 fn test_grant_ungrant() -> Result<()> {
3678 const CALLER_UID: u32 = 15;
3679 const GRANTEE_UID: u32 = 12;
3680 const SELINUX_NAMESPACE: i64 = 7;
3681
3682 let mut db = new_test_db()?;
3683 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003684 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3685 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3686 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003687 )?;
3688 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003689 domain: super::Domain::APP,
3690 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003691 alias: Some("key".to_string()),
3692 blob: None,
3693 };
3694 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3695 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3696
3697 // Reset totally predictable random number generator in case we
3698 // are not the first test running on this thread.
3699 reset_random();
3700 let next_random = 0i64;
3701
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003702 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003703 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003704 assert_eq!(*a, PVEC1);
3705 assert_eq!(
3706 *k,
3707 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003708 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003709 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003710 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003711 alias: Some("key".to_string()),
3712 blob: None,
3713 }
3714 );
3715 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003716 })
3717 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003718
3719 assert_eq!(
3720 app_granted_key,
3721 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003722 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003723 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003724 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725 alias: None,
3726 blob: None,
3727 }
3728 );
3729
3730 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003731 domain: super::Domain::SELINUX,
3732 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003733 alias: Some("yek".to_string()),
3734 blob: None,
3735 };
3736
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003737 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003738 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003739 assert_eq!(*a, PVEC1);
3740 assert_eq!(
3741 *k,
3742 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003743 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003744 // namespace must be the supplied SELinux
3745 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003746 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003747 alias: Some("yek".to_string()),
3748 blob: None,
3749 }
3750 );
3751 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003752 })
3753 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754
3755 assert_eq!(
3756 selinux_granted_key,
3757 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003758 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003759 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003760 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003761 alias: None,
3762 blob: None,
3763 }
3764 );
3765
3766 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003767 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003768 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003769 assert_eq!(*a, PVEC2);
3770 assert_eq!(
3771 *k,
3772 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003773 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003774 // namespace must be the supplied SELinux
3775 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003776 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003777 alias: Some("yek".to_string()),
3778 blob: None,
3779 }
3780 );
3781 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003782 })
3783 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003784
3785 assert_eq!(
3786 selinux_granted_key,
3787 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003788 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003789 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003790 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003791 alias: None,
3792 blob: None,
3793 }
3794 );
3795
3796 {
3797 // Limiting scope of stmt, because it borrows db.
3798 let mut stmt = db
3799 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003800 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003801 let mut rows =
3802 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3803 Ok((
3804 row.get(0)?,
3805 row.get(1)?,
3806 row.get(2)?,
3807 KeyPermSet::from(row.get::<_, i32>(3)?),
3808 ))
3809 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003810
3811 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003812 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003813 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003814 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003815 assert!(rows.next().is_none());
3816 }
3817
3818 debug_dump_keyentry_table(&mut db)?;
3819 println!("app_key {:?}", app_key);
3820 println!("selinux_key {:?}", selinux_key);
3821
Janis Danisevskis66784c42021-01-27 08:40:25 -08003822 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3823 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003824
3825 Ok(())
3826 }
3827
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003828 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003829 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3830 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3831
3832 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003833 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003834 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003835 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003836 let mut blob_metadata = BlobMetaData::new();
3837 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3838 db.set_blob(
3839 &key_id,
3840 SubComponentType::KEY_BLOB,
3841 Some(TEST_KEY_BLOB),
3842 Some(&blob_metadata),
3843 )?;
3844 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3845 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003846 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003847
3848 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003849 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003850 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003851 )?;
3852 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003853 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3854 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003855 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003856 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003857 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003858 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003859 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003860 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003861 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003862
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003863 drop(rows);
3864 drop(stmt);
3865
3866 assert_eq!(
3867 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3868 BlobMetaData::load_from_db(id, tx).no_gc()
3869 })
3870 .expect("Should find blob metadata."),
3871 blob_metadata
3872 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003873 Ok(())
3874 }
3875
3876 static TEST_ALIAS: &str = "my super duper key";
3877
3878 #[test]
3879 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3880 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003881 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003882 .context("test_insert_and_load_full_keyentry_domain_app")?
3883 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003884 let (_key_guard, key_entry) = db
3885 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003886 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003887 domain: Domain::APP,
3888 nspace: 0,
3889 alias: Some(TEST_ALIAS.to_string()),
3890 blob: None,
3891 },
3892 KeyType::Client,
3893 KeyEntryLoadBits::BOTH,
3894 1,
3895 |_k, _av| Ok(()),
3896 )
3897 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003898 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003899
3900 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003901 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003902 domain: Domain::APP,
3903 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003904 alias: Some(TEST_ALIAS.to_string()),
3905 blob: None,
3906 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003907 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003908 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003909 |_, _| Ok(()),
3910 )
3911 .unwrap();
3912
3913 assert_eq!(
3914 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3915 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003916 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003917 domain: Domain::APP,
3918 nspace: 0,
3919 alias: Some(TEST_ALIAS.to_string()),
3920 blob: None,
3921 },
3922 KeyType::Client,
3923 KeyEntryLoadBits::NONE,
3924 1,
3925 |_k, _av| Ok(()),
3926 )
3927 .unwrap_err()
3928 .root_cause()
3929 .downcast_ref::<KsError>()
3930 );
3931
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003932 Ok(())
3933 }
3934
3935 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003936 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3937 let mut db = new_test_db()?;
3938
3939 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003940 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003941 domain: Domain::APP,
3942 nspace: 1,
3943 alias: Some(TEST_ALIAS.to_string()),
3944 blob: None,
3945 },
3946 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003947 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003948 )
3949 .expect("Trying to insert cert.");
3950
3951 let (_key_guard, mut key_entry) = db
3952 .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::PUBLIC,
3961 1,
3962 |_k, _av| Ok(()),
3963 )
3964 .expect("Trying to read certificate entry.");
3965
3966 assert!(key_entry.pure_cert());
3967 assert!(key_entry.cert().is_none());
3968 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3969
3970 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003971 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003972 domain: Domain::APP,
3973 nspace: 1,
3974 alias: Some(TEST_ALIAS.to_string()),
3975 blob: None,
3976 },
3977 KeyType::Client,
3978 1,
3979 |_, _| Ok(()),
3980 )
3981 .unwrap();
3982
3983 assert_eq!(
3984 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3985 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003986 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003987 domain: Domain::APP,
3988 nspace: 1,
3989 alias: Some(TEST_ALIAS.to_string()),
3990 blob: None,
3991 },
3992 KeyType::Client,
3993 KeyEntryLoadBits::NONE,
3994 1,
3995 |_k, _av| Ok(()),
3996 )
3997 .unwrap_err()
3998 .root_cause()
3999 .downcast_ref::<KsError>()
4000 );
4001
4002 Ok(())
4003 }
4004
4005 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004006 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4007 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004008 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004009 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4010 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004011 let (_key_guard, key_entry) = db
4012 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004013 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004014 domain: Domain::SELINUX,
4015 nspace: 1,
4016 alias: Some(TEST_ALIAS.to_string()),
4017 blob: None,
4018 },
4019 KeyType::Client,
4020 KeyEntryLoadBits::BOTH,
4021 1,
4022 |_k, _av| Ok(()),
4023 )
4024 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004025 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004026
4027 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004028 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004029 domain: Domain::SELINUX,
4030 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004031 alias: Some(TEST_ALIAS.to_string()),
4032 blob: None,
4033 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004034 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004035 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004036 |_, _| Ok(()),
4037 )
4038 .unwrap();
4039
4040 assert_eq!(
4041 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4042 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004043 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004044 domain: Domain::SELINUX,
4045 nspace: 1,
4046 alias: Some(TEST_ALIAS.to_string()),
4047 blob: None,
4048 },
4049 KeyType::Client,
4050 KeyEntryLoadBits::NONE,
4051 1,
4052 |_k, _av| Ok(()),
4053 )
4054 .unwrap_err()
4055 .root_cause()
4056 .downcast_ref::<KsError>()
4057 );
4058
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004059 Ok(())
4060 }
4061
4062 #[test]
4063 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4064 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004065 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004066 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4067 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004068 let (_, key_entry) = db
4069 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004070 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004071 KeyType::Client,
4072 KeyEntryLoadBits::BOTH,
4073 1,
4074 |_k, _av| Ok(()),
4075 )
4076 .unwrap();
4077
Qi Wub9433b52020-12-01 14:52:46 +08004078 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004079
4080 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004081 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004082 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004083 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004084 |_, _| Ok(()),
4085 )
4086 .unwrap();
4087
4088 assert_eq!(
4089 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4090 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004091 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004092 KeyType::Client,
4093 KeyEntryLoadBits::NONE,
4094 1,
4095 |_k, _av| Ok(()),
4096 )
4097 .unwrap_err()
4098 .root_cause()
4099 .downcast_ref::<KsError>()
4100 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004101
4102 Ok(())
4103 }
4104
4105 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004106 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4107 let mut db = new_test_db()?;
4108 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4109 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4110 .0;
4111 // Update the usage count of the limited use key.
4112 db.check_and_update_key_usage_count(key_id)?;
4113
4114 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004115 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004116 KeyType::Client,
4117 KeyEntryLoadBits::BOTH,
4118 1,
4119 |_k, _av| Ok(()),
4120 )?;
4121
4122 // The usage count is decremented now.
4123 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4124
4125 Ok(())
4126 }
4127
4128 #[test]
4129 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4130 let mut db = new_test_db()?;
4131 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4132 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4133 .0;
4134 // Update the usage count of the limited use key.
4135 db.check_and_update_key_usage_count(key_id).expect(concat!(
4136 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4137 "This should succeed."
4138 ));
4139
4140 // Try to update the exhausted limited use key.
4141 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4142 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4143 "This should fail."
4144 ));
4145 assert_eq!(
4146 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4147 e.root_cause().downcast_ref::<KsError>().unwrap()
4148 );
4149
4150 Ok(())
4151 }
4152
4153 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004154 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4155 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004156 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004157 .context("test_insert_and_load_full_keyentry_from_grant")?
4158 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004159
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004160 let granted_key = db
4161 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004162 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004163 domain: Domain::APP,
4164 nspace: 0,
4165 alias: Some(TEST_ALIAS.to_string()),
4166 blob: None,
4167 },
4168 1,
4169 2,
4170 key_perm_set![KeyPerm::use_()],
4171 |_k, _av| Ok(()),
4172 )
4173 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004174
4175 debug_dump_grant_table(&mut db)?;
4176
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004177 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004178 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4179 assert_eq!(Domain::GRANT, k.domain);
4180 assert!(av.unwrap().includes(KeyPerm::use_()));
4181 Ok(())
4182 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004183 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004184
Qi Wub9433b52020-12-01 14:52:46 +08004185 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004186
Janis Danisevskis66784c42021-01-27 08:40:25 -08004187 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004188
4189 assert_eq!(
4190 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4191 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004192 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004193 KeyType::Client,
4194 KeyEntryLoadBits::NONE,
4195 2,
4196 |_k, _av| Ok(()),
4197 )
4198 .unwrap_err()
4199 .root_cause()
4200 .downcast_ref::<KsError>()
4201 );
4202
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004203 Ok(())
4204 }
4205
Janis Danisevskis45760022021-01-19 16:34:10 -08004206 // This test attempts to load a key by key id while the caller is not the owner
4207 // but a grant exists for the given key and the caller.
4208 #[test]
4209 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4210 let mut db = new_test_db()?;
4211 const OWNER_UID: u32 = 1u32;
4212 const GRANTEE_UID: u32 = 2u32;
4213 const SOMEONE_ELSE_UID: u32 = 3u32;
4214 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4215 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4216 .0;
4217
4218 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004219 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004220 domain: Domain::APP,
4221 nspace: 0,
4222 alias: Some(TEST_ALIAS.to_string()),
4223 blob: None,
4224 },
4225 OWNER_UID,
4226 GRANTEE_UID,
4227 key_perm_set![KeyPerm::use_()],
4228 |_k, _av| Ok(()),
4229 )
4230 .unwrap();
4231
4232 debug_dump_grant_table(&mut db)?;
4233
4234 let id_descriptor =
4235 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4236
4237 let (_, key_entry) = db
4238 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004239 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004240 KeyType::Client,
4241 KeyEntryLoadBits::BOTH,
4242 GRANTEE_UID,
4243 |k, av| {
4244 assert_eq!(Domain::APP, k.domain);
4245 assert_eq!(OWNER_UID as i64, k.nspace);
4246 assert!(av.unwrap().includes(KeyPerm::use_()));
4247 Ok(())
4248 },
4249 )
4250 .unwrap();
4251
4252 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4253
4254 let (_, key_entry) = db
4255 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004256 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004257 KeyType::Client,
4258 KeyEntryLoadBits::BOTH,
4259 SOMEONE_ELSE_UID,
4260 |k, av| {
4261 assert_eq!(Domain::APP, k.domain);
4262 assert_eq!(OWNER_UID as i64, k.nspace);
4263 assert!(av.is_none());
4264 Ok(())
4265 },
4266 )
4267 .unwrap();
4268
4269 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4270
Janis Danisevskis66784c42021-01-27 08:40:25 -08004271 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004272
4273 assert_eq!(
4274 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4275 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004276 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004277 KeyType::Client,
4278 KeyEntryLoadBits::NONE,
4279 GRANTEE_UID,
4280 |_k, _av| Ok(()),
4281 )
4282 .unwrap_err()
4283 .root_cause()
4284 .downcast_ref::<KsError>()
4285 );
4286
4287 Ok(())
4288 }
4289
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004290 // Creates a key migrates it to a different location and then tries to access it by the old
4291 // and new location.
4292 #[test]
4293 fn test_migrate_key_app_to_app() -> Result<()> {
4294 let mut db = new_test_db()?;
4295 const SOURCE_UID: u32 = 1u32;
4296 const DESTINATION_UID: u32 = 2u32;
4297 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4298 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4299 let key_id_guard =
4300 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4301 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4302
4303 let source_descriptor: KeyDescriptor = KeyDescriptor {
4304 domain: Domain::APP,
4305 nspace: -1,
4306 alias: Some(SOURCE_ALIAS.to_string()),
4307 blob: None,
4308 };
4309
4310 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4311 domain: Domain::APP,
4312 nspace: -1,
4313 alias: Some(DESTINATION_ALIAS.to_string()),
4314 blob: None,
4315 };
4316
4317 let key_id = key_id_guard.id();
4318
4319 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4320 Ok(())
4321 })
4322 .unwrap();
4323
4324 let (_, key_entry) = db
4325 .load_key_entry(
4326 &destination_descriptor,
4327 KeyType::Client,
4328 KeyEntryLoadBits::BOTH,
4329 DESTINATION_UID,
4330 |k, av| {
4331 assert_eq!(Domain::APP, k.domain);
4332 assert_eq!(DESTINATION_UID as i64, k.nspace);
4333 assert!(av.is_none());
4334 Ok(())
4335 },
4336 )
4337 .unwrap();
4338
4339 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4340
4341 assert_eq!(
4342 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4343 db.load_key_entry(
4344 &source_descriptor,
4345 KeyType::Client,
4346 KeyEntryLoadBits::NONE,
4347 SOURCE_UID,
4348 |_k, _av| Ok(()),
4349 )
4350 .unwrap_err()
4351 .root_cause()
4352 .downcast_ref::<KsError>()
4353 );
4354
4355 Ok(())
4356 }
4357
4358 // Creates a key migrates it to a different location and then tries to access it by the old
4359 // and new location.
4360 #[test]
4361 fn test_migrate_key_app_to_selinux() -> Result<()> {
4362 let mut db = new_test_db()?;
4363 const SOURCE_UID: u32 = 1u32;
4364 const DESTINATION_UID: u32 = 2u32;
4365 const DESTINATION_NAMESPACE: i64 = 1000i64;
4366 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4367 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4368 let key_id_guard =
4369 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4370 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4371
4372 let source_descriptor: KeyDescriptor = KeyDescriptor {
4373 domain: Domain::APP,
4374 nspace: -1,
4375 alias: Some(SOURCE_ALIAS.to_string()),
4376 blob: None,
4377 };
4378
4379 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4380 domain: Domain::SELINUX,
4381 nspace: DESTINATION_NAMESPACE,
4382 alias: Some(DESTINATION_ALIAS.to_string()),
4383 blob: None,
4384 };
4385
4386 let key_id = key_id_guard.id();
4387
4388 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4389 Ok(())
4390 })
4391 .unwrap();
4392
4393 let (_, key_entry) = db
4394 .load_key_entry(
4395 &destination_descriptor,
4396 KeyType::Client,
4397 KeyEntryLoadBits::BOTH,
4398 DESTINATION_UID,
4399 |k, av| {
4400 assert_eq!(Domain::SELINUX, k.domain);
4401 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4402 assert!(av.is_none());
4403 Ok(())
4404 },
4405 )
4406 .unwrap();
4407
4408 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4409
4410 assert_eq!(
4411 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4412 db.load_key_entry(
4413 &source_descriptor,
4414 KeyType::Client,
4415 KeyEntryLoadBits::NONE,
4416 SOURCE_UID,
4417 |_k, _av| Ok(()),
4418 )
4419 .unwrap_err()
4420 .root_cause()
4421 .downcast_ref::<KsError>()
4422 );
4423
4424 Ok(())
4425 }
4426
4427 // Creates two keys and tries to migrate the first to the location of the second which
4428 // is expected to fail.
4429 #[test]
4430 fn test_migrate_key_destination_occupied() -> Result<()> {
4431 let mut db = new_test_db()?;
4432 const SOURCE_UID: u32 = 1u32;
4433 const DESTINATION_UID: u32 = 2u32;
4434 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4435 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4436 let key_id_guard =
4437 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4438 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4439 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4440 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4441
4442 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4443 domain: Domain::APP,
4444 nspace: -1,
4445 alias: Some(DESTINATION_ALIAS.to_string()),
4446 blob: None,
4447 };
4448
4449 assert_eq!(
4450 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4451 db.migrate_key_namespace(
4452 key_id_guard,
4453 &destination_descriptor,
4454 DESTINATION_UID,
4455 |_k| Ok(())
4456 )
4457 .unwrap_err()
4458 .root_cause()
4459 .downcast_ref::<KsError>()
4460 );
4461
4462 Ok(())
4463 }
4464
Janis Danisevskisaec14592020-11-12 09:41:49 -08004465 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4466
Janis Danisevskisaec14592020-11-12 09:41:49 -08004467 #[test]
4468 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4469 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004470 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4471 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004472 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004473 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004474 .context("test_insert_and_load_full_keyentry_domain_app")?
4475 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004476 let (_key_guard, key_entry) = db
4477 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004478 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004479 domain: Domain::APP,
4480 nspace: 0,
4481 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4482 blob: None,
4483 },
4484 KeyType::Client,
4485 KeyEntryLoadBits::BOTH,
4486 33,
4487 |_k, _av| Ok(()),
4488 )
4489 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004490 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004491 let state = Arc::new(AtomicU8::new(1));
4492 let state2 = state.clone();
4493
4494 // Spawning a second thread that attempts to acquire the key id lock
4495 // for the same key as the primary thread. The primary thread then
4496 // waits, thereby forcing the secondary thread into the second stage
4497 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4498 // The test succeeds if the secondary thread observes the transition
4499 // of `state` from 1 to 2, despite having a whole second to overtake
4500 // the primary thread.
4501 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004502 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004503 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004504 assert!(db
4505 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004506 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004507 domain: Domain::APP,
4508 nspace: 0,
4509 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4510 blob: None,
4511 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004512 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004513 KeyEntryLoadBits::BOTH,
4514 33,
4515 |_k, _av| Ok(()),
4516 )
4517 .is_ok());
4518 // We should only see a 2 here because we can only return
4519 // from load_key_entry when the `_key_guard` expires,
4520 // which happens at the end of the scope.
4521 assert_eq!(2, state2.load(Ordering::Relaxed));
4522 });
4523
4524 thread::sleep(std::time::Duration::from_millis(1000));
4525
4526 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4527
4528 // Return the handle from this scope so we can join with the
4529 // secondary thread after the key id lock has expired.
4530 handle
4531 // This is where the `_key_guard` goes out of scope,
4532 // which is the reason for concurrent load_key_entry on the same key
4533 // to unblock.
4534 };
4535 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4536 // main test thread. We will not see failing asserts in secondary threads otherwise.
4537 handle.join().unwrap();
4538 Ok(())
4539 }
4540
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004541 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004542 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004543 let temp_dir =
4544 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4545
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004546 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4547 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004548
4549 let _tx1 = db1
4550 .conn
4551 .transaction_with_behavior(TransactionBehavior::Immediate)
4552 .expect("Failed to create first transaction.");
4553
4554 let error = db2
4555 .conn
4556 .transaction_with_behavior(TransactionBehavior::Immediate)
4557 .context("Transaction begin failed.")
4558 .expect_err("This should fail.");
4559 let root_cause = error.root_cause();
4560 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4561 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4562 {
4563 return;
4564 }
4565 panic!(
4566 "Unexpected error {:?} \n{:?} \n{:?}",
4567 error,
4568 root_cause,
4569 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4570 )
4571 }
4572
4573 #[cfg(disabled)]
4574 #[test]
4575 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4576 let temp_dir = Arc::new(
4577 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4578 .expect("Failed to create temp dir."),
4579 );
4580
4581 let test_begin = Instant::now();
4582
4583 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4584 const KEY_COUNT: u32 = 500u32;
4585 const OPEN_DB_COUNT: u32 = 50u32;
4586
4587 let mut actual_key_count = KEY_COUNT;
4588 // First insert KEY_COUNT keys.
4589 for count in 0..KEY_COUNT {
4590 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4591 actual_key_count = count;
4592 break;
4593 }
4594 let alias = format!("test_alias_{}", count);
4595 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4596 .expect("Failed to make key entry.");
4597 }
4598
4599 // Insert more keys from a different thread and into a different namespace.
4600 let temp_dir1 = temp_dir.clone();
4601 let handle1 = thread::spawn(move || {
4602 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4603
4604 for count in 0..actual_key_count {
4605 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4606 return;
4607 }
4608 let alias = format!("test_alias_{}", count);
4609 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4610 .expect("Failed to make key entry.");
4611 }
4612
4613 // then unbind them again.
4614 for count in 0..actual_key_count {
4615 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4616 return;
4617 }
4618 let key = KeyDescriptor {
4619 domain: Domain::APP,
4620 nspace: -1,
4621 alias: Some(format!("test_alias_{}", count)),
4622 blob: None,
4623 };
4624 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4625 }
4626 });
4627
4628 // And start unbinding the first set of keys.
4629 let temp_dir2 = temp_dir.clone();
4630 let handle2 = thread::spawn(move || {
4631 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4632
4633 for count in 0..actual_key_count {
4634 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4635 return;
4636 }
4637 let key = KeyDescriptor {
4638 domain: Domain::APP,
4639 nspace: -1,
4640 alias: Some(format!("test_alias_{}", count)),
4641 blob: None,
4642 };
4643 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4644 }
4645 });
4646
4647 let stop_deleting = Arc::new(AtomicU8::new(0));
4648 let stop_deleting2 = stop_deleting.clone();
4649
4650 // And delete anything that is unreferenced keys.
4651 let temp_dir3 = temp_dir.clone();
4652 let handle3 = thread::spawn(move || {
4653 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4654
4655 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4656 while let Some((key_guard, _key)) =
4657 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4658 {
4659 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4660 return;
4661 }
4662 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4663 }
4664 std::thread::sleep(std::time::Duration::from_millis(100));
4665 }
4666 });
4667
4668 // While a lot of inserting and deleting is going on we have to open database connections
4669 // successfully and use them.
4670 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4671 // out of scope.
4672 #[allow(clippy::redundant_clone)]
4673 let temp_dir4 = temp_dir.clone();
4674 let handle4 = thread::spawn(move || {
4675 for count in 0..OPEN_DB_COUNT {
4676 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4677 return;
4678 }
4679 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4680
4681 let alias = format!("test_alias_{}", count);
4682 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4683 .expect("Failed to make key entry.");
4684 let key = KeyDescriptor {
4685 domain: Domain::APP,
4686 nspace: -1,
4687 alias: Some(alias),
4688 blob: None,
4689 };
4690 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4691 }
4692 });
4693
4694 handle1.join().expect("Thread 1 panicked.");
4695 handle2.join().expect("Thread 2 panicked.");
4696 handle4.join().expect("Thread 4 panicked.");
4697
4698 stop_deleting.store(1, Ordering::Relaxed);
4699 handle3.join().expect("Thread 3 panicked.");
4700
4701 Ok(())
4702 }
4703
4704 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004705 fn list() -> Result<()> {
4706 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004707 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004708 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4709 (Domain::APP, 1, "test1"),
4710 (Domain::APP, 1, "test2"),
4711 (Domain::APP, 1, "test3"),
4712 (Domain::APP, 1, "test4"),
4713 (Domain::APP, 1, "test5"),
4714 (Domain::APP, 1, "test6"),
4715 (Domain::APP, 1, "test7"),
4716 (Domain::APP, 2, "test1"),
4717 (Domain::APP, 2, "test2"),
4718 (Domain::APP, 2, "test3"),
4719 (Domain::APP, 2, "test4"),
4720 (Domain::APP, 2, "test5"),
4721 (Domain::APP, 2, "test6"),
4722 (Domain::APP, 2, "test8"),
4723 (Domain::SELINUX, 100, "test1"),
4724 (Domain::SELINUX, 100, "test2"),
4725 (Domain::SELINUX, 100, "test3"),
4726 (Domain::SELINUX, 100, "test4"),
4727 (Domain::SELINUX, 100, "test5"),
4728 (Domain::SELINUX, 100, "test6"),
4729 (Domain::SELINUX, 100, "test9"),
4730 ];
4731
4732 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4733 .iter()
4734 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004735 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4736 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004737 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4738 });
4739 (entry.id(), *ns)
4740 })
4741 .collect();
4742
4743 for (domain, namespace) in
4744 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4745 {
4746 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4747 .iter()
4748 .filter_map(|(domain, ns, alias)| match ns {
4749 ns if *ns == *namespace => Some(KeyDescriptor {
4750 domain: *domain,
4751 nspace: *ns,
4752 alias: Some(alias.to_string()),
4753 blob: None,
4754 }),
4755 _ => None,
4756 })
4757 .collect();
4758 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07004759 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004760 list_result.sort();
4761 assert_eq!(list_o_descriptors, list_result);
4762
4763 let mut list_o_ids: Vec<i64> = list_o_descriptors
4764 .into_iter()
4765 .map(|d| {
4766 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004767 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004768 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004769 KeyType::Client,
4770 KeyEntryLoadBits::NONE,
4771 *namespace as u32,
4772 |_, _| Ok(()),
4773 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004774 .unwrap();
4775 entry.id()
4776 })
4777 .collect();
4778 list_o_ids.sort_unstable();
4779 let mut loaded_entries: Vec<i64> = list_o_keys
4780 .iter()
4781 .filter_map(|(id, ns)| match ns {
4782 ns if *ns == *namespace => Some(*id),
4783 _ => None,
4784 })
4785 .collect();
4786 loaded_entries.sort_unstable();
4787 assert_eq!(list_o_ids, loaded_entries);
4788 }
Janis Danisevskis18313832021-05-17 13:30:32 -07004789 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004790
4791 Ok(())
4792 }
4793
Joel Galenson0891bc12020-07-20 10:37:03 -07004794 // Helpers
4795
4796 // Checks that the given result is an error containing the given string.
4797 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4798 let error_str = format!(
4799 "{:#?}",
4800 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4801 );
4802 assert!(
4803 error_str.contains(target),
4804 "The string \"{}\" should contain \"{}\"",
4805 error_str,
4806 target
4807 );
4808 }
4809
Joel Galenson2aab4432020-07-22 15:27:57 -07004810 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004811 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004812 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004813 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004814 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004815 namespace: Option<i64>,
4816 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004817 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004818 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004819 }
4820
4821 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4822 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004823 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004824 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004825 Ok(KeyEntryRow {
4826 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004827 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004828 domain: match row.get(2)? {
4829 Some(i) => Some(Domain(i)),
4830 None => None,
4831 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004832 namespace: row.get(3)?,
4833 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004834 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004835 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004836 })
4837 })?
4838 .map(|r| r.context("Could not read keyentry row."))
4839 .collect::<Result<Vec<_>>>()
4840 }
4841
Max Biresb2e1d032021-02-08 21:35:05 -08004842 struct RemoteProvValues {
4843 cert_chain: Vec<u8>,
4844 priv_key: Vec<u8>,
4845 batch_cert: Vec<u8>,
4846 }
4847
Max Bires2b2e6562020-09-22 11:22:36 -07004848 fn load_attestation_key_pool(
4849 db: &mut KeystoreDB,
4850 expiration_date: i64,
4851 namespace: i64,
4852 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004853 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004854 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4855 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4856 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4857 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004858 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004859 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4860 db.store_signed_attestation_certificate_chain(
4861 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004862 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004863 &cert_chain,
4864 expiration_date,
4865 &KEYSTORE_UUID,
4866 )?;
4867 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004868 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004869 }
4870
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004871 // Note: The parameters and SecurityLevel associations are nonsensical. This
4872 // collection is only used to check if the parameters are preserved as expected by the
4873 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004874 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4875 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004876 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4877 KeyParameter::new(
4878 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4879 SecurityLevel::TRUSTED_ENVIRONMENT,
4880 ),
4881 KeyParameter::new(
4882 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4883 SecurityLevel::TRUSTED_ENVIRONMENT,
4884 ),
4885 KeyParameter::new(
4886 KeyParameterValue::Algorithm(Algorithm::RSA),
4887 SecurityLevel::TRUSTED_ENVIRONMENT,
4888 ),
4889 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4890 KeyParameter::new(
4891 KeyParameterValue::BlockMode(BlockMode::ECB),
4892 SecurityLevel::TRUSTED_ENVIRONMENT,
4893 ),
4894 KeyParameter::new(
4895 KeyParameterValue::BlockMode(BlockMode::GCM),
4896 SecurityLevel::TRUSTED_ENVIRONMENT,
4897 ),
4898 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4899 KeyParameter::new(
4900 KeyParameterValue::Digest(Digest::MD5),
4901 SecurityLevel::TRUSTED_ENVIRONMENT,
4902 ),
4903 KeyParameter::new(
4904 KeyParameterValue::Digest(Digest::SHA_2_224),
4905 SecurityLevel::TRUSTED_ENVIRONMENT,
4906 ),
4907 KeyParameter::new(
4908 KeyParameterValue::Digest(Digest::SHA_2_256),
4909 SecurityLevel::STRONGBOX,
4910 ),
4911 KeyParameter::new(
4912 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4913 SecurityLevel::TRUSTED_ENVIRONMENT,
4914 ),
4915 KeyParameter::new(
4916 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4917 SecurityLevel::TRUSTED_ENVIRONMENT,
4918 ),
4919 KeyParameter::new(
4920 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4921 SecurityLevel::STRONGBOX,
4922 ),
4923 KeyParameter::new(
4924 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4925 SecurityLevel::TRUSTED_ENVIRONMENT,
4926 ),
4927 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4928 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4929 KeyParameter::new(
4930 KeyParameterValue::EcCurve(EcCurve::P_224),
4931 SecurityLevel::TRUSTED_ENVIRONMENT,
4932 ),
4933 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4934 KeyParameter::new(
4935 KeyParameterValue::EcCurve(EcCurve::P_384),
4936 SecurityLevel::TRUSTED_ENVIRONMENT,
4937 ),
4938 KeyParameter::new(
4939 KeyParameterValue::EcCurve(EcCurve::P_521),
4940 SecurityLevel::TRUSTED_ENVIRONMENT,
4941 ),
4942 KeyParameter::new(
4943 KeyParameterValue::RSAPublicExponent(3),
4944 SecurityLevel::TRUSTED_ENVIRONMENT,
4945 ),
4946 KeyParameter::new(
4947 KeyParameterValue::IncludeUniqueID,
4948 SecurityLevel::TRUSTED_ENVIRONMENT,
4949 ),
4950 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4951 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4952 KeyParameter::new(
4953 KeyParameterValue::ActiveDateTime(1234567890),
4954 SecurityLevel::STRONGBOX,
4955 ),
4956 KeyParameter::new(
4957 KeyParameterValue::OriginationExpireDateTime(1234567890),
4958 SecurityLevel::TRUSTED_ENVIRONMENT,
4959 ),
4960 KeyParameter::new(
4961 KeyParameterValue::UsageExpireDateTime(1234567890),
4962 SecurityLevel::TRUSTED_ENVIRONMENT,
4963 ),
4964 KeyParameter::new(
4965 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4966 SecurityLevel::TRUSTED_ENVIRONMENT,
4967 ),
4968 KeyParameter::new(
4969 KeyParameterValue::MaxUsesPerBoot(1234567890),
4970 SecurityLevel::TRUSTED_ENVIRONMENT,
4971 ),
4972 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4973 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4974 KeyParameter::new(
4975 KeyParameterValue::NoAuthRequired,
4976 SecurityLevel::TRUSTED_ENVIRONMENT,
4977 ),
4978 KeyParameter::new(
4979 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4980 SecurityLevel::TRUSTED_ENVIRONMENT,
4981 ),
4982 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4983 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4984 KeyParameter::new(
4985 KeyParameterValue::TrustedUserPresenceRequired,
4986 SecurityLevel::TRUSTED_ENVIRONMENT,
4987 ),
4988 KeyParameter::new(
4989 KeyParameterValue::TrustedConfirmationRequired,
4990 SecurityLevel::TRUSTED_ENVIRONMENT,
4991 ),
4992 KeyParameter::new(
4993 KeyParameterValue::UnlockedDeviceRequired,
4994 SecurityLevel::TRUSTED_ENVIRONMENT,
4995 ),
4996 KeyParameter::new(
4997 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4998 SecurityLevel::SOFTWARE,
4999 ),
5000 KeyParameter::new(
5001 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5002 SecurityLevel::SOFTWARE,
5003 ),
5004 KeyParameter::new(
5005 KeyParameterValue::CreationDateTime(12345677890),
5006 SecurityLevel::SOFTWARE,
5007 ),
5008 KeyParameter::new(
5009 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5010 SecurityLevel::TRUSTED_ENVIRONMENT,
5011 ),
5012 KeyParameter::new(
5013 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5014 SecurityLevel::TRUSTED_ENVIRONMENT,
5015 ),
5016 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5017 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5018 KeyParameter::new(
5019 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5020 SecurityLevel::SOFTWARE,
5021 ),
5022 KeyParameter::new(
5023 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5024 SecurityLevel::TRUSTED_ENVIRONMENT,
5025 ),
5026 KeyParameter::new(
5027 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5028 SecurityLevel::TRUSTED_ENVIRONMENT,
5029 ),
5030 KeyParameter::new(
5031 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5032 SecurityLevel::TRUSTED_ENVIRONMENT,
5033 ),
5034 KeyParameter::new(
5035 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5036 SecurityLevel::TRUSTED_ENVIRONMENT,
5037 ),
5038 KeyParameter::new(
5039 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5040 SecurityLevel::TRUSTED_ENVIRONMENT,
5041 ),
5042 KeyParameter::new(
5043 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5044 SecurityLevel::TRUSTED_ENVIRONMENT,
5045 ),
5046 KeyParameter::new(
5047 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5048 SecurityLevel::TRUSTED_ENVIRONMENT,
5049 ),
5050 KeyParameter::new(
5051 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5052 SecurityLevel::TRUSTED_ENVIRONMENT,
5053 ),
5054 KeyParameter::new(
5055 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5056 SecurityLevel::TRUSTED_ENVIRONMENT,
5057 ),
5058 KeyParameter::new(
5059 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5060 SecurityLevel::TRUSTED_ENVIRONMENT,
5061 ),
5062 KeyParameter::new(
5063 KeyParameterValue::VendorPatchLevel(3),
5064 SecurityLevel::TRUSTED_ENVIRONMENT,
5065 ),
5066 KeyParameter::new(
5067 KeyParameterValue::BootPatchLevel(4),
5068 SecurityLevel::TRUSTED_ENVIRONMENT,
5069 ),
5070 KeyParameter::new(
5071 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5072 SecurityLevel::TRUSTED_ENVIRONMENT,
5073 ),
5074 KeyParameter::new(
5075 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5076 SecurityLevel::TRUSTED_ENVIRONMENT,
5077 ),
5078 KeyParameter::new(
5079 KeyParameterValue::MacLength(256),
5080 SecurityLevel::TRUSTED_ENVIRONMENT,
5081 ),
5082 KeyParameter::new(
5083 KeyParameterValue::ResetSinceIdRotation,
5084 SecurityLevel::TRUSTED_ENVIRONMENT,
5085 ),
5086 KeyParameter::new(
5087 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5088 SecurityLevel::TRUSTED_ENVIRONMENT,
5089 ),
Qi Wub9433b52020-12-01 14:52:46 +08005090 ];
5091 if let Some(value) = max_usage_count {
5092 params.push(KeyParameter::new(
5093 KeyParameterValue::UsageCountLimit(value),
5094 SecurityLevel::SOFTWARE,
5095 ));
5096 }
5097 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005098 }
5099
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005100 fn make_test_key_entry(
5101 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005102 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005103 namespace: i64,
5104 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005105 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005106 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005107 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005108 let mut blob_metadata = BlobMetaData::new();
5109 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5110 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5111 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5112 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5113 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5114
5115 db.set_blob(
5116 &key_id,
5117 SubComponentType::KEY_BLOB,
5118 Some(TEST_KEY_BLOB),
5119 Some(&blob_metadata),
5120 )?;
5121 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5122 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005123
5124 let params = make_test_params(max_usage_count);
5125 db.insert_keyparameter(&key_id, &params)?;
5126
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005127 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005128 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005129 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005130 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005131 Ok(key_id)
5132 }
5133
Qi Wub9433b52020-12-01 14:52:46 +08005134 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5135 let params = make_test_params(max_usage_count);
5136
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005137 let mut blob_metadata = BlobMetaData::new();
5138 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5139 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5140 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5141 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5142 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5143
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005144 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005145 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005146
5147 KeyEntry {
5148 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005149 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005150 cert: Some(TEST_CERT_BLOB.to_vec()),
5151 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005152 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005153 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005154 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005155 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005156 }
5157 }
5158
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005159 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005160 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005161 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005162 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005163 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005164 NO_PARAMS,
5165 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005166 Ok((
5167 row.get(0)?,
5168 row.get(1)?,
5169 row.get(2)?,
5170 row.get(3)?,
5171 row.get(4)?,
5172 row.get(5)?,
5173 row.get(6)?,
5174 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005175 },
5176 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005177
5178 println!("Key entry table rows:");
5179 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005180 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005181 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005182 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5183 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005184 );
5185 }
5186 Ok(())
5187 }
5188
5189 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005190 let mut stmt = db
5191 .conn
5192 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005193 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5194 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5195 })?;
5196
5197 println!("Grant table rows:");
5198 for r in rows {
5199 let (id, gt, ki, av) = r.unwrap();
5200 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5201 }
5202 Ok(())
5203 }
5204
Joel Galenson0891bc12020-07-20 10:37:03 -07005205 // Use a custom random number generator that repeats each number once.
5206 // This allows us to test repeated elements.
5207
5208 thread_local! {
5209 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5210 }
5211
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005212 fn reset_random() {
5213 RANDOM_COUNTER.with(|counter| {
5214 *counter.borrow_mut() = 0;
5215 })
5216 }
5217
Joel Galenson0891bc12020-07-20 10:37:03 -07005218 pub fn random() -> i64 {
5219 RANDOM_COUNTER.with(|counter| {
5220 let result = *counter.borrow() / 2;
5221 *counter.borrow_mut() += 1;
5222 result
5223 })
5224 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005225
5226 #[test]
5227 fn test_last_off_body() -> Result<()> {
5228 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005229 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005230 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005231 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005232 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005233 let one_second = Duration::from_secs(1);
5234 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005235 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005236 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005237 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005238 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005239 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005240 Ok(())
5241 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005242
5243 #[test]
5244 fn test_unbind_keys_for_user() -> Result<()> {
5245 let mut db = new_test_db()?;
5246 db.unbind_keys_for_user(1, false)?;
5247
5248 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5249 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5250 db.unbind_keys_for_user(2, false)?;
5251
Janis Danisevskis18313832021-05-17 13:30:32 -07005252 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5253 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005254
5255 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005256 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005257
5258 Ok(())
5259 }
5260
5261 #[test]
5262 fn test_store_super_key() -> Result<()> {
5263 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005264 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005265 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005266 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005267 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005268 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005269
5270 let (encrypted_super_key, metadata) =
5271 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005272 db.store_super_key(
5273 1,
5274 &USER_SUPER_KEY,
5275 &encrypted_super_key,
5276 &metadata,
5277 &KeyMetaData::new(),
5278 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005279
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005280 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005281 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005282
Paul Crowley7a658392021-03-18 17:08:20 -07005283 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005284 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5285 USER_SUPER_KEY.algorithm,
5286 key_entry,
5287 &pw,
5288 None,
5289 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005290
Paul Crowley7a658392021-03-18 17:08:20 -07005291 let decrypted_secret_bytes =
5292 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5293 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005294 Ok(())
5295 }
Seth Moore78c091f2021-04-09 21:38:30 +00005296
5297 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5298 vec![
5299 StatsdStorageType::KeyEntry,
5300 StatsdStorageType::KeyEntryIdIndex,
5301 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5302 StatsdStorageType::BlobEntry,
5303 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5304 StatsdStorageType::KeyParameter,
5305 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5306 StatsdStorageType::KeyMetadata,
5307 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5308 StatsdStorageType::Grant,
5309 StatsdStorageType::AuthToken,
5310 StatsdStorageType::BlobMetadata,
5311 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5312 ]
5313 }
5314
5315 /// Perform a simple check to ensure that we can query all the storage types
5316 /// that are supported by the DB. Check for reasonable values.
5317 #[test]
5318 fn test_query_all_valid_table_sizes() -> Result<()> {
5319 const PAGE_SIZE: i64 = 4096;
5320
5321 let mut db = new_test_db()?;
5322
5323 for t in get_valid_statsd_storage_types() {
5324 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005325 // AuthToken can be less than a page since it's in a btree, not sqlite
5326 // TODO(b/187474736) stop using if-let here
5327 if let StatsdStorageType::AuthToken = t {
5328 } else {
5329 assert!(stat.size >= PAGE_SIZE);
5330 }
Seth Moore78c091f2021-04-09 21:38:30 +00005331 assert!(stat.size >= stat.unused_size);
5332 }
5333
5334 Ok(())
5335 }
5336
5337 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5338 get_valid_statsd_storage_types()
5339 .into_iter()
5340 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5341 .collect()
5342 }
5343
5344 fn assert_storage_increased(
5345 db: &mut KeystoreDB,
5346 increased_storage_types: Vec<StatsdStorageType>,
5347 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5348 ) {
5349 for storage in increased_storage_types {
5350 // Verify the expected storage increased.
5351 let new = db.get_storage_stat(storage).unwrap();
5352 let storage = storage as i32;
5353 let old = &baseline[&storage];
5354 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5355 assert!(
5356 new.unused_size <= old.unused_size,
5357 "{}: {} <= {}",
5358 storage,
5359 new.unused_size,
5360 old.unused_size
5361 );
5362
5363 // Update the baseline with the new value so that it succeeds in the
5364 // later comparison.
5365 baseline.insert(storage, new);
5366 }
5367
5368 // Get an updated map of the storage and verify there were no unexpected changes.
5369 let updated_stats = get_storage_stats_map(db);
5370 assert_eq!(updated_stats.len(), baseline.len());
5371
5372 for &k in baseline.keys() {
5373 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5374 let mut s = String::new();
5375 for &k in map.keys() {
5376 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5377 .expect("string concat failed");
5378 }
5379 s
5380 };
5381
5382 assert!(
5383 updated_stats[&k].size == baseline[&k].size
5384 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5385 "updated_stats:\n{}\nbaseline:\n{}",
5386 stringify(&updated_stats),
5387 stringify(&baseline)
5388 );
5389 }
5390 }
5391
5392 #[test]
5393 fn test_verify_key_table_size_reporting() -> Result<()> {
5394 let mut db = new_test_db()?;
5395 let mut working_stats = get_storage_stats_map(&mut db);
5396
5397 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5398 assert_storage_increased(
5399 &mut db,
5400 vec![
5401 StatsdStorageType::KeyEntry,
5402 StatsdStorageType::KeyEntryIdIndex,
5403 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5404 ],
5405 &mut working_stats,
5406 );
5407
5408 let mut blob_metadata = BlobMetaData::new();
5409 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5410 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5411 assert_storage_increased(
5412 &mut db,
5413 vec![
5414 StatsdStorageType::BlobEntry,
5415 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5416 StatsdStorageType::BlobMetadata,
5417 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5418 ],
5419 &mut working_stats,
5420 );
5421
5422 let params = make_test_params(None);
5423 db.insert_keyparameter(&key_id, &params)?;
5424 assert_storage_increased(
5425 &mut db,
5426 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5427 &mut working_stats,
5428 );
5429
5430 let mut metadata = KeyMetaData::new();
5431 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5432 db.insert_key_metadata(&key_id, &metadata)?;
5433 assert_storage_increased(
5434 &mut db,
5435 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5436 &mut working_stats,
5437 );
5438
5439 let mut sum = 0;
5440 for stat in working_stats.values() {
5441 sum += stat.size;
5442 }
5443 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5444 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5445
5446 Ok(())
5447 }
5448
5449 #[test]
5450 fn test_verify_auth_table_size_reporting() -> Result<()> {
5451 let mut db = new_test_db()?;
5452 let mut working_stats = get_storage_stats_map(&mut db);
5453 db.insert_auth_token(&HardwareAuthToken {
5454 challenge: 123,
5455 userId: 456,
5456 authenticatorId: 789,
5457 authenticatorType: kmhw_authenticator_type::ANY,
5458 timestamp: Timestamp { milliSeconds: 10 },
5459 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005460 });
Seth Moore78c091f2021-04-09 21:38:30 +00005461 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5462 Ok(())
5463 }
5464
5465 #[test]
5466 fn test_verify_grant_table_size_reporting() -> Result<()> {
5467 const OWNER: i64 = 1;
5468 let mut db = new_test_db()?;
5469 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5470
5471 let mut working_stats = get_storage_stats_map(&mut db);
5472 db.grant(
5473 &KeyDescriptor {
5474 domain: Domain::APP,
5475 nspace: 0,
5476 alias: Some(TEST_ALIAS.to_string()),
5477 blob: None,
5478 },
5479 OWNER as u32,
5480 123,
5481 key_perm_set![KeyPerm::use_()],
5482 |_, _| Ok(()),
5483 )?;
5484
5485 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5486
5487 Ok(())
5488 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005489
5490 #[test]
5491 fn find_auth_token_entry_returns_latest() -> Result<()> {
5492 let mut db = new_test_db()?;
5493 db.insert_auth_token(&HardwareAuthToken {
5494 challenge: 123,
5495 userId: 456,
5496 authenticatorId: 789,
5497 authenticatorType: kmhw_authenticator_type::ANY,
5498 timestamp: Timestamp { milliSeconds: 10 },
5499 mac: b"mac0".to_vec(),
5500 });
5501 std::thread::sleep(std::time::Duration::from_millis(1));
5502 db.insert_auth_token(&HardwareAuthToken {
5503 challenge: 123,
5504 userId: 457,
5505 authenticatorId: 789,
5506 authenticatorType: kmhw_authenticator_type::ANY,
5507 timestamp: Timestamp { milliSeconds: 12 },
5508 mac: b"mac1".to_vec(),
5509 });
5510 std::thread::sleep(std::time::Duration::from_millis(1));
5511 db.insert_auth_token(&HardwareAuthToken {
5512 challenge: 123,
5513 userId: 458,
5514 authenticatorId: 789,
5515 authenticatorType: kmhw_authenticator_type::ANY,
5516 timestamp: Timestamp { milliSeconds: 3 },
5517 mac: b"mac2".to_vec(),
5518 });
5519 // All three entries are in the database
5520 assert_eq!(db.perboot.auth_tokens_len(), 3);
5521 // It selected the most recent timestamp
5522 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5523 Ok(())
5524 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005525
5526 #[test]
5527 fn test_set_wal_mode() -> Result<()> {
5528 let temp_dir = TempDir::new("test_set_wal_mode")?;
5529 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5530 let mode: String =
5531 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5532 row.get(0)
5533 })?;
5534 assert_eq!(mode, "delete");
5535 db.conn.close().expect("Close didn't work");
5536
5537 KeystoreDB::set_wal_mode(temp_dir.path())?;
5538
5539 db = KeystoreDB::new(temp_dir.path(), None)?;
5540 let mode: String =
5541 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5542 row.get(0)
5543 })?;
5544 assert_eq!(mode, "wal");
5545 Ok(())
5546 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01005547
5548 #[test]
5549 fn test_load_key_descriptor() -> Result<()> {
5550 let mut db = new_test_db()?;
5551 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5552
5553 let key = db.load_key_descriptor(key_id)?.unwrap();
5554
5555 assert_eq!(key.domain, Domain::APP);
5556 assert_eq!(key.nspace, 1);
5557 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5558
5559 // No such id
5560 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5561 Ok(())
5562 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005563}