blob: 7c0d4c76bbd850b225395a66cb610ce796e7ce71 [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
45
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080047use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070048use crate::permission::KeyPermSet;
Janis Danisevskis850d4862021-05-05 08:41:14 -070049use crate::utils::{get_current_time_in_seconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080050use crate::{
51 db_utils::{self, SqlField},
52 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070053 super_key::USER_SUPER_KEY,
54};
55use crate::{
56 error::{Error as KsError, ErrorCode, ResponseCode},
57 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080058};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080059use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080060use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070061
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080063 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080065};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070066use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070067 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070068};
Max Bires2b2e6562020-09-22 11:22:36 -070069use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
70 AttestationPoolStatus::AttestationPoolStatus,
71};
Seth Moore78c091f2021-04-09 21:38:30 +000072use statslog_rust::keystore2_storage_stats::{
73 Keystore2StorageStats, StorageType as StatsdStorageType,
74};
Max Bires2b2e6562020-09-22 11:22:36 -070075
76use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080077use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000078use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070079#[cfg(not(test))]
80use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070081use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080082 params,
83 types::FromSql,
84 types::FromSqlResult,
85 types::ToSqlOutput,
86 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080087 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070088};
Max Bires2b2e6562020-09-22 11:22:36 -070089
Janis Danisevskisaec14592020-11-12 09:41:49 -080090use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080091 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080092 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070093 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080095};
Max Bires2b2e6562020-09-22 11:22:36 -070096
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800100impl_metadata!(
101 /// A set of metadata for key entries.
102 #[derive(Debug, Default, Eq, PartialEq)]
103 pub struct KeyMetaData;
104 /// A metadata entry for key entries.
105 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
106 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800107 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800108 CreationDate(DateTime) with accessor creation_date,
109 /// Expiration date for attestation keys.
110 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700111 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
112 /// provisioning
113 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
114 /// Vector representing the raw public key so results from the server can be matched
115 /// to the right entry
116 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700117 /// SEC1 public key for ECDH encryption
118 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800119 // --- ADD NEW META DATA FIELDS HERE ---
120 // For backwards compatibility add new entries only to
121 // end of this list and above this comment.
122 };
123);
124
125impl KeyMetaData {
126 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
127 let mut stmt = tx
128 .prepare(
129 "SELECT tag, data from persistent.keymetadata
130 WHERE keyentryid = ?;",
131 )
132 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
133
134 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
135
136 let mut rows =
137 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
138 db_utils::with_rows_extract_all(&mut rows, |row| {
139 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
140 metadata.insert(
141 db_tag,
142 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
143 .context("Failed to read KeyMetaEntry.")?,
144 );
145 Ok(())
146 })
147 .context("In KeyMetaData::load_from_db.")?;
148
149 Ok(Self { data: metadata })
150 }
151
152 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
153 let mut stmt = tx
154 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000155 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800156 VALUES (?, ?, ?);",
157 )
158 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
159
160 let iter = self.data.iter();
161 for (tag, entry) in iter {
162 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
163 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
164 })?;
165 }
166 Ok(())
167 }
168}
169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170impl_metadata!(
171 /// A set of metadata for key blobs.
172 #[derive(Debug, Default, Eq, PartialEq)]
173 pub struct BlobMetaData;
174 /// A metadata entry for key blobs.
175 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
176 pub enum BlobMetaEntry {
177 /// If present, indicates that the blob is encrypted with another key or a key derived
178 /// from a password.
179 EncryptedBy(EncryptedBy) with accessor encrypted_by,
180 /// If the blob is password encrypted this field is set to the
181 /// salt used for the key derivation.
182 Salt(Vec<u8>) with accessor salt,
183 /// If the blob is encrypted, this field is set to the initialization vector.
184 Iv(Vec<u8>) with accessor iv,
185 /// If the blob is encrypted, this field holds the AEAD TAG.
186 AeadTag(Vec<u8>) with accessor aead_tag,
187 /// The uuid of the owning KeyMint instance.
188 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700189 /// If the key is ECDH encrypted, this is the ephemeral public key
190 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000191 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
192 /// of that key
193 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800194 // --- ADD NEW META DATA FIELDS HERE ---
195 // For backwards compatibility add new entries only to
196 // end of this list and above this comment.
197 };
198);
199
200impl BlobMetaData {
201 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
202 let mut stmt = tx
203 .prepare(
204 "SELECT tag, data from persistent.blobmetadata
205 WHERE blobentryid = ?;",
206 )
207 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
208
209 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
210
211 let mut rows =
212 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
213 db_utils::with_rows_extract_all(&mut rows, |row| {
214 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
215 metadata.insert(
216 db_tag,
217 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
218 .context("Failed to read BlobMetaEntry.")?,
219 );
220 Ok(())
221 })
222 .context("In BlobMetaData::load_from_db.")?;
223
224 Ok(Self { data: metadata })
225 }
226
227 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
228 let mut stmt = tx
229 .prepare(
230 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
231 VALUES (?, ?, ?);",
232 )
233 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
234
235 let iter = self.data.iter();
236 for (tag, entry) in iter {
237 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
238 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
239 })?;
240 }
241 Ok(())
242 }
243}
244
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800245/// Indicates the type of the keyentry.
246#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
247pub enum KeyType {
248 /// This is a client key type. These keys are created or imported through the Keystore 2.0
249 /// AIDL interface android.system.keystore2.
250 Client,
251 /// This is a super key type. These keys are created by keystore itself and used to encrypt
252 /// other key blobs to provide LSKF binding.
253 Super,
254 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
255 Attestation,
256}
257
258impl ToSql for KeyType {
259 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
260 Ok(ToSqlOutput::Owned(Value::Integer(match self {
261 KeyType::Client => 0,
262 KeyType::Super => 1,
263 KeyType::Attestation => 2,
264 })))
265 }
266}
267
268impl FromSql for KeyType {
269 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
270 match i64::column_result(value)? {
271 0 => Ok(KeyType::Client),
272 1 => Ok(KeyType::Super),
273 2 => Ok(KeyType::Attestation),
274 v => Err(FromSqlError::OutOfRange(v)),
275 }
276 }
277}
278
Max Bires8e93d2b2021-01-14 13:17:59 -0800279/// Uuid representation that can be stored in the database.
280/// Right now it can only be initialized from SecurityLevel.
281/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
282#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
283pub struct Uuid([u8; 16]);
284
285impl Deref for Uuid {
286 type Target = [u8; 16];
287
288 fn deref(&self) -> &Self::Target {
289 &self.0
290 }
291}
292
293impl From<SecurityLevel> for Uuid {
294 fn from(sec_level: SecurityLevel) -> Self {
295 Self((sec_level.0 as u128).to_be_bytes())
296 }
297}
298
299impl ToSql for Uuid {
300 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
301 self.0.to_sql()
302 }
303}
304
305impl FromSql for Uuid {
306 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
307 let blob = Vec::<u8>::column_result(value)?;
308 if blob.len() != 16 {
309 return Err(FromSqlError::OutOfRange(blob.len() as i64));
310 }
311 let mut arr = [0u8; 16];
312 arr.copy_from_slice(&blob);
313 Ok(Self(arr))
314 }
315}
316
317/// Key entries that are not associated with any KeyMint instance, such as pure certificate
318/// entries are associated with this UUID.
319pub static KEYSTORE_UUID: Uuid = Uuid([
320 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
321]);
322
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800323/// Indicates how the sensitive part of this key blob is encrypted.
324#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
325pub enum EncryptedBy {
326 /// The keyblob is encrypted by a user password.
327 /// In the database this variant is represented as NULL.
328 Password,
329 /// The keyblob is encrypted by another key with wrapped key id.
330 /// In the database this variant is represented as non NULL value
331 /// that is convertible to i64, typically NUMERIC.
332 KeyId(i64),
333}
334
335impl ToSql for EncryptedBy {
336 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
337 match self {
338 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
339 Self::KeyId(id) => id.to_sql(),
340 }
341 }
342}
343
344impl FromSql for EncryptedBy {
345 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
346 match value {
347 ValueRef::Null => Ok(Self::Password),
348 _ => Ok(Self::KeyId(i64::column_result(value)?)),
349 }
350 }
351}
352
353/// A database representation of wall clock time. DateTime stores unix epoch time as
354/// i64 in milliseconds.
355#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
356pub struct DateTime(i64);
357
358/// Error type returned when creating DateTime or converting it from and to
359/// SystemTime.
360#[derive(thiserror::Error, Debug)]
361pub enum DateTimeError {
362 /// This is returned when SystemTime and Duration computations fail.
363 #[error(transparent)]
364 SystemTimeError(#[from] SystemTimeError),
365
366 /// This is returned when type conversions fail.
367 #[error(transparent)]
368 TypeConversion(#[from] std::num::TryFromIntError),
369
370 /// This is returned when checked time arithmetic failed.
371 #[error("Time arithmetic failed.")]
372 TimeArithmetic,
373}
374
375impl DateTime {
376 /// Constructs a new DateTime object denoting the current time. This may fail during
377 /// conversion to unix epoch time and during conversion to the internal i64 representation.
378 pub fn now() -> Result<Self, DateTimeError> {
379 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
380 }
381
382 /// Constructs a new DateTime object from milliseconds.
383 pub fn from_millis_epoch(millis: i64) -> Self {
384 Self(millis)
385 }
386
387 /// Returns unix epoch time in milliseconds.
388 pub fn to_millis_epoch(&self) -> i64 {
389 self.0
390 }
391
392 /// Returns unix epoch time in seconds.
393 pub fn to_secs_epoch(&self) -> i64 {
394 self.0 / 1000
395 }
396}
397
398impl ToSql for DateTime {
399 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
400 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
401 }
402}
403
404impl FromSql for DateTime {
405 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
406 Ok(Self(i64::column_result(value)?))
407 }
408}
409
410impl TryInto<SystemTime> for DateTime {
411 type Error = DateTimeError;
412
413 fn try_into(self) -> Result<SystemTime, Self::Error> {
414 // We want to construct a SystemTime representation equivalent to self, denoting
415 // a point in time THEN, but we cannot set the time directly. We can only construct
416 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
417 // and between EPOCH and THEN. With this common reference we can construct the
418 // duration between NOW and THEN which we can add to our SystemTime representation
419 // of NOW to get a SystemTime representation of THEN.
420 // Durations can only be positive, thus the if statement below.
421 let now = SystemTime::now();
422 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
423 let then_epoch = Duration::from_millis(self.0.try_into()?);
424 Ok(if now_epoch > then_epoch {
425 // then = now - (now_epoch - then_epoch)
426 now_epoch
427 .checked_sub(then_epoch)
428 .and_then(|d| now.checked_sub(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 } else {
431 // then = now + (then_epoch - now_epoch)
432 then_epoch
433 .checked_sub(now_epoch)
434 .and_then(|d| now.checked_add(d))
435 .ok_or(DateTimeError::TimeArithmetic)?
436 })
437 }
438}
439
440impl TryFrom<SystemTime> for DateTime {
441 type Error = DateTimeError;
442
443 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
444 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
445 }
446}
447
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800448#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
449enum KeyLifeCycle {
450 /// Existing keys have a key ID but are not fully populated yet.
451 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
452 /// them to Unreferenced for garbage collection.
453 Existing,
454 /// A live key is fully populated and usable by clients.
455 Live,
456 /// An unreferenced key is scheduled for garbage collection.
457 Unreferenced,
458}
459
460impl ToSql for KeyLifeCycle {
461 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
462 match self {
463 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
464 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
465 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
466 }
467 }
468}
469
470impl FromSql for KeyLifeCycle {
471 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
472 match i64::column_result(value)? {
473 0 => Ok(KeyLifeCycle::Existing),
474 1 => Ok(KeyLifeCycle::Live),
475 2 => Ok(KeyLifeCycle::Unreferenced),
476 v => Err(FromSqlError::OutOfRange(v)),
477 }
478 }
479}
480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700481/// Keys have a KeyMint blob component and optional public certificate and
482/// certificate chain components.
483/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
484/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800485#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700486pub struct KeyEntryLoadBits(u32);
487
488impl KeyEntryLoadBits {
489 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
490 pub const NONE: KeyEntryLoadBits = Self(0);
491 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
492 pub const KM: KeyEntryLoadBits = Self(1);
493 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
494 pub const PUBLIC: KeyEntryLoadBits = Self(2);
495 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
496 pub const BOTH: KeyEntryLoadBits = Self(3);
497
498 /// Returns true if this object indicates that the public components shall be loaded.
499 pub const fn load_public(&self) -> bool {
500 self.0 & Self::PUBLIC.0 != 0
501 }
502
503 /// Returns true if the object indicates that the KeyMint component shall be loaded.
504 pub const fn load_km(&self) -> bool {
505 self.0 & Self::KM.0 != 0
506 }
507}
508
Janis Danisevskisaec14592020-11-12 09:41:49 -0800509lazy_static! {
510 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
511}
512
513struct KeyIdLockDb {
514 locked_keys: Mutex<HashSet<i64>>,
515 cond_var: Condvar,
516}
517
518/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
519/// from the database a second time. Most functions manipulating the key blob database
520/// require a KeyIdGuard.
521#[derive(Debug)]
522pub struct KeyIdGuard(i64);
523
524impl KeyIdLockDb {
525 fn new() -> Self {
526 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
527 }
528
529 /// This function blocks until an exclusive lock for the given key entry id can
530 /// be acquired. It returns a guard object, that represents the lifecycle of the
531 /// acquired lock.
532 pub fn get(&self, key_id: i64) -> KeyIdGuard {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 while locked_keys.contains(&key_id) {
535 locked_keys = self.cond_var.wait(locked_keys).unwrap();
536 }
537 locked_keys.insert(key_id);
538 KeyIdGuard(key_id)
539 }
540
541 /// This function attempts to acquire an exclusive lock on a given key id. If the
542 /// given key id is already taken the function returns None immediately. If a lock
543 /// can be acquired this function returns a guard object, that represents the
544 /// lifecycle of the acquired lock.
545 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
546 let mut locked_keys = self.locked_keys.lock().unwrap();
547 if locked_keys.insert(key_id) {
548 Some(KeyIdGuard(key_id))
549 } else {
550 None
551 }
552 }
553}
554
555impl KeyIdGuard {
556 /// Get the numeric key id of the locked key.
557 pub fn id(&self) -> i64 {
558 self.0
559 }
560}
561
562impl Drop for KeyIdGuard {
563 fn drop(&mut self) {
564 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
565 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800566 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800567 KEY_ID_LOCK.cond_var.notify_all();
568 }
569}
570
Max Bires8e93d2b2021-01-14 13:17:59 -0800571/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700572#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800573pub struct CertificateInfo {
574 cert: Option<Vec<u8>>,
575 cert_chain: Option<Vec<u8>>,
576}
577
578impl CertificateInfo {
579 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
580 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
581 Self { cert, cert_chain }
582 }
583
584 /// Take the cert
585 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
586 self.cert.take()
587 }
588
589 /// Take the cert chain
590 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
591 self.cert_chain.take()
592 }
593}
594
Max Bires2b2e6562020-09-22 11:22:36 -0700595/// This type represents a certificate chain with a private key corresponding to the leaf
596/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
Max Bires2b2e6562020-09-22 11:22:36 -0700597pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800598 /// A KM key blob
599 pub private_key: ZVec,
600 /// A batch cert for private_key
601 pub batch_cert: Vec<u8>,
602 /// A full certificate chain from root signing authority to private_key, including batch_cert
603 /// for convenience.
604 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700605}
606
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700607/// This type represents a Keystore 2.0 key entry.
608/// An entry has a unique `id` by which it can be found in the database.
609/// It has a security level field, key parameters, and three optional fields
610/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800611#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700612pub struct KeyEntry {
613 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800614 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615 cert: Option<Vec<u8>>,
616 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800617 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700618 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800619 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800620 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700621}
622
623impl KeyEntry {
624 /// Returns the unique id of the Key entry.
625 pub fn id(&self) -> i64 {
626 self.id
627 }
628 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800629 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
630 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 /// Extracts the Optional KeyMint blob including its metadata.
633 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
634 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700635 }
636 /// Exposes the optional public certificate.
637 pub fn cert(&self) -> &Option<Vec<u8>> {
638 &self.cert
639 }
640 /// Extracts the optional public certificate.
641 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
642 self.cert.take()
643 }
644 /// Exposes the optional public certificate chain.
645 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
646 &self.cert_chain
647 }
648 /// Extracts the optional public certificate_chain.
649 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
650 self.cert_chain.take()
651 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800652 /// Returns the uuid of the owning KeyMint instance.
653 pub fn km_uuid(&self) -> &Uuid {
654 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700656 /// Exposes the key parameters of this key entry.
657 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
658 &self.parameters
659 }
660 /// Consumes this key entry and extracts the keyparameters from it.
661 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
662 self.parameters
663 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800664 /// Exposes the key metadata of this key entry.
665 pub fn metadata(&self) -> &KeyMetaData {
666 &self.metadata
667 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800668 /// This returns true if the entry is a pure certificate entry with no
669 /// private key component.
670 pub fn pure_cert(&self) -> bool {
671 self.pure_cert
672 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000673 /// Consumes this key entry and extracts the keyparameters and metadata from it.
674 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
675 (self.parameters, self.metadata)
676 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700677}
678
679/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800680#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681pub struct SubComponentType(u32);
682impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800683 /// Persistent identifier for a key blob.
684 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700685 /// Persistent identifier for a certificate blob.
686 pub const CERT: SubComponentType = Self(1);
687 /// Persistent identifier for a certificate chain blob.
688 pub const CERT_CHAIN: SubComponentType = Self(2);
689}
690
691impl ToSql for SubComponentType {
692 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
693 self.0.to_sql()
694 }
695}
696
697impl FromSql for SubComponentType {
698 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
699 Ok(Self(u32::column_result(value)?))
700 }
701}
702
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800703/// This trait is private to the database module. It is used to convey whether or not the garbage
704/// collector shall be invoked after a database access. All closures passed to
705/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
706/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
707/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
708/// `.need_gc()`.
709trait DoGc<T> {
710 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
711
712 fn no_gc(self) -> Result<(bool, T)>;
713
714 fn need_gc(self) -> Result<(bool, T)>;
715}
716
717impl<T> DoGc<T> for Result<T> {
718 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
719 self.map(|r| (need_gc, r))
720 }
721
722 fn no_gc(self) -> Result<(bool, T)> {
723 self.do_gc(false)
724 }
725
726 fn need_gc(self) -> Result<(bool, T)> {
727 self.do_gc(true)
728 }
729}
730
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700731/// KeystoreDB wraps a connection to an SQLite database and tracks its
732/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700733pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700734 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700735 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700736 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700737}
738
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000739/// Database representation of the monotonic time retrieved from the system call clock_gettime with
740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
741#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
742pub struct MonotonicRawTime(i64);
743
744impl MonotonicRawTime {
745 /// Constructs a new MonotonicRawTime
746 pub fn now() -> Self {
747 Self(get_current_time_in_seconds())
748 }
749
David Drysdale0e45a612021-02-25 17:24:36 +0000750 /// Constructs a new MonotonicRawTime from a given number of seconds.
751 pub fn from_secs(val: i64) -> Self {
752 Self(val)
753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
757 self.0
758 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800759
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000760 /// Returns the value of MonotonicRawTime in milli seconds as i64
761 pub fn milli_seconds(&self) -> i64 {
762 self.0 * 1000
763 }
764
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800765 /// Like i64::checked_sub.
766 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
767 self.0.checked_sub(other.0).map(Self)
768 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000769}
770
771impl ToSql for MonotonicRawTime {
772 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
773 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
774 }
775}
776
777impl FromSql for MonotonicRawTime {
778 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
779 Ok(Self(i64::column_result(value)?))
780 }
781}
782
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000783/// This struct encapsulates the information to be stored in the database about the auth tokens
784/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700785#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000786pub struct AuthTokenEntry {
787 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000789}
790
791impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000792 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000793 AuthTokenEntry { auth_token, time_received }
794 }
795
796 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800797 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000798 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800799 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
800 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000801 })
802 }
803
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000804 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800805 pub fn auth_token(&self) -> &HardwareAuthToken {
806 &self.auth_token
807 }
808
809 /// Returns the auth token wrapped by the AuthTokenEntry
810 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000811 self.auth_token
812 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800813
814 /// Returns the time that this auth token was received.
815 pub fn time_received(&self) -> MonotonicRawTime {
816 self.time_received
817 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000818
819 /// Returns the challenge value of the auth token.
820 pub fn challenge(&self) -> i64 {
821 self.auth_token.challenge
822 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000823}
824
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800825/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
826/// This object does not allow access to the database connection. But it keeps a database
827/// connection alive in order to keep the in memory per boot database alive.
828pub struct PerBootDbKeepAlive(Connection);
829
Joel Galenson26f4d012020-07-17 14:57:21 -0700830impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800831 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800832
Seth Moore78c091f2021-04-09 21:38:30 +0000833 /// Name of the file that holds the cross-boot persistent database.
834 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
835
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700836 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800837 /// files persistent.sqlite and perboot.sqlite in the given directory.
838 /// It also attempts to initialize all of the tables.
839 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700840 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700841 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700842 let _wp = wd::watch_millis("KeystoreDB::new", 500);
843
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800844 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800845 let mut persistent_path = db_root.to_path_buf();
Seth Moore78c091f2021-04-09 21:38:30 +0000846 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700847
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800848 // Now convert them to strings prefixed with "file:"
849 let mut persistent_path_str = "file:".to_owned();
850 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800851
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700852 let conn = Self::make_connection(&persistent_path_str)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800853
Janis Danisevskis66784c42021-01-27 08:40:25 -0800854 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
855 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
856
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700857 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800858 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800859 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800860 })?;
861 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700862 }
863
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 fn init_tables(tx: &Transaction) -> Result<()> {
865 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700866 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700867 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800868 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700869 domain INTEGER,
870 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800871 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800872 state INTEGER,
873 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700874 NO_PARAMS,
875 )
876 .context("Failed to initialize \"keyentry\" table.")?;
877
Janis Danisevskis66784c42021-01-27 08:40:25 -0800878 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800879 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
880 ON keyentry(id);",
881 NO_PARAMS,
882 )
883 .context("Failed to create index keyentry_id_index.")?;
884
885 tx.execute(
886 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
887 ON keyentry(domain, namespace, alias);",
888 NO_PARAMS,
889 )
890 .context("Failed to create index keyentry_domain_namespace_index.")?;
891
892 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700893 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
894 id INTEGER PRIMARY KEY,
895 subcomponent_type INTEGER,
896 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800897 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700898 NO_PARAMS,
899 )
900 .context("Failed to initialize \"blobentry\" table.")?;
901
Janis Danisevskis66784c42021-01-27 08:40:25 -0800902 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800903 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
904 ON blobentry(keyentryid);",
905 NO_PARAMS,
906 )
907 .context("Failed to create index blobentry_keyentryid_index.")?;
908
909 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800910 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
911 id INTEGER PRIMARY KEY,
912 blobentryid INTEGER,
913 tag INTEGER,
914 data ANY,
915 UNIQUE (blobentryid, tag));",
916 NO_PARAMS,
917 )
918 .context("Failed to initialize \"blobmetadata\" table.")?;
919
920 tx.execute(
921 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
922 ON blobmetadata(blobentryid);",
923 NO_PARAMS,
924 )
925 .context("Failed to create index blobmetadata_blobentryid_index.")?;
926
927 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700928 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000929 keyentryid INTEGER,
930 tag INTEGER,
931 data ANY,
932 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700933 NO_PARAMS,
934 )
935 .context("Failed to initialize \"keyparameter\" table.")?;
936
Janis Danisevskis66784c42021-01-27 08:40:25 -0800937 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800938 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
939 ON keyparameter(keyentryid);",
940 NO_PARAMS,
941 )
942 .context("Failed to create index keyparameter_keyentryid_index.")?;
943
944 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800945 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
946 keyentryid INTEGER,
947 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000948 data ANY,
949 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800950 NO_PARAMS,
951 )
952 .context("Failed to initialize \"keymetadata\" table.")?;
953
Janis Danisevskis66784c42021-01-27 08:40:25 -0800954 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800955 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
956 ON keymetadata(keyentryid);",
957 NO_PARAMS,
958 )
959 .context("Failed to create index keymetadata_keyentryid_index.")?;
960
961 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800962 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700963 id INTEGER UNIQUE,
964 grantee INTEGER,
965 keyentryid INTEGER,
966 access_vector INTEGER);",
967 NO_PARAMS,
968 )
969 .context("Failed to initialize \"grant\" table.")?;
970
Joel Galenson0891bc12020-07-20 10:37:03 -0700971 Ok(())
972 }
973
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700974 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700975 let conn =
976 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
977
Janis Danisevskis66784c42021-01-27 08:40:25 -0800978 loop {
979 if let Err(e) = conn
980 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
981 .context("Failed to attach database persistent.")
982 {
983 if Self::is_locked_error(&e) {
984 std::thread::sleep(std::time::Duration::from_micros(500));
985 continue;
986 } else {
987 return Err(e);
988 }
989 }
990 break;
991 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700992
Matthew Maurer4fb19112021-05-06 15:40:44 -0700993 // Drop the cache size from default (2M) to 0.5M
994 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
995 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -0700996
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700997 Ok(conn)
998 }
999
Seth Moore78c091f2021-04-09 21:38:30 +00001000 fn do_table_size_query(
1001 &mut self,
1002 storage_type: StatsdStorageType,
1003 query: &str,
1004 params: &[&str],
1005 ) -> Result<Keystore2StorageStats> {
1006 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1007 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1008 .with_context(|| {
1009 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1010 })
1011 .no_gc()
1012 })?;
1013 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1014 }
1015
1016 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1017 self.do_table_size_query(
1018 StatsdStorageType::Database,
1019 "SELECT page_count * page_size, freelist_count * page_size
1020 FROM pragma_page_count('persistent'),
1021 pragma_page_size('persistent'),
1022 persistent.pragma_freelist_count();",
1023 &[],
1024 )
1025 }
1026
1027 fn get_table_size(
1028 &mut self,
1029 storage_type: StatsdStorageType,
1030 schema: &str,
1031 table: &str,
1032 ) -> Result<Keystore2StorageStats> {
1033 self.do_table_size_query(
1034 storage_type,
1035 "SELECT pgsize,unused FROM dbstat(?1)
1036 WHERE name=?2 AND aggregate=TRUE;",
1037 &[schema, table],
1038 )
1039 }
1040
1041 /// Fetches a storage statisitics atom for a given storage type. For storage
1042 /// types that map to a table, information about the table's storage is
1043 /// returned. Requests for storage types that are not DB tables return None.
1044 pub fn get_storage_stat(
1045 &mut self,
1046 storage_type: StatsdStorageType,
1047 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001048 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1049
Seth Moore78c091f2021-04-09 21:38:30 +00001050 match storage_type {
1051 StatsdStorageType::Database => self.get_total_size(),
1052 StatsdStorageType::KeyEntry => {
1053 self.get_table_size(storage_type, "persistent", "keyentry")
1054 }
1055 StatsdStorageType::KeyEntryIdIndex => {
1056 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1057 }
1058 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1059 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1060 }
1061 StatsdStorageType::BlobEntry => {
1062 self.get_table_size(storage_type, "persistent", "blobentry")
1063 }
1064 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1065 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1066 }
1067 StatsdStorageType::KeyParameter => {
1068 self.get_table_size(storage_type, "persistent", "keyparameter")
1069 }
1070 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1071 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1072 }
1073 StatsdStorageType::KeyMetadata => {
1074 self.get_table_size(storage_type, "persistent", "keymetadata")
1075 }
1076 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1077 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1078 }
1079 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1080 StatsdStorageType::AuthToken => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001081 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1082 // reportable
1083 // Size provided is only an approximation
1084 Ok(Keystore2StorageStats {
1085 storage_type,
1086 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1087 as i64,
1088 unused_size: 0,
1089 })
Seth Moore78c091f2021-04-09 21:38:30 +00001090 }
1091 StatsdStorageType::BlobMetadata => {
1092 self.get_table_size(storage_type, "persistent", "blobmetadata")
1093 }
1094 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1095 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1096 }
1097 _ => Err(anyhow::Error::msg(format!(
1098 "Unsupported storage type: {}",
1099 storage_type as i32
1100 ))),
1101 }
1102 }
1103
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001104 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001105 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1106 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001107 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1108 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001109 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001110 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001111 blob_ids_to_delete: &[i64],
1112 max_blobs: usize,
1113 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001114 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001115 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001116 // Delete the given blobs.
1117 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001118 tx.execute(
1119 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001120 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001121 )
1122 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001123 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1124 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001125 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001126
1127 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1128
Janis Danisevskis3395f862021-05-06 10:54:17 -07001129 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1130 let result: Vec<(i64, Vec<u8>)> = {
1131 let mut stmt = tx
1132 .prepare(
1133 "SELECT id, blob FROM persistent.blobentry
1134 WHERE subcomponent_type = ?
1135 AND (
1136 id NOT IN (
1137 SELECT MAX(id) FROM persistent.blobentry
1138 WHERE subcomponent_type = ?
1139 GROUP BY keyentryid, subcomponent_type
1140 )
1141 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1142 ) LIMIT ?;",
1143 )
1144 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001145
Janis Danisevskis3395f862021-05-06 10:54:17 -07001146 let rows = stmt
1147 .query_map(
1148 params![
1149 SubComponentType::KEY_BLOB,
1150 SubComponentType::KEY_BLOB,
1151 max_blobs as i64,
1152 ],
1153 |row| Ok((row.get(0)?, row.get(1)?)),
1154 )
1155 .context("Trying to query superseded blob.")?;
1156
1157 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1158 .context("Trying to extract superseded blobs.")?
1159 };
1160
1161 let result = result
1162 .into_iter()
1163 .map(|(blob_id, blob)| {
1164 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1165 })
1166 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1167 .context("Trying to load blob metadata.")?;
1168 if !result.is_empty() {
1169 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001170 }
1171
1172 // We did not find any superseded key blob, so let's remove other superseded blob in
1173 // one transaction.
1174 tx.execute(
1175 "DELETE FROM persistent.blobentry
1176 WHERE NOT subcomponent_type = ?
1177 AND (
1178 id NOT IN (
1179 SELECT MAX(id) FROM persistent.blobentry
1180 WHERE NOT subcomponent_type = ?
1181 GROUP BY keyentryid, subcomponent_type
1182 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1183 );",
1184 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1185 )
1186 .context("Trying to purge superseded blobs.")?;
1187
Janis Danisevskis3395f862021-05-06 10:54:17 -07001188 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001189 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001190 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001191 }
1192
1193 /// This maintenance function should be called only once before the database is used for the
1194 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1195 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1196 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1197 /// Keystore crashed at some point during key generation. Callers may want to log such
1198 /// occurrences.
1199 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1200 /// it to `KeyLifeCycle::Live` may have grants.
1201 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001202 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1203
Janis Danisevskis66784c42021-01-27 08:40:25 -08001204 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1205 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001206 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1207 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1208 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001209 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001210 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001211 })
1212 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001213 }
1214
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001215 /// Checks if a key exists with given key type and key descriptor properties.
1216 pub fn key_exists(
1217 &mut self,
1218 domain: Domain,
1219 nspace: i64,
1220 alias: &str,
1221 key_type: KeyType,
1222 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001223 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1224
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001225 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1226 let key_descriptor =
1227 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1228 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1229 match result {
1230 Ok(_) => Ok(true),
1231 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1232 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1233 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1234 },
1235 }
1236 .no_gc()
1237 })
1238 .context("In key_exists.")
1239 }
1240
Hasini Gunasingheda895552021-01-27 19:34:37 +00001241 /// Stores a super key in the database.
1242 pub fn store_super_key(
1243 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001244 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001245 key_type: &SuperKeyType,
1246 blob: &[u8],
1247 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001248 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001249 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001250 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1251
Hasini Gunasingheda895552021-01-27 19:34:37 +00001252 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1253 let key_id = Self::insert_with_retry(|id| {
1254 tx.execute(
1255 "INSERT into persistent.keyentry
1256 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001257 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001258 params![
1259 id,
1260 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001261 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001262 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001263 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001264 KeyLifeCycle::Live,
1265 &KEYSTORE_UUID,
1266 ],
1267 )
1268 })
1269 .context("Failed to insert into keyentry table.")?;
1270
Paul Crowley8d5b2532021-03-19 10:53:07 -07001271 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1272
Hasini Gunasingheda895552021-01-27 19:34:37 +00001273 Self::set_blob_internal(
1274 &tx,
1275 key_id,
1276 SubComponentType::KEY_BLOB,
1277 Some(blob),
1278 Some(blob_metadata),
1279 )
1280 .context("Failed to store key blob.")?;
1281
1282 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1283 .context("Trying to load key components.")
1284 .no_gc()
1285 })
1286 .context("In store_super_key.")
1287 }
1288
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001289 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001290 pub fn load_super_key(
1291 &mut self,
1292 key_type: &SuperKeyType,
1293 user_id: u32,
1294 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001295 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1296
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001297 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1298 let key_descriptor = KeyDescriptor {
1299 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001300 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001301 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001302 blob: None,
1303 };
1304 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1305 match id {
1306 Ok(id) => {
1307 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1308 .context("In load_super_key. Failed to load key entry.")?;
1309 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1310 }
1311 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1312 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1313 _ => Err(error).context("In load_super_key."),
1314 },
1315 }
1316 .no_gc()
1317 })
1318 .context("In load_super_key.")
1319 }
1320
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001321 /// Atomically loads a key entry and associated metadata or creates it using the
1322 /// callback create_new_key callback. The callback is called during a database
1323 /// transaction. This means that implementers should be mindful about using
1324 /// blocking operations such as IPC or grabbing mutexes.
1325 pub fn get_or_create_key_with<F>(
1326 &mut self,
1327 domain: Domain,
1328 namespace: i64,
1329 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001330 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001331 create_new_key: F,
1332 ) -> Result<(KeyIdGuard, KeyEntry)>
1333 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001334 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001335 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001336 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1337
Janis Danisevskis66784c42021-01-27 08:40:25 -08001338 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1339 let id = {
1340 let mut stmt = tx
1341 .prepare(
1342 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001343 WHERE
1344 key_type = ?
1345 AND domain = ?
1346 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001347 AND alias = ?
1348 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001349 )
1350 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1351 let mut rows = stmt
1352 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1353 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001354
Janis Danisevskis66784c42021-01-27 08:40:25 -08001355 db_utils::with_rows_extract_one(&mut rows, |row| {
1356 Ok(match row {
1357 Some(r) => r.get(0).context("Failed to unpack id.")?,
1358 None => None,
1359 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001360 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001361 .context("In get_or_create_key_with.")?
1362 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001363
Janis Danisevskis66784c42021-01-27 08:40:25 -08001364 let (id, entry) = match id {
1365 Some(id) => (
1366 id,
1367 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1368 .context("In get_or_create_key_with.")?,
1369 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001370
Janis Danisevskis66784c42021-01-27 08:40:25 -08001371 None => {
1372 let id = Self::insert_with_retry(|id| {
1373 tx.execute(
1374 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001375 (id, key_type, domain, namespace, alias, state, km_uuid)
1376 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001377 params![
1378 id,
1379 KeyType::Super,
1380 domain.0,
1381 namespace,
1382 alias,
1383 KeyLifeCycle::Live,
1384 km_uuid,
1385 ],
1386 )
1387 })
1388 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001389
Janis Danisevskis66784c42021-01-27 08:40:25 -08001390 let (blob, metadata) =
1391 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001392 Self::set_blob_internal(
1393 &tx,
1394 id,
1395 SubComponentType::KEY_BLOB,
1396 Some(&blob),
1397 Some(&metadata),
1398 )
Paul Crowley7a658392021-03-18 17:08:20 -07001399 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001401 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001402 KeyEntry {
1403 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001404 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001405 pure_cert: false,
1406 ..Default::default()
1407 },
1408 )
1409 }
1410 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001411 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 })
1413 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001414 }
1415
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1417 /// waiting for the database file to become available. This makes it
1418 /// impossible to successfully recover from a locked database when the
1419 /// transaction holding the device busy is in the same process on a
1420 /// different connection. As a result the busy handler has to time out and
1421 /// fail in order to make progress.
1422 ///
1423 /// Instead, we set the busy handler to None (return immediately). And catch
1424 /// Busy and Locked errors (the latter occur on in memory databases with
1425 /// shared cache, e.g., the per-boot database.) and restart the transaction
1426 /// after a grace period of half a millisecond.
1427 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001428 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001429 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1430 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001431 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1432 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001433 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001434 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001435 loop {
1436 match self
1437 .conn
1438 .transaction_with_behavior(behavior)
1439 .context("In with_transaction.")
1440 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1441 .and_then(|(result, tx)| {
1442 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1443 Ok(result)
1444 }) {
1445 Ok(result) => break Ok(result),
1446 Err(e) => {
1447 if Self::is_locked_error(&e) {
1448 std::thread::sleep(std::time::Duration::from_micros(500));
1449 continue;
1450 } else {
1451 return Err(e).context("In with_transaction.");
1452 }
1453 }
1454 }
1455 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001456 .map(|(need_gc, result)| {
1457 if need_gc {
1458 if let Some(ref gc) = self.gc {
1459 gc.notify_gc();
1460 }
1461 }
1462 result
1463 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001464 }
1465
1466 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001467 matches!(
1468 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1469 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1470 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1471 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001472 }
1473
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001474 /// Creates a new key entry and allocates a new randomized id for the new key.
1475 /// The key id gets associated with a domain and namespace but not with an alias.
1476 /// To complete key generation `rebind_alias` should be called after all of the
1477 /// key artifacts, i.e., blobs and parameters have been associated with the new
1478 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1479 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001480 pub fn create_key_entry(
1481 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001482 domain: &Domain,
1483 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001484 km_uuid: &Uuid,
1485 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001486 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1487
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001488 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001489 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001490 })
1491 .context("In create_key_entry.")
1492 }
1493
1494 fn create_key_entry_internal(
1495 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001496 domain: &Domain,
1497 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001498 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001499 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001500 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001501 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001502 _ => {
1503 return Err(KsError::sys())
1504 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1505 }
1506 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001507 Ok(KEY_ID_LOCK.get(
1508 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001509 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001510 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001511 (id, key_type, domain, namespace, alias, state, km_uuid)
1512 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001513 params![
1514 id,
1515 KeyType::Client,
1516 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001517 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001518 KeyLifeCycle::Existing,
1519 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001520 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001521 )
1522 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001523 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001524 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001525 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001526
Max Bires2b2e6562020-09-22 11:22:36 -07001527 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1528 /// The key id gets associated with a domain and namespace later but not with an alias. The
1529 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1530 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1531 /// a key.
1532 pub fn create_attestation_key_entry(
1533 &mut self,
1534 maced_public_key: &[u8],
1535 raw_public_key: &[u8],
1536 private_key: &[u8],
1537 km_uuid: &Uuid,
1538 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001539 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1540
Max Bires2b2e6562020-09-22 11:22:36 -07001541 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1542 let key_id = KEY_ID_LOCK.get(
1543 Self::insert_with_retry(|id| {
1544 tx.execute(
1545 "INSERT into persistent.keyentry
1546 (id, key_type, domain, namespace, alias, state, km_uuid)
1547 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1548 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1549 )
1550 })
1551 .context("In create_key_entry")?,
1552 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001553 Self::set_blob_internal(
1554 &tx,
1555 key_id.0,
1556 SubComponentType::KEY_BLOB,
1557 Some(private_key),
1558 None,
1559 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001560 let mut metadata = KeyMetaData::new();
1561 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1562 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1563 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001564 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001565 })
1566 .context("In create_attestation_key_entry")
1567 }
1568
Janis Danisevskis377d1002021-01-27 19:07:48 -08001569 /// Set a new blob and associates it with the given key id. Each blob
1570 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001571 /// Each key can have one of each sub component type associated. If more
1572 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001573 /// will get garbage collected.
1574 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1575 /// removed by setting blob to None.
1576 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001577 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001578 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001579 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001580 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001581 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001582 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001583 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1584
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001585 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001586 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001587 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001588 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001589 }
1590
Janis Danisevskiseed69842021-02-18 20:04:10 -08001591 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1592 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1593 /// We use this to insert key blobs into the database which can then be garbage collected
1594 /// lazily by the key garbage collector.
1595 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001596 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1597
Janis Danisevskiseed69842021-02-18 20:04:10 -08001598 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1599 Self::set_blob_internal(
1600 &tx,
1601 Self::UNASSIGNED_KEY_ID,
1602 SubComponentType::KEY_BLOB,
1603 Some(blob),
1604 Some(blob_metadata),
1605 )
1606 .need_gc()
1607 })
1608 .context("In set_deleted_blob.")
1609 }
1610
Janis Danisevskis377d1002021-01-27 19:07:48 -08001611 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001612 tx: &Transaction,
1613 key_id: i64,
1614 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001615 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001616 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001617 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001618 match (blob, sc_type) {
1619 (Some(blob), _) => {
1620 tx.execute(
1621 "INSERT INTO persistent.blobentry
1622 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1623 params![sc_type, key_id, blob],
1624 )
1625 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001626 if let Some(blob_metadata) = blob_metadata {
1627 let blob_id = tx
1628 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1629 row.get(0)
1630 })
1631 .context("In set_blob_internal: Failed to get new blob id.")?;
1632 blob_metadata
1633 .store_in_db(blob_id, tx)
1634 .context("In set_blob_internal: Trying to store blob metadata.")?;
1635 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001636 }
1637 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1638 tx.execute(
1639 "DELETE FROM persistent.blobentry
1640 WHERE subcomponent_type = ? AND keyentryid = ?;",
1641 params![sc_type, key_id],
1642 )
1643 .context("In set_blob_internal: Failed to delete blob.")?;
1644 }
1645 (None, _) => {
1646 return Err(KsError::sys())
1647 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1648 }
1649 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001650 Ok(())
1651 }
1652
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001653 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1654 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001655 #[cfg(test)]
1656 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001657 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001658 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001659 })
1660 .context("In insert_keyparameter.")
1661 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001662
Janis Danisevskis66784c42021-01-27 08:40:25 -08001663 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001664 tx: &Transaction,
1665 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001666 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001667 ) -> Result<()> {
1668 let mut stmt = tx
1669 .prepare(
1670 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1671 VALUES (?, ?, ?, ?);",
1672 )
1673 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1674
Janis Danisevskis66784c42021-01-27 08:40:25 -08001675 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001676 stmt.insert(params![
1677 key_id.0,
1678 p.get_tag().0,
1679 p.key_parameter_value(),
1680 p.security_level().0
1681 ])
1682 .with_context(|| {
1683 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1684 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001685 }
1686 Ok(())
1687 }
1688
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001689 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001690 #[cfg(test)]
1691 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001692 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001693 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001694 })
1695 .context("In insert_key_metadata.")
1696 }
1697
Max Bires2b2e6562020-09-22 11:22:36 -07001698 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1699 /// on the public key.
1700 pub fn store_signed_attestation_certificate_chain(
1701 &mut self,
1702 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001703 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001704 cert_chain: &[u8],
1705 expiration_date: i64,
1706 km_uuid: &Uuid,
1707 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001708 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1709
Max Bires2b2e6562020-09-22 11:22:36 -07001710 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1711 let mut stmt = tx
1712 .prepare(
1713 "SELECT keyentryid
1714 FROM persistent.keymetadata
1715 WHERE tag = ? AND data = ? AND keyentryid IN
1716 (SELECT id
1717 FROM persistent.keyentry
1718 WHERE
1719 alias IS NULL AND
1720 domain IS NULL AND
1721 namespace IS NULL AND
1722 key_type = ? AND
1723 km_uuid = ?);",
1724 )
1725 .context("Failed to store attestation certificate chain.")?;
1726 let mut rows = stmt
1727 .query(params![
1728 KeyMetaData::AttestationRawPubKey,
1729 raw_public_key,
1730 KeyType::Attestation,
1731 km_uuid
1732 ])
1733 .context("Failed to fetch keyid")?;
1734 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1735 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1736 .get(0)
1737 .context("Failed to unpack id.")
1738 })
1739 .context("Failed to get key_id.")?;
1740 let num_updated = tx
1741 .execute(
1742 "UPDATE persistent.keyentry
1743 SET alias = ?
1744 WHERE id = ?;",
1745 params!["signed", key_id],
1746 )
1747 .context("Failed to update alias.")?;
1748 if num_updated != 1 {
1749 return Err(KsError::sys()).context("Alias not updated for the key.");
1750 }
1751 let mut metadata = KeyMetaData::new();
1752 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1753 expiration_date,
1754 )));
1755 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001756 Self::set_blob_internal(
1757 &tx,
1758 key_id,
1759 SubComponentType::CERT_CHAIN,
1760 Some(cert_chain),
1761 None,
1762 )
1763 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001764 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1765 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001766 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001767 })
1768 .context("In store_signed_attestation_certificate_chain: ")
1769 }
1770
1771 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1772 /// currently have a key assigned to it.
1773 pub fn assign_attestation_key(
1774 &mut self,
1775 domain: Domain,
1776 namespace: i64,
1777 km_uuid: &Uuid,
1778 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001779 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1780
Max Bires2b2e6562020-09-22 11:22:36 -07001781 match domain {
1782 Domain::APP | Domain::SELINUX => {}
1783 _ => {
1784 return Err(KsError::sys()).context(format!(
1785 concat!(
1786 "In assign_attestation_key: Domain {:?} ",
1787 "must be either App or SELinux.",
1788 ),
1789 domain
1790 ));
1791 }
1792 }
1793 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1794 let result = tx
1795 .execute(
1796 "UPDATE persistent.keyentry
1797 SET domain=?1, namespace=?2
1798 WHERE
1799 id =
1800 (SELECT MIN(id)
1801 FROM persistent.keyentry
1802 WHERE ALIAS IS NOT NULL
1803 AND domain IS NULL
1804 AND key_type IS ?3
1805 AND state IS ?4
1806 AND km_uuid IS ?5)
1807 AND
1808 (SELECT COUNT(*)
1809 FROM persistent.keyentry
1810 WHERE domain=?1
1811 AND namespace=?2
1812 AND key_type IS ?3
1813 AND state IS ?4
1814 AND km_uuid IS ?5) = 0;",
1815 params![
1816 domain.0 as u32,
1817 namespace,
1818 KeyType::Attestation,
1819 KeyLifeCycle::Live,
1820 km_uuid,
1821 ],
1822 )
1823 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001824 if result == 0 {
1825 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1826 } else if result > 1 {
1827 return Err(KsError::sys())
1828 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001829 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001830 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001831 })
1832 .context("In assign_attestation_key: ")
1833 }
1834
1835 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1836 /// provisioning server, or the maximum number available if there are not num_keys number of
1837 /// entries in the table.
1838 pub fn fetch_unsigned_attestation_keys(
1839 &mut self,
1840 num_keys: i32,
1841 km_uuid: &Uuid,
1842 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001843 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1844
Max Bires2b2e6562020-09-22 11:22:36 -07001845 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1846 let mut stmt = tx
1847 .prepare(
1848 "SELECT data
1849 FROM persistent.keymetadata
1850 WHERE tag = ? AND keyentryid IN
1851 (SELECT id
1852 FROM persistent.keyentry
1853 WHERE
1854 alias IS NULL AND
1855 domain IS NULL AND
1856 namespace IS NULL AND
1857 key_type = ? AND
1858 km_uuid = ?
1859 LIMIT ?);",
1860 )
1861 .context("Failed to prepare statement")?;
1862 let rows = stmt
1863 .query_map(
1864 params![
1865 KeyMetaData::AttestationMacedPublicKey,
1866 KeyType::Attestation,
1867 km_uuid,
1868 num_keys
1869 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001870 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001871 )?
1872 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1873 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001874 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001875 })
1876 .context("In fetch_unsigned_attestation_keys")
1877 }
1878
1879 /// Removes any keys that have expired as of the current time. Returns the number of keys
1880 /// marked unreferenced that are bound to be garbage collected.
1881 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001882 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1883
Max Bires2b2e6562020-09-22 11:22:36 -07001884 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1885 let mut stmt = tx
1886 .prepare(
1887 "SELECT keyentryid, data
1888 FROM persistent.keymetadata
1889 WHERE tag = ? AND keyentryid IN
1890 (SELECT id
1891 FROM persistent.keyentry
1892 WHERE key_type = ?);",
1893 )
1894 .context("Failed to prepare query")?;
1895 let key_ids_to_check = stmt
1896 .query_map(
1897 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1898 |row| Ok((row.get(0)?, row.get(1)?)),
1899 )?
1900 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1901 .context("Failed to get date metadata")?;
1902 let curr_time = DateTime::from_millis_epoch(
1903 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1904 );
1905 let mut num_deleted = 0;
1906 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1907 if Self::mark_unreferenced(&tx, id)? {
1908 num_deleted += 1;
1909 }
1910 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001911 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001912 })
1913 .context("In delete_expired_attestation_keys: ")
1914 }
1915
Max Bires60d7ed12021-03-05 15:59:22 -08001916 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1917 /// they are in. This is useful primarily as a testing mechanism.
1918 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001919 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1920
Max Bires60d7ed12021-03-05 15:59:22 -08001921 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1922 let mut stmt = tx
1923 .prepare(
1924 "SELECT id FROM persistent.keyentry
1925 WHERE key_type IS ?;",
1926 )
1927 .context("Failed to prepare statement")?;
1928 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001929 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001930 .collect::<rusqlite::Result<Vec<i64>>>()
1931 .context("Failed to execute statement")?;
1932 let num_deleted = keys_to_delete
1933 .iter()
1934 .map(|id| Self::mark_unreferenced(&tx, *id))
1935 .collect::<Result<Vec<bool>>>()
1936 .context("Failed to execute mark_unreferenced on a keyid")?
1937 .into_iter()
1938 .filter(|result| *result)
1939 .count() as i64;
1940 Ok(num_deleted).do_gc(num_deleted != 0)
1941 })
1942 .context("In delete_all_attestation_keys: ")
1943 }
1944
Max Bires2b2e6562020-09-22 11:22:36 -07001945 /// Counts the number of keys that will expire by the provided epoch date and the number of
1946 /// keys not currently assigned to a domain.
1947 pub fn get_attestation_pool_status(
1948 &mut self,
1949 date: i64,
1950 km_uuid: &Uuid,
1951 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001952 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1953
Max Bires2b2e6562020-09-22 11:22:36 -07001954 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1955 let mut stmt = tx.prepare(
1956 "SELECT data
1957 FROM persistent.keymetadata
1958 WHERE tag = ? AND keyentryid IN
1959 (SELECT id
1960 FROM persistent.keyentry
1961 WHERE alias IS NOT NULL
1962 AND key_type = ?
1963 AND km_uuid = ?
1964 AND state = ?);",
1965 )?;
1966 let times = stmt
1967 .query_map(
1968 params![
1969 KeyMetaData::AttestationExpirationDate,
1970 KeyType::Attestation,
1971 km_uuid,
1972 KeyLifeCycle::Live
1973 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001974 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001975 )?
1976 .collect::<rusqlite::Result<Vec<DateTime>>>()
1977 .context("Failed to execute metadata statement")?;
1978 let expiring =
1979 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1980 as i32;
1981 stmt = tx.prepare(
1982 "SELECT alias, domain
1983 FROM persistent.keyentry
1984 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1985 )?;
1986 let rows = stmt
1987 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1988 Ok((row.get(0)?, row.get(1)?))
1989 })?
1990 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1991 .context("Failed to execute keyentry statement")?;
1992 let mut unassigned = 0i32;
1993 let mut attested = 0i32;
1994 let total = rows.len() as i32;
1995 for (alias, domain) in rows {
1996 match (alias, domain) {
1997 (Some(_alias), None) => {
1998 attested += 1;
1999 unassigned += 1;
2000 }
2001 (Some(_alias), Some(_domain)) => {
2002 attested += 1;
2003 }
2004 _ => {}
2005 }
2006 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002007 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002008 })
2009 .context("In get_attestation_pool_status: ")
2010 }
2011
2012 /// Fetches the private key and corresponding certificate chain assigned to a
2013 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2014 /// not assigned, or one CertificateChain.
2015 pub fn retrieve_attestation_key_and_cert_chain(
2016 &mut self,
2017 domain: Domain,
2018 namespace: i64,
2019 km_uuid: &Uuid,
2020 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002021 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2022
Max Bires2b2e6562020-09-22 11:22:36 -07002023 match domain {
2024 Domain::APP | Domain::SELINUX => {}
2025 _ => {
2026 return Err(KsError::sys())
2027 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2028 }
2029 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002030 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2031 let mut stmt = tx.prepare(
2032 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002033 FROM persistent.blobentry
2034 WHERE keyentryid IN
2035 (SELECT id
2036 FROM persistent.keyentry
2037 WHERE key_type = ?
2038 AND domain = ?
2039 AND namespace = ?
2040 AND state = ?
2041 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002042 )?;
2043 let rows = stmt
2044 .query_map(
2045 params![
2046 KeyType::Attestation,
2047 domain.0 as u32,
2048 namespace,
2049 KeyLifeCycle::Live,
2050 km_uuid
2051 ],
2052 |row| Ok((row.get(0)?, row.get(1)?)),
2053 )?
2054 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002055 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002056 if rows.is_empty() {
2057 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002058 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002059 return Err(KsError::sys()).context(format!(
2060 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002061 "Expected to get a single attestation",
2062 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2063 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002064 rows.len()
2065 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002066 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002067 let mut km_blob: Vec<u8> = Vec::new();
2068 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002069 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002070 for row in rows {
2071 let sub_type: SubComponentType = row.0;
2072 match sub_type {
2073 SubComponentType::KEY_BLOB => {
2074 km_blob = row.1;
2075 }
2076 SubComponentType::CERT_CHAIN => {
2077 cert_chain_blob = row.1;
2078 }
Max Biresb2e1d032021-02-08 21:35:05 -08002079 SubComponentType::CERT => {
2080 batch_cert_blob = row.1;
2081 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2083 }
2084 }
2085 Ok(Some(CertificateChain {
2086 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002087 batch_cert: batch_cert_blob,
2088 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002089 }))
2090 .no_gc()
2091 })
Max Biresb2e1d032021-02-08 21:35:05 -08002092 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002093 }
2094
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002095 /// Updates the alias column of the given key id `newid` with the given alias,
2096 /// and atomically, removes the alias, domain, and namespace from another row
2097 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002098 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2099 /// collector.
2100 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002101 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002102 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002103 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002104 domain: &Domain,
2105 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002106 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002107 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002108 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002109 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002110 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002111 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002112 domain
2113 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002114 }
2115 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002116 let updated = tx
2117 .execute(
2118 "UPDATE persistent.keyentry
2119 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002120 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002121 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2122 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002123 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002124 let result = tx
2125 .execute(
2126 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 SET alias = ?, state = ?
2128 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2129 params![
2130 alias,
2131 KeyLifeCycle::Live,
2132 newid.0,
2133 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002134 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002135 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002136 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002137 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002138 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002139 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002140 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002141 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002142 result
2143 ));
2144 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002145 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002146 }
2147
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002148 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2149 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2150 pub fn migrate_key_namespace(
2151 &mut self,
2152 key_id_guard: KeyIdGuard,
2153 destination: &KeyDescriptor,
2154 caller_uid: u32,
2155 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2156 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002157 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2158
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002159 let destination = match destination.domain {
2160 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2161 Domain::SELINUX => (*destination).clone(),
2162 domain => {
2163 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2164 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2165 }
2166 };
2167
2168 // Security critical: Must return immediately on failure. Do not remove the '?';
2169 check_permission(&destination)
2170 .context("In migrate_key_namespace: Trying to check permission.")?;
2171
2172 let alias = destination
2173 .alias
2174 .as_ref()
2175 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2176 .context("In migrate_key_namespace: Alias must be specified.")?;
2177
2178 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2179 // Query the destination location. If there is a key, the migration request fails.
2180 if tx
2181 .query_row(
2182 "SELECT id FROM persistent.keyentry
2183 WHERE alias = ? AND domain = ? AND namespace = ?;",
2184 params![alias, destination.domain.0, destination.nspace],
2185 |_| Ok(()),
2186 )
2187 .optional()
2188 .context("Failed to query destination.")?
2189 .is_some()
2190 {
2191 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2192 .context("Target already exists.");
2193 }
2194
2195 let updated = tx
2196 .execute(
2197 "UPDATE persistent.keyentry
2198 SET alias = ?, domain = ?, namespace = ?
2199 WHERE id = ?;",
2200 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2201 )
2202 .context("Failed to update key entry.")?;
2203
2204 if updated != 1 {
2205 return Err(KsError::sys())
2206 .context(format!("Update succeeded, but {} rows were updated.", updated));
2207 }
2208 Ok(()).no_gc()
2209 })
2210 .context("In migrate_key_namespace:")
2211 }
2212
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002213 /// Store a new key in a single transaction.
2214 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2215 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002216 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2217 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002218 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002219 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002220 key: &KeyDescriptor,
2221 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002222 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002223 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002224 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002225 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002226 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002227 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2228
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002229 let (alias, domain, namespace) = match key {
2230 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2231 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2232 (alias, key.domain, nspace)
2233 }
2234 _ => {
2235 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2236 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2237 }
2238 };
2239 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002240 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002241 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002242 let (blob, blob_metadata) = *blob_info;
2243 Self::set_blob_internal(
2244 tx,
2245 key_id.id(),
2246 SubComponentType::KEY_BLOB,
2247 Some(blob),
2248 Some(&blob_metadata),
2249 )
2250 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002251 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002252 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002253 .context("Trying to insert the certificate.")?;
2254 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002255 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002256 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002257 tx,
2258 key_id.id(),
2259 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002260 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002261 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002262 )
2263 .context("Trying to insert the certificate chain.")?;
2264 }
2265 Self::insert_keyparameter_internal(tx, &key_id, params)
2266 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002267 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002268 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002269 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002270 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 })
2272 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002273 }
2274
Janis Danisevskis377d1002021-01-27 19:07:48 -08002275 /// Store a new certificate
2276 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2277 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002278 pub fn store_new_certificate(
2279 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002280 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002281 cert: &[u8],
2282 km_uuid: &Uuid,
2283 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002284 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2285
Janis Danisevskis377d1002021-01-27 19:07:48 -08002286 let (alias, domain, namespace) = match key {
2287 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2288 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2289 (alias, key.domain, nspace)
2290 }
2291 _ => {
2292 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2293 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2294 )
2295 }
2296 };
2297 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002298 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002299 .context("Trying to create new key entry.")?;
2300
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002301 Self::set_blob_internal(
2302 tx,
2303 key_id.id(),
2304 SubComponentType::CERT_CHAIN,
2305 Some(cert),
2306 None,
2307 )
2308 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002309
2310 let mut metadata = KeyMetaData::new();
2311 metadata.add(KeyMetaEntry::CreationDate(
2312 DateTime::now().context("Trying to make creation time.")?,
2313 ));
2314
2315 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2316
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002317 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002318 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002319 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002320 })
2321 .context("In store_new_certificate.")
2322 }
2323
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002324 // Helper function loading the key_id given the key descriptor
2325 // tuple comprising domain, namespace, and alias.
2326 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002327 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002328 let alias = key
2329 .alias
2330 .as_ref()
2331 .map_or_else(|| Err(KsError::sys()), Ok)
2332 .context("In load_key_entry_id: Alias must be specified.")?;
2333 let mut stmt = tx
2334 .prepare(
2335 "SELECT id FROM persistent.keyentry
2336 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002337 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002338 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002339 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002340 AND alias = ?
2341 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002342 )
2343 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2344 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002345 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002346 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002347 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002348 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002349 .get(0)
2350 .context("Failed to unpack id.")
2351 })
2352 .context("In load_key_entry_id.")
2353 }
2354
2355 /// This helper function completes the access tuple of a key, which is required
2356 /// to perform access control. The strategy depends on the `domain` field in the
2357 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002358 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002359 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002360 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002361 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002362 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002363 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002364 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002365 /// `namespace`.
2366 /// In each case the information returned is sufficient to perform the access
2367 /// check and the key id can be used to load further key artifacts.
2368 fn load_access_tuple(
2369 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002370 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002371 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002372 caller_uid: u32,
2373 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2374 match key.domain {
2375 // Domain App or SELinux. In this case we load the key_id from
2376 // the keyentry database for further loading of key components.
2377 // We already have the full access tuple to perform access control.
2378 // The only distinction is that we use the caller_uid instead
2379 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002380 // Domain::APP.
2381 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002382 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002383 if access_key.domain == Domain::APP {
2384 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002385 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002386 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002387 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002388
2389 Ok((key_id, access_key, None))
2390 }
2391
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002392 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002393 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002394 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002395 let mut stmt = tx
2396 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002397 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002398 WHERE grantee = ? AND id = ? AND
2399 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002400 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002401 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002402 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002403 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002404 .context("Domain:Grant: query failed.")?;
2405 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002406 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002407 let r =
2408 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002409 Ok((
2410 r.get(0).context("Failed to unpack key_id.")?,
2411 r.get(1).context("Failed to unpack access_vector.")?,
2412 ))
2413 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002414 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002415 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002416 }
2417
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002418 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002420 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002421 let (domain, namespace): (Domain, i64) = {
2422 let mut stmt = tx
2423 .prepare(
2424 "SELECT domain, namespace FROM persistent.keyentry
2425 WHERE
2426 id = ?
2427 AND state = ?;",
2428 )
2429 .context("Domain::KEY_ID: prepare statement failed")?;
2430 let mut rows = stmt
2431 .query(params![key.nspace, KeyLifeCycle::Live])
2432 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002433 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002434 let r =
2435 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002436 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002437 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 r.get(1).context("Failed to unpack namespace.")?,
2439 ))
2440 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002441 .context("Domain::KEY_ID.")?
2442 };
2443
2444 // We may use a key by id after loading it by grant.
2445 // In this case we have to check if the caller has a grant for this particular
2446 // key. We can skip this if we already know that the caller is the owner.
2447 // But we cannot know this if domain is anything but App. E.g. in the case
2448 // of Domain::SELINUX we have to speculatively check for grants because we have to
2449 // consult the SEPolicy before we know if the caller is the owner.
2450 let access_vector: Option<KeyPermSet> =
2451 if domain != Domain::APP || namespace != caller_uid as i64 {
2452 let access_vector: Option<i32> = tx
2453 .query_row(
2454 "SELECT access_vector FROM persistent.grant
2455 WHERE grantee = ? AND keyentryid = ?;",
2456 params![caller_uid as i64, key.nspace],
2457 |row| row.get(0),
2458 )
2459 .optional()
2460 .context("Domain::KEY_ID: query grant failed.")?;
2461 access_vector.map(|p| p.into())
2462 } else {
2463 None
2464 };
2465
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002466 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002467 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002468 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002469 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002470
Janis Danisevskis45760022021-01-19 16:34:10 -08002471 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002472 }
2473 _ => Err(anyhow!(KsError::sys())),
2474 }
2475 }
2476
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002477 fn load_blob_components(
2478 key_id: i64,
2479 load_bits: KeyEntryLoadBits,
2480 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002481 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002482 let mut stmt = tx
2483 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002484 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002485 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2486 )
2487 .context("In load_blob_components: prepare statement failed.")?;
2488
2489 let mut rows =
2490 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2491
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002492 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002493 let mut cert_blob: Option<Vec<u8>> = None;
2494 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002495 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002496 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002497 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002498 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002499 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002500 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2501 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002502 key_blob = Some((
2503 row.get(0).context("Failed to extract key blob id.")?,
2504 row.get(2).context("Failed to extract key blob.")?,
2505 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002506 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002507 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002508 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002509 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002510 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002511 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002512 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002513 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002514 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002515 (SubComponentType::CERT, _, _)
2516 | (SubComponentType::CERT_CHAIN, _, _)
2517 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002518 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2519 }
2520 Ok(())
2521 })
2522 .context("In load_blob_components.")?;
2523
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002524 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2525 Ok(Some((
2526 blob,
2527 BlobMetaData::load_from_db(blob_id, tx)
2528 .context("In load_blob_components: Trying to load blob_metadata.")?,
2529 )))
2530 })?;
2531
2532 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002533 }
2534
2535 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2536 let mut stmt = tx
2537 .prepare(
2538 "SELECT tag, data, security_level from persistent.keyparameter
2539 WHERE keyentryid = ?;",
2540 )
2541 .context("In load_key_parameters: prepare statement failed.")?;
2542
2543 let mut parameters: Vec<KeyParameter> = Vec::new();
2544
2545 let mut rows =
2546 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002547 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002548 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2549 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002550 parameters.push(
2551 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2552 .context("Failed to read KeyParameter.")?,
2553 );
2554 Ok(())
2555 })
2556 .context("In load_key_parameters.")?;
2557
2558 Ok(parameters)
2559 }
2560
Qi Wub9433b52020-12-01 14:52:46 +08002561 /// Decrements the usage count of a limited use key. This function first checks whether the
2562 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2563 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2564 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002565 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002566 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2567
Qi Wub9433b52020-12-01 14:52:46 +08002568 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2569 let limit: Option<i32> = tx
2570 .query_row(
2571 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2572 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2573 |row| row.get(0),
2574 )
2575 .optional()
2576 .context("Trying to load usage count")?;
2577
2578 let limit = limit
2579 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2580 .context("The Key no longer exists. Key is exhausted.")?;
2581
2582 tx.execute(
2583 "UPDATE persistent.keyparameter
2584 SET data = data - 1
2585 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2586 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2587 )
2588 .context("Failed to update key usage count.")?;
2589
2590 match limit {
2591 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002592 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002593 .context("Trying to mark limited use key for deletion."),
2594 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002595 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002596 }
2597 })
2598 .context("In check_and_update_key_usage_count.")
2599 }
2600
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002601 /// Load a key entry by the given key descriptor.
2602 /// It uses the `check_permission` callback to verify if the access is allowed
2603 /// given the key access tuple read from the database using `load_access_tuple`.
2604 /// With `load_bits` the caller may specify which blobs shall be loaded from
2605 /// the blob database.
2606 pub fn load_key_entry(
2607 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002608 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002609 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002610 load_bits: KeyEntryLoadBits,
2611 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002612 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2613 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002614 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2615
Janis Danisevskis66784c42021-01-27 08:40:25 -08002616 loop {
2617 match self.load_key_entry_internal(
2618 key,
2619 key_type,
2620 load_bits,
2621 caller_uid,
2622 &check_permission,
2623 ) {
2624 Ok(result) => break Ok(result),
2625 Err(e) => {
2626 if Self::is_locked_error(&e) {
2627 std::thread::sleep(std::time::Duration::from_micros(500));
2628 continue;
2629 } else {
2630 return Err(e).context("In load_key_entry.");
2631 }
2632 }
2633 }
2634 }
2635 }
2636
2637 fn load_key_entry_internal(
2638 &mut self,
2639 key: &KeyDescriptor,
2640 key_type: KeyType,
2641 load_bits: KeyEntryLoadBits,
2642 caller_uid: u32,
2643 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002644 ) -> Result<(KeyIdGuard, KeyEntry)> {
2645 // KEY ID LOCK 1/2
2646 // If we got a key descriptor with a key id we can get the lock right away.
2647 // Otherwise we have to defer it until we know the key id.
2648 let key_id_guard = match key.domain {
2649 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2650 _ => None,
2651 };
2652
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002653 let tx = self
2654 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002655 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002656 .context("In load_key_entry: Failed to initialize transaction.")?;
2657
2658 // Load the key_id and complete the access control tuple.
2659 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002660 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2661 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002662
2663 // Perform access control. It is vital that we return here if the permission is denied.
2664 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002665 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002666
Janis Danisevskisaec14592020-11-12 09:41:49 -08002667 // KEY ID LOCK 2/2
2668 // If we did not get a key id lock by now, it was because we got a key descriptor
2669 // without a key id. At this point we got the key id, so we can try and get a lock.
2670 // However, we cannot block here, because we are in the middle of the transaction.
2671 // So first we try to get the lock non blocking. If that fails, we roll back the
2672 // transaction and block until we get the lock. After we successfully got the lock,
2673 // we start a new transaction and load the access tuple again.
2674 //
2675 // We don't need to perform access control again, because we already established
2676 // that the caller had access to the given key. But we need to make sure that the
2677 // key id still exists. So we have to load the key entry by key id this time.
2678 let (key_id_guard, tx) = match key_id_guard {
2679 None => match KEY_ID_LOCK.try_get(key_id) {
2680 None => {
2681 // Roll back the transaction.
2682 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002683
Janis Danisevskisaec14592020-11-12 09:41:49 -08002684 // Block until we have a key id lock.
2685 let key_id_guard = KEY_ID_LOCK.get(key_id);
2686
2687 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002688 let tx = self
2689 .conn
2690 .unchecked_transaction()
2691 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002692
2693 Self::load_access_tuple(
2694 &tx,
2695 // This time we have to load the key by the retrieved key id, because the
2696 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002697 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002698 domain: Domain::KEY_ID,
2699 nspace: key_id,
2700 ..Default::default()
2701 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002702 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002703 caller_uid,
2704 )
2705 .context("In load_key_entry. (deferred key lock)")?;
2706 (key_id_guard, tx)
2707 }
2708 Some(l) => (l, tx),
2709 },
2710 Some(key_id_guard) => (key_id_guard, tx),
2711 };
2712
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002713 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2714 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002715
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002716 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2717
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002718 Ok((key_id_guard, key_entry))
2719 }
2720
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002721 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002722 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002723 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2724 .context("Trying to delete keyentry.")?;
2725 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2726 .context("Trying to delete keymetadata.")?;
2727 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2728 .context("Trying to delete keyparameters.")?;
2729 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2730 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002731 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002732 }
2733
2734 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002735 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002736 pub fn unbind_key(
2737 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002738 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002739 key_type: KeyType,
2740 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002741 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002742 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002743 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2744
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002745 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2746 let (key_id, access_key_descriptor, access_vector) =
2747 Self::load_access_tuple(tx, key, key_type, caller_uid)
2748 .context("Trying to get access tuple.")?;
2749
2750 // Perform access control. It is vital that we return here if the permission is denied.
2751 // So do not touch that '?' at the end.
2752 check_permission(&access_key_descriptor, access_vector)
2753 .context("While checking permission.")?;
2754
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002755 Self::mark_unreferenced(tx, key_id)
2756 .map(|need_gc| (need_gc, ()))
2757 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002758 })
2759 .context("In unbind_key.")
2760 }
2761
Max Bires8e93d2b2021-01-14 13:17:59 -08002762 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2763 tx.query_row(
2764 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2765 params![key_id],
2766 |row| row.get(0),
2767 )
2768 .context("In get_key_km_uuid.")
2769 }
2770
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002771 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2772 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2773 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002774 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2775
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002776 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2777 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2778 .context("In unbind_keys_for_namespace.");
2779 }
2780 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2781 tx.execute(
2782 "DELETE FROM persistent.keymetadata
2783 WHERE keyentryid IN (
2784 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002785 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002786 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002787 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002788 )
2789 .context("Trying to delete keymetadata.")?;
2790 tx.execute(
2791 "DELETE FROM persistent.keyparameter
2792 WHERE keyentryid IN (
2793 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002794 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002795 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002796 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002797 )
2798 .context("Trying to delete keyparameters.")?;
2799 tx.execute(
2800 "DELETE FROM persistent.grant
2801 WHERE keyentryid IN (
2802 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002803 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002804 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002805 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002806 )
2807 .context("Trying to delete grants.")?;
2808 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002809 "DELETE FROM persistent.keyentry
2810 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2811 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002812 )
2813 .context("Trying to delete keyentry.")?;
2814 Ok(()).need_gc()
2815 })
2816 .context("In unbind_keys_for_namespace")
2817 }
2818
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002819 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2820 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2821 {
2822 tx.execute(
2823 "DELETE FROM persistent.keymetadata
2824 WHERE keyentryid IN (
2825 SELECT id FROM persistent.keyentry
2826 WHERE state = ?
2827 );",
2828 params![KeyLifeCycle::Unreferenced],
2829 )
2830 .context("Trying to delete keymetadata.")?;
2831 tx.execute(
2832 "DELETE FROM persistent.keyparameter
2833 WHERE keyentryid IN (
2834 SELECT id FROM persistent.keyentry
2835 WHERE state = ?
2836 );",
2837 params![KeyLifeCycle::Unreferenced],
2838 )
2839 .context("Trying to delete keyparameters.")?;
2840 tx.execute(
2841 "DELETE FROM persistent.grant
2842 WHERE keyentryid IN (
2843 SELECT id FROM persistent.keyentry
2844 WHERE state = ?
2845 );",
2846 params![KeyLifeCycle::Unreferenced],
2847 )
2848 .context("Trying to delete grants.")?;
2849 tx.execute(
2850 "DELETE FROM persistent.keyentry
2851 WHERE state = ?;",
2852 params![KeyLifeCycle::Unreferenced],
2853 )
2854 .context("Trying to delete keyentry.")?;
2855 Result::<()>::Ok(())
2856 }
2857 .context("In cleanup_unreferenced")
2858 }
2859
Hasini Gunasingheda895552021-01-27 19:34:37 +00002860 /// Delete the keys created on behalf of the user, denoted by the user id.
2861 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2862 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2863 /// The caller of this function should notify the gc if the returned value is true.
2864 pub fn unbind_keys_for_user(
2865 &mut self,
2866 user_id: u32,
2867 keep_non_super_encrypted_keys: bool,
2868 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002869 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2870
Hasini Gunasingheda895552021-01-27 19:34:37 +00002871 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2872 let mut stmt = tx
2873 .prepare(&format!(
2874 "SELECT id from persistent.keyentry
2875 WHERE (
2876 key_type = ?
2877 AND domain = ?
2878 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2879 AND state = ?
2880 ) OR (
2881 key_type = ?
2882 AND namespace = ?
2883 AND alias = ?
2884 AND state = ?
2885 );",
2886 aid_user_offset = AID_USER_OFFSET
2887 ))
2888 .context(concat!(
2889 "In unbind_keys_for_user. ",
2890 "Failed to prepare the query to find the keys created by apps."
2891 ))?;
2892
2893 let mut rows = stmt
2894 .query(params![
2895 // WHERE client key:
2896 KeyType::Client,
2897 Domain::APP.0 as u32,
2898 user_id,
2899 KeyLifeCycle::Live,
2900 // OR super key:
2901 KeyType::Super,
2902 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002903 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002904 KeyLifeCycle::Live
2905 ])
2906 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2907
2908 let mut key_ids: Vec<i64> = Vec::new();
2909 db_utils::with_rows_extract_all(&mut rows, |row| {
2910 key_ids
2911 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2912 Ok(())
2913 })
2914 .context("In unbind_keys_for_user.")?;
2915
2916 let mut notify_gc = false;
2917 for key_id in key_ids {
2918 if keep_non_super_encrypted_keys {
2919 // Load metadata and filter out non-super-encrypted keys.
2920 if let (_, Some((_, blob_metadata)), _, _) =
2921 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2922 .context("In unbind_keys_for_user: Trying to load blob info.")?
2923 {
2924 if blob_metadata.encrypted_by().is_none() {
2925 continue;
2926 }
2927 }
2928 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002929 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002930 .context("In unbind_keys_for_user.")?
2931 || notify_gc;
2932 }
2933 Ok(()).do_gc(notify_gc)
2934 })
2935 .context("In unbind_keys_for_user.")
2936 }
2937
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002938 fn load_key_components(
2939 tx: &Transaction,
2940 load_bits: KeyEntryLoadBits,
2941 key_id: i64,
2942 ) -> Result<KeyEntry> {
2943 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2944
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002945 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002946 Self::load_blob_components(key_id, load_bits, &tx)
2947 .context("In load_key_components.")?;
2948
Max Bires8e93d2b2021-01-14 13:17:59 -08002949 let parameters = Self::load_key_parameters(key_id, &tx)
2950 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002951
Max Bires8e93d2b2021-01-14 13:17:59 -08002952 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2953 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002954
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002955 Ok(KeyEntry {
2956 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002957 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002958 cert: cert_blob,
2959 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002960 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002961 parameters,
2962 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002963 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002964 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002965 }
2966
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002967 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2968 /// The key descriptors will have the domain, nspace, and alias field set.
2969 /// Domain must be APP or SELINUX, the caller must make sure of that.
2970 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002971 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2972
Janis Danisevskis66784c42021-01-27 08:40:25 -08002973 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2974 let mut stmt = tx
2975 .prepare(
2976 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002977 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002978 )
2979 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002980
Janis Danisevskis66784c42021-01-27 08:40:25 -08002981 let mut rows = stmt
2982 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2983 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002984
Janis Danisevskis66784c42021-01-27 08:40:25 -08002985 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2986 db_utils::with_rows_extract_all(&mut rows, |row| {
2987 descriptors.push(KeyDescriptor {
2988 domain,
2989 nspace: namespace,
2990 alias: Some(row.get(0).context("Trying to extract alias.")?),
2991 blob: None,
2992 });
2993 Ok(())
2994 })
2995 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002996 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002997 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002998 }
2999
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003000 /// Adds a grant to the grant table.
3001 /// Like `load_key_entry` this function loads the access tuple before
3002 /// it uses the callback for a permission check. Upon success,
3003 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3004 /// grant table. The new row will have a randomized id, which is used as
3005 /// grant id in the namespace field of the resulting KeyDescriptor.
3006 pub fn grant(
3007 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003008 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003009 caller_uid: u32,
3010 grantee_uid: u32,
3011 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003012 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003013 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003014 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3015
Janis Danisevskis66784c42021-01-27 08:40:25 -08003016 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3017 // Load the key_id and complete the access control tuple.
3018 // We ignore the access vector here because grants cannot be granted.
3019 // The access vector returned here expresses the permissions the
3020 // grantee has if key.domain == Domain::GRANT. But this vector
3021 // cannot include the grant permission by design, so there is no way the
3022 // subsequent permission check can pass.
3023 // We could check key.domain == Domain::GRANT and fail early.
3024 // But even if we load the access tuple by grant here, the permission
3025 // check denies the attempt to create a grant by grant descriptor.
3026 let (key_id, access_key_descriptor, _) =
3027 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3028 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003029
Janis Danisevskis66784c42021-01-27 08:40:25 -08003030 // Perform access control. It is vital that we return here if the permission
3031 // was denied. So do not touch that '?' at the end of the line.
3032 // This permission check checks if the caller has the grant permission
3033 // for the given key and in addition to all of the permissions
3034 // expressed in `access_vector`.
3035 check_permission(&access_key_descriptor, &access_vector)
3036 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003037
Janis Danisevskis66784c42021-01-27 08:40:25 -08003038 let grant_id = if let Some(grant_id) = tx
3039 .query_row(
3040 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003041 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003042 params![key_id, grantee_uid],
3043 |row| row.get(0),
3044 )
3045 .optional()
3046 .context("In grant: Failed get optional existing grant id.")?
3047 {
3048 tx.execute(
3049 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003050 SET access_vector = ?
3051 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003052 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003053 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003054 .context("In grant: Failed to update existing grant.")?;
3055 grant_id
3056 } else {
3057 Self::insert_with_retry(|id| {
3058 tx.execute(
3059 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3060 VALUES (?, ?, ?, ?);",
3061 params![id, grantee_uid, key_id, i32::from(access_vector)],
3062 )
3063 })
3064 .context("In grant")?
3065 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003066
Janis Danisevskis66784c42021-01-27 08:40:25 -08003067 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003068 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003069 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003070 }
3071
3072 /// This function checks permissions like `grant` and `load_key_entry`
3073 /// before removing a grant from the grant table.
3074 pub fn ungrant(
3075 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003076 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003077 caller_uid: u32,
3078 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003079 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003080 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003081 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3082
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3084 // Load the key_id and complete the access control tuple.
3085 // We ignore the access vector here because grants cannot be granted.
3086 let (key_id, access_key_descriptor, _) =
3087 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3088 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003089
Janis Danisevskis66784c42021-01-27 08:40:25 -08003090 // Perform access control. We must return here if the permission
3091 // was denied. So do not touch the '?' at the end of this line.
3092 check_permission(&access_key_descriptor)
3093 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003094
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 tx.execute(
3096 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003097 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003098 params![key_id, grantee_uid],
3099 )
3100 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003102 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003103 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003104 }
3105
Joel Galenson845f74b2020-09-09 14:11:55 -07003106 // Generates a random id and passes it to the given function, which will
3107 // try to insert it into a database. If that insertion fails, retry;
3108 // otherwise return the id.
3109 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3110 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003111 let newid: i64 = match random() {
3112 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3113 i => i,
3114 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003115 match inserter(newid) {
3116 // If the id already existed, try again.
3117 Err(rusqlite::Error::SqliteFailure(
3118 libsqlite3_sys::Error {
3119 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3120 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3121 },
3122 _,
3123 )) => (),
3124 Err(e) => {
3125 return Err(e).context("In insert_with_retry: failed to insert into database.")
3126 }
3127 _ => return Ok(newid),
3128 }
3129 }
3130 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003131
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003132 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3133 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3134 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3135 auth_token.clone(),
3136 MonotonicRawTime::now(),
3137 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003138 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003139
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003140 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003141 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003142 where
3143 F: Fn(&AuthTokenEntry) -> bool,
3144 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003145 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003146 }
3147
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003148 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003149 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3150 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003151 }
3152
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003153 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003154 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3155 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003156 }
3157
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003158 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003159 fn get_last_off_body(&self) -> MonotonicRawTime {
3160 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003161 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003162}
3163
3164#[cfg(test)]
3165mod tests {
3166
3167 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003168 use crate::key_parameter::{
3169 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3170 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3171 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003172 use crate::key_perm_set;
3173 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003174 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003175 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003176 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3177 HardwareAuthToken::HardwareAuthToken,
3178 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003179 };
3180 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003181 Timestamp::Timestamp,
3182 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003183 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003184 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003185 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003186 use std::collections::BTreeMap;
3187 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003188 use std::sync::atomic::{AtomicU8, Ordering};
3189 use std::sync::Arc;
3190 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003191 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003192 #[cfg(disabled)]
3193 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003194
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003195 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003196 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003197
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003198 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003199 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003200 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003201 })?;
3202 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003203 }
3204
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003205 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3206 where
3207 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3208 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003209 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003210
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003211 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003212 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003213
Janis Danisevskis3395f862021-05-06 10:54:17 -07003214 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003215 }
3216
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003217 fn rebind_alias(
3218 db: &mut KeystoreDB,
3219 newid: &KeyIdGuard,
3220 alias: &str,
3221 domain: Domain,
3222 namespace: i64,
3223 ) -> Result<bool> {
3224 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003225 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003226 })
3227 .context("In rebind_alias.")
3228 }
3229
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003230 #[test]
3231 fn datetime() -> Result<()> {
3232 let conn = Connection::open_in_memory()?;
3233 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3234 let now = SystemTime::now();
3235 let duration = Duration::from_secs(1000);
3236 let then = now.checked_sub(duration).unwrap();
3237 let soon = now.checked_add(duration).unwrap();
3238 conn.execute(
3239 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3240 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3241 )?;
3242 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3243 let mut rows = stmt.query(NO_PARAMS)?;
3244 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3245 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3246 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3247 assert!(rows.next()?.is_none());
3248 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3249 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3250 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3251 Ok(())
3252 }
3253
Joel Galenson0891bc12020-07-20 10:37:03 -07003254 // Ensure that we're using the "injected" random function, not the real one.
3255 #[test]
3256 fn test_mocked_random() {
3257 let rand1 = random();
3258 let rand2 = random();
3259 let rand3 = random();
3260 if rand1 == rand2 {
3261 assert_eq!(rand2 + 1, rand3);
3262 } else {
3263 assert_eq!(rand1 + 1, rand2);
3264 assert_eq!(rand2, rand3);
3265 }
3266 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003267
Joel Galenson26f4d012020-07-17 14:57:21 -07003268 // Test that we have the correct tables.
3269 #[test]
3270 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003271 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003272 let tables = db
3273 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003274 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003275 .query_map(params![], |row| row.get(0))?
3276 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003277 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003278 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003279 assert_eq!(tables[1], "blobmetadata");
3280 assert_eq!(tables[2], "grant");
3281 assert_eq!(tables[3], "keyentry");
3282 assert_eq!(tables[4], "keymetadata");
3283 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003284 Ok(())
3285 }
3286
3287 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003288 fn test_auth_token_table_invariant() -> Result<()> {
3289 let mut db = new_test_db()?;
3290 let auth_token1 = HardwareAuthToken {
3291 challenge: i64::MAX,
3292 userId: 200,
3293 authenticatorId: 200,
3294 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3295 timestamp: Timestamp { milliSeconds: 500 },
3296 mac: String::from("mac").into_bytes(),
3297 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003298 db.insert_auth_token(&auth_token1);
3299 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003300 assert_eq!(auth_tokens_returned.len(), 1);
3301
3302 // insert another auth token with the same values for the columns in the UNIQUE constraint
3303 // of the auth token table and different value for timestamp
3304 let auth_token2 = HardwareAuthToken {
3305 challenge: i64::MAX,
3306 userId: 200,
3307 authenticatorId: 200,
3308 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3309 timestamp: Timestamp { milliSeconds: 600 },
3310 mac: String::from("mac").into_bytes(),
3311 };
3312
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003313 db.insert_auth_token(&auth_token2);
3314 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003315 assert_eq!(auth_tokens_returned.len(), 1);
3316
3317 if let Some(auth_token) = auth_tokens_returned.pop() {
3318 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3319 }
3320
3321 // insert another auth token with the different values for the columns in the UNIQUE
3322 // constraint of the auth token table
3323 let auth_token3 = HardwareAuthToken {
3324 challenge: i64::MAX,
3325 userId: 201,
3326 authenticatorId: 200,
3327 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3328 timestamp: Timestamp { milliSeconds: 600 },
3329 mac: String::from("mac").into_bytes(),
3330 };
3331
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003332 db.insert_auth_token(&auth_token3);
3333 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003334 assert_eq!(auth_tokens_returned.len(), 2);
3335
3336 Ok(())
3337 }
3338
3339 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003340 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3341 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003342 }
3343
3344 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003345 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003346 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003347 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003348
Janis Danisevskis66784c42021-01-27 08:40:25 -08003349 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003350 let entries = get_keyentry(&db)?;
3351 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003352
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003353 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003354
3355 let entries_new = get_keyentry(&db)?;
3356 assert_eq!(entries, entries_new);
3357 Ok(())
3358 }
3359
3360 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003361 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003362 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3363 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003364 }
3365
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003366 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003367
Janis Danisevskis66784c42021-01-27 08:40:25 -08003368 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3369 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003370
3371 let entries = get_keyentry(&db)?;
3372 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003373 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3374 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003375
3376 // Test that we must pass in a valid Domain.
3377 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003378 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003379 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003380 );
3381 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003382 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003383 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003384 );
3385 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003386 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003387 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003388 );
3389
3390 Ok(())
3391 }
3392
Joel Galenson33c04ad2020-08-03 11:04:38 -07003393 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003394 fn test_add_unsigned_key() -> Result<()> {
3395 let mut db = new_test_db()?;
3396 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3397 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3398 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3399 db.create_attestation_key_entry(
3400 &public_key,
3401 &raw_public_key,
3402 &private_key,
3403 &KEYSTORE_UUID,
3404 )?;
3405 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3406 assert_eq!(keys.len(), 1);
3407 assert_eq!(keys[0], public_key);
3408 Ok(())
3409 }
3410
3411 #[test]
3412 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3413 let mut db = new_test_db()?;
3414 let expiration_date: i64 = 20;
3415 let namespace: i64 = 30;
3416 let base_byte: u8 = 1;
3417 let loaded_values =
3418 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3419 let chain =
3420 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3421 assert_eq!(true, chain.is_some());
3422 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003423 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003424 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3425 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003426 Ok(())
3427 }
3428
3429 #[test]
3430 fn test_get_attestation_pool_status() -> Result<()> {
3431 let mut db = new_test_db()?;
3432 let namespace: i64 = 30;
3433 load_attestation_key_pool(
3434 &mut db, 10, /* expiration */
3435 namespace, 0x01, /* base_byte */
3436 )?;
3437 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3438 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3439 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3440 assert_eq!(status.expiring, 0);
3441 assert_eq!(status.attested, 3);
3442 assert_eq!(status.unassigned, 0);
3443 assert_eq!(status.total, 3);
3444 assert_eq!(
3445 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3446 1
3447 );
3448 assert_eq!(
3449 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3450 2
3451 );
3452 assert_eq!(
3453 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3454 3
3455 );
3456 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3457 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3458 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3459 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003460 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003461 db.create_attestation_key_entry(
3462 &public_key,
3463 &raw_public_key,
3464 &private_key,
3465 &KEYSTORE_UUID,
3466 )?;
3467 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3468 assert_eq!(status.attested, 3);
3469 assert_eq!(status.unassigned, 0);
3470 assert_eq!(status.total, 4);
3471 db.store_signed_attestation_certificate_chain(
3472 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003473 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003474 &cert_chain,
3475 20,
3476 &KEYSTORE_UUID,
3477 )?;
3478 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3479 assert_eq!(status.attested, 4);
3480 assert_eq!(status.unassigned, 1);
3481 assert_eq!(status.total, 4);
3482 Ok(())
3483 }
3484
3485 #[test]
3486 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003487 let temp_dir =
3488 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3489 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003490 let expiration_date: i64 =
3491 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3492 let namespace: i64 = 30;
3493 let namespace_del1: i64 = 45;
3494 let namespace_del2: i64 = 60;
3495 let entry_values = load_attestation_key_pool(
3496 &mut db,
3497 expiration_date,
3498 namespace,
3499 0x01, /* base_byte */
3500 )?;
3501 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3502 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003503
3504 let blob_entry_row_count: u32 = db
3505 .conn
3506 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3507 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003508 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3509 // one key, one certificate chain, and one certificate.
3510 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003511
Max Bires2b2e6562020-09-22 11:22:36 -07003512 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3513
3514 let mut cert_chain =
3515 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003516 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003517 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003518 assert_eq!(entry_values.batch_cert, value.batch_cert);
3519 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003520 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003521
3522 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3523 Domain::APP,
3524 namespace_del1,
3525 &KEYSTORE_UUID,
3526 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003527 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003528 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3529 Domain::APP,
3530 namespace_del2,
3531 &KEYSTORE_UUID,
3532 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003533 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003534
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003535 // Give the garbage collector half a second to catch up.
3536 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003537
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003538 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 // There shound be 3 blob entries left, because we deleted two of the attestation
3543 // key entries with three blobs each.
3544 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003545
Max Bires2b2e6562020-09-22 11:22:36 -07003546 Ok(())
3547 }
3548
3549 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003550 fn test_delete_all_attestation_keys() -> Result<()> {
3551 let mut db = new_test_db()?;
3552 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3553 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3554 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3555 let result = db.delete_all_attestation_keys()?;
3556
3557 // Give the garbage collector half a second to catch up.
3558 std::thread::sleep(Duration::from_millis(500));
3559
3560 // Attestation keys should be deleted, and the regular key should remain.
3561 assert_eq!(result, 2);
3562
3563 Ok(())
3564 }
3565
3566 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003567 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003568 fn extractor(
3569 ke: &KeyEntryRow,
3570 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3571 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003572 }
3573
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003574 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003575 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3576 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003577 let entries = get_keyentry(&db)?;
3578 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003579 assert_eq!(
3580 extractor(&entries[0]),
3581 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3582 );
3583 assert_eq!(
3584 extractor(&entries[1]),
3585 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3586 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003587
3588 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003589 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003590 let entries = get_keyentry(&db)?;
3591 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003592 assert_eq!(
3593 extractor(&entries[0]),
3594 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3595 );
3596 assert_eq!(
3597 extractor(&entries[1]),
3598 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3599 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003600
3601 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003602 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003603 let entries = get_keyentry(&db)?;
3604 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003605 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3606 assert_eq!(
3607 extractor(&entries[1]),
3608 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3609 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003610
3611 // Test that we must pass in a valid Domain.
3612 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003613 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003614 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003615 );
3616 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003617 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003618 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003619 );
3620 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003621 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003622 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003623 );
3624
3625 // Test that we correctly handle setting an alias for something that does not exist.
3626 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003627 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003628 "Expected to update a single entry but instead updated 0",
3629 );
3630 // Test that we correctly abort the transaction in this case.
3631 let entries = get_keyentry(&db)?;
3632 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003633 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3634 assert_eq!(
3635 extractor(&entries[1]),
3636 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3637 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003638
3639 Ok(())
3640 }
3641
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003642 #[test]
3643 fn test_grant_ungrant() -> Result<()> {
3644 const CALLER_UID: u32 = 15;
3645 const GRANTEE_UID: u32 = 12;
3646 const SELINUX_NAMESPACE: i64 = 7;
3647
3648 let mut db = new_test_db()?;
3649 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003650 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3651 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3652 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003653 )?;
3654 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003655 domain: super::Domain::APP,
3656 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003657 alias: Some("key".to_string()),
3658 blob: None,
3659 };
3660 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3661 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3662
3663 // Reset totally predictable random number generator in case we
3664 // are not the first test running on this thread.
3665 reset_random();
3666 let next_random = 0i64;
3667
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003668 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003669 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003670 assert_eq!(*a, PVEC1);
3671 assert_eq!(
3672 *k,
3673 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003674 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003675 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003676 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003677 alias: Some("key".to_string()),
3678 blob: None,
3679 }
3680 );
3681 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003682 })
3683 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003684
3685 assert_eq!(
3686 app_granted_key,
3687 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003688 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003689 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003690 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003691 alias: None,
3692 blob: None,
3693 }
3694 );
3695
3696 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003697 domain: super::Domain::SELINUX,
3698 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003699 alias: Some("yek".to_string()),
3700 blob: None,
3701 };
3702
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003703 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003704 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003705 assert_eq!(*a, PVEC1);
3706 assert_eq!(
3707 *k,
3708 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003709 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003710 // namespace must be the supplied SELinux
3711 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003712 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003713 alias: Some("yek".to_string()),
3714 blob: None,
3715 }
3716 );
3717 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003718 })
3719 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003720
3721 assert_eq!(
3722 selinux_granted_key,
3723 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003724 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003726 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003727 alias: None,
3728 blob: None,
3729 }
3730 );
3731
3732 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003733 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003734 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003735 assert_eq!(*a, PVEC2);
3736 assert_eq!(
3737 *k,
3738 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003739 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003740 // namespace must be the supplied SELinux
3741 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003742 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003743 alias: Some("yek".to_string()),
3744 blob: None,
3745 }
3746 );
3747 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003748 })
3749 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003750
3751 assert_eq!(
3752 selinux_granted_key,
3753 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003754 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003756 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003757 alias: None,
3758 blob: None,
3759 }
3760 );
3761
3762 {
3763 // Limiting scope of stmt, because it borrows db.
3764 let mut stmt = db
3765 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003766 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003767 let mut rows =
3768 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3769 Ok((
3770 row.get(0)?,
3771 row.get(1)?,
3772 row.get(2)?,
3773 KeyPermSet::from(row.get::<_, i32>(3)?),
3774 ))
3775 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003776
3777 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003778 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003779 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003780 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003781 assert!(rows.next().is_none());
3782 }
3783
3784 debug_dump_keyentry_table(&mut db)?;
3785 println!("app_key {:?}", app_key);
3786 println!("selinux_key {:?}", selinux_key);
3787
Janis Danisevskis66784c42021-01-27 08:40:25 -08003788 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3789 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003790
3791 Ok(())
3792 }
3793
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003794 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003795 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3796 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3797
3798 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003799 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003800 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003801 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003802 let mut blob_metadata = BlobMetaData::new();
3803 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3804 db.set_blob(
3805 &key_id,
3806 SubComponentType::KEY_BLOB,
3807 Some(TEST_KEY_BLOB),
3808 Some(&blob_metadata),
3809 )?;
3810 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3811 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003812 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003813
3814 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003815 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003816 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003817 )?;
3818 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003819 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3820 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003821 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003822 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003823 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003824 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003825 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003826 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003827 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003828
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003829 drop(rows);
3830 drop(stmt);
3831
3832 assert_eq!(
3833 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3834 BlobMetaData::load_from_db(id, tx).no_gc()
3835 })
3836 .expect("Should find blob metadata."),
3837 blob_metadata
3838 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003839 Ok(())
3840 }
3841
3842 static TEST_ALIAS: &str = "my super duper key";
3843
3844 #[test]
3845 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3846 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003847 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003848 .context("test_insert_and_load_full_keyentry_domain_app")?
3849 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003850 let (_key_guard, key_entry) = db
3851 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003852 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003853 domain: Domain::APP,
3854 nspace: 0,
3855 alias: Some(TEST_ALIAS.to_string()),
3856 blob: None,
3857 },
3858 KeyType::Client,
3859 KeyEntryLoadBits::BOTH,
3860 1,
3861 |_k, _av| Ok(()),
3862 )
3863 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003864 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003865
3866 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003867 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003868 domain: Domain::APP,
3869 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003870 alias: Some(TEST_ALIAS.to_string()),
3871 blob: None,
3872 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003873 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003874 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003875 |_, _| Ok(()),
3876 )
3877 .unwrap();
3878
3879 assert_eq!(
3880 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3881 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003882 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003883 domain: Domain::APP,
3884 nspace: 0,
3885 alias: Some(TEST_ALIAS.to_string()),
3886 blob: None,
3887 },
3888 KeyType::Client,
3889 KeyEntryLoadBits::NONE,
3890 1,
3891 |_k, _av| Ok(()),
3892 )
3893 .unwrap_err()
3894 .root_cause()
3895 .downcast_ref::<KsError>()
3896 );
3897
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003898 Ok(())
3899 }
3900
3901 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003902 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3903 let mut db = new_test_db()?;
3904
3905 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003906 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003907 domain: Domain::APP,
3908 nspace: 1,
3909 alias: Some(TEST_ALIAS.to_string()),
3910 blob: None,
3911 },
3912 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003913 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003914 )
3915 .expect("Trying to insert cert.");
3916
3917 let (_key_guard, mut key_entry) = db
3918 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003919 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003920 domain: Domain::APP,
3921 nspace: 1,
3922 alias: Some(TEST_ALIAS.to_string()),
3923 blob: None,
3924 },
3925 KeyType::Client,
3926 KeyEntryLoadBits::PUBLIC,
3927 1,
3928 |_k, _av| Ok(()),
3929 )
3930 .expect("Trying to read certificate entry.");
3931
3932 assert!(key_entry.pure_cert());
3933 assert!(key_entry.cert().is_none());
3934 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3935
3936 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003937 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003938 domain: Domain::APP,
3939 nspace: 1,
3940 alias: Some(TEST_ALIAS.to_string()),
3941 blob: None,
3942 },
3943 KeyType::Client,
3944 1,
3945 |_, _| Ok(()),
3946 )
3947 .unwrap();
3948
3949 assert_eq!(
3950 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3951 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003952 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003953 domain: Domain::APP,
3954 nspace: 1,
3955 alias: Some(TEST_ALIAS.to_string()),
3956 blob: None,
3957 },
3958 KeyType::Client,
3959 KeyEntryLoadBits::NONE,
3960 1,
3961 |_k, _av| Ok(()),
3962 )
3963 .unwrap_err()
3964 .root_cause()
3965 .downcast_ref::<KsError>()
3966 );
3967
3968 Ok(())
3969 }
3970
3971 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003972 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3973 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003974 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003975 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3976 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003977 let (_key_guard, key_entry) = db
3978 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003979 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003980 domain: Domain::SELINUX,
3981 nspace: 1,
3982 alias: Some(TEST_ALIAS.to_string()),
3983 blob: None,
3984 },
3985 KeyType::Client,
3986 KeyEntryLoadBits::BOTH,
3987 1,
3988 |_k, _av| Ok(()),
3989 )
3990 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003991 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003992
3993 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003994 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003995 domain: Domain::SELINUX,
3996 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003997 alias: Some(TEST_ALIAS.to_string()),
3998 blob: None,
3999 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004000 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004001 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004002 |_, _| Ok(()),
4003 )
4004 .unwrap();
4005
4006 assert_eq!(
4007 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4008 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004009 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004010 domain: Domain::SELINUX,
4011 nspace: 1,
4012 alias: Some(TEST_ALIAS.to_string()),
4013 blob: None,
4014 },
4015 KeyType::Client,
4016 KeyEntryLoadBits::NONE,
4017 1,
4018 |_k, _av| Ok(()),
4019 )
4020 .unwrap_err()
4021 .root_cause()
4022 .downcast_ref::<KsError>()
4023 );
4024
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004025 Ok(())
4026 }
4027
4028 #[test]
4029 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4030 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004031 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004032 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4033 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004034 let (_, key_entry) = db
4035 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004036 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004037 KeyType::Client,
4038 KeyEntryLoadBits::BOTH,
4039 1,
4040 |_k, _av| Ok(()),
4041 )
4042 .unwrap();
4043
Qi Wub9433b52020-12-01 14:52:46 +08004044 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004045
4046 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004047 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004048 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004049 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004050 |_, _| Ok(()),
4051 )
4052 .unwrap();
4053
4054 assert_eq!(
4055 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4056 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004057 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004058 KeyType::Client,
4059 KeyEntryLoadBits::NONE,
4060 1,
4061 |_k, _av| Ok(()),
4062 )
4063 .unwrap_err()
4064 .root_cause()
4065 .downcast_ref::<KsError>()
4066 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004067
4068 Ok(())
4069 }
4070
4071 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004072 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4073 let mut db = new_test_db()?;
4074 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4075 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4076 .0;
4077 // Update the usage count of the limited use key.
4078 db.check_and_update_key_usage_count(key_id)?;
4079
4080 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004081 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004082 KeyType::Client,
4083 KeyEntryLoadBits::BOTH,
4084 1,
4085 |_k, _av| Ok(()),
4086 )?;
4087
4088 // The usage count is decremented now.
4089 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4090
4091 Ok(())
4092 }
4093
4094 #[test]
4095 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4096 let mut db = new_test_db()?;
4097 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4098 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4099 .0;
4100 // Update the usage count of the limited use key.
4101 db.check_and_update_key_usage_count(key_id).expect(concat!(
4102 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4103 "This should succeed."
4104 ));
4105
4106 // Try to update the exhausted limited use key.
4107 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4108 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4109 "This should fail."
4110 ));
4111 assert_eq!(
4112 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4113 e.root_cause().downcast_ref::<KsError>().unwrap()
4114 );
4115
4116 Ok(())
4117 }
4118
4119 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004120 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4121 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004122 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004123 .context("test_insert_and_load_full_keyentry_from_grant")?
4124 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004125
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004126 let granted_key = db
4127 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004128 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004129 domain: Domain::APP,
4130 nspace: 0,
4131 alias: Some(TEST_ALIAS.to_string()),
4132 blob: None,
4133 },
4134 1,
4135 2,
4136 key_perm_set![KeyPerm::use_()],
4137 |_k, _av| Ok(()),
4138 )
4139 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004140
4141 debug_dump_grant_table(&mut db)?;
4142
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004143 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004144 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4145 assert_eq!(Domain::GRANT, k.domain);
4146 assert!(av.unwrap().includes(KeyPerm::use_()));
4147 Ok(())
4148 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004149 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004150
Qi Wub9433b52020-12-01 14:52:46 +08004151 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004152
Janis Danisevskis66784c42021-01-27 08:40:25 -08004153 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004154
4155 assert_eq!(
4156 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4157 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004158 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004159 KeyType::Client,
4160 KeyEntryLoadBits::NONE,
4161 2,
4162 |_k, _av| Ok(()),
4163 )
4164 .unwrap_err()
4165 .root_cause()
4166 .downcast_ref::<KsError>()
4167 );
4168
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004169 Ok(())
4170 }
4171
Janis Danisevskis45760022021-01-19 16:34:10 -08004172 // This test attempts to load a key by key id while the caller is not the owner
4173 // but a grant exists for the given key and the caller.
4174 #[test]
4175 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4176 let mut db = new_test_db()?;
4177 const OWNER_UID: u32 = 1u32;
4178 const GRANTEE_UID: u32 = 2u32;
4179 const SOMEONE_ELSE_UID: u32 = 3u32;
4180 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4181 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4182 .0;
4183
4184 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004185 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004186 domain: Domain::APP,
4187 nspace: 0,
4188 alias: Some(TEST_ALIAS.to_string()),
4189 blob: None,
4190 },
4191 OWNER_UID,
4192 GRANTEE_UID,
4193 key_perm_set![KeyPerm::use_()],
4194 |_k, _av| Ok(()),
4195 )
4196 .unwrap();
4197
4198 debug_dump_grant_table(&mut db)?;
4199
4200 let id_descriptor =
4201 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4202
4203 let (_, key_entry) = db
4204 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004205 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004206 KeyType::Client,
4207 KeyEntryLoadBits::BOTH,
4208 GRANTEE_UID,
4209 |k, av| {
4210 assert_eq!(Domain::APP, k.domain);
4211 assert_eq!(OWNER_UID as i64, k.nspace);
4212 assert!(av.unwrap().includes(KeyPerm::use_()));
4213 Ok(())
4214 },
4215 )
4216 .unwrap();
4217
4218 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4219
4220 let (_, key_entry) = db
4221 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004222 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004223 KeyType::Client,
4224 KeyEntryLoadBits::BOTH,
4225 SOMEONE_ELSE_UID,
4226 |k, av| {
4227 assert_eq!(Domain::APP, k.domain);
4228 assert_eq!(OWNER_UID as i64, k.nspace);
4229 assert!(av.is_none());
4230 Ok(())
4231 },
4232 )
4233 .unwrap();
4234
4235 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4236
Janis Danisevskis66784c42021-01-27 08:40:25 -08004237 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004238
4239 assert_eq!(
4240 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4241 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004242 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004243 KeyType::Client,
4244 KeyEntryLoadBits::NONE,
4245 GRANTEE_UID,
4246 |_k, _av| Ok(()),
4247 )
4248 .unwrap_err()
4249 .root_cause()
4250 .downcast_ref::<KsError>()
4251 );
4252
4253 Ok(())
4254 }
4255
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004256 // Creates a key migrates it to a different location and then tries to access it by the old
4257 // and new location.
4258 #[test]
4259 fn test_migrate_key_app_to_app() -> Result<()> {
4260 let mut db = new_test_db()?;
4261 const SOURCE_UID: u32 = 1u32;
4262 const DESTINATION_UID: u32 = 2u32;
4263 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4264 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4265 let key_id_guard =
4266 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4267 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4268
4269 let source_descriptor: KeyDescriptor = KeyDescriptor {
4270 domain: Domain::APP,
4271 nspace: -1,
4272 alias: Some(SOURCE_ALIAS.to_string()),
4273 blob: None,
4274 };
4275
4276 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4277 domain: Domain::APP,
4278 nspace: -1,
4279 alias: Some(DESTINATION_ALIAS.to_string()),
4280 blob: None,
4281 };
4282
4283 let key_id = key_id_guard.id();
4284
4285 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4286 Ok(())
4287 })
4288 .unwrap();
4289
4290 let (_, key_entry) = db
4291 .load_key_entry(
4292 &destination_descriptor,
4293 KeyType::Client,
4294 KeyEntryLoadBits::BOTH,
4295 DESTINATION_UID,
4296 |k, av| {
4297 assert_eq!(Domain::APP, k.domain);
4298 assert_eq!(DESTINATION_UID as i64, k.nspace);
4299 assert!(av.is_none());
4300 Ok(())
4301 },
4302 )
4303 .unwrap();
4304
4305 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4306
4307 assert_eq!(
4308 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4309 db.load_key_entry(
4310 &source_descriptor,
4311 KeyType::Client,
4312 KeyEntryLoadBits::NONE,
4313 SOURCE_UID,
4314 |_k, _av| Ok(()),
4315 )
4316 .unwrap_err()
4317 .root_cause()
4318 .downcast_ref::<KsError>()
4319 );
4320
4321 Ok(())
4322 }
4323
4324 // Creates a key migrates it to a different location and then tries to access it by the old
4325 // and new location.
4326 #[test]
4327 fn test_migrate_key_app_to_selinux() -> Result<()> {
4328 let mut db = new_test_db()?;
4329 const SOURCE_UID: u32 = 1u32;
4330 const DESTINATION_UID: u32 = 2u32;
4331 const DESTINATION_NAMESPACE: i64 = 1000i64;
4332 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4333 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4334 let key_id_guard =
4335 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4336 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4337
4338 let source_descriptor: KeyDescriptor = KeyDescriptor {
4339 domain: Domain::APP,
4340 nspace: -1,
4341 alias: Some(SOURCE_ALIAS.to_string()),
4342 blob: None,
4343 };
4344
4345 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4346 domain: Domain::SELINUX,
4347 nspace: DESTINATION_NAMESPACE,
4348 alias: Some(DESTINATION_ALIAS.to_string()),
4349 blob: None,
4350 };
4351
4352 let key_id = key_id_guard.id();
4353
4354 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4355 Ok(())
4356 })
4357 .unwrap();
4358
4359 let (_, key_entry) = db
4360 .load_key_entry(
4361 &destination_descriptor,
4362 KeyType::Client,
4363 KeyEntryLoadBits::BOTH,
4364 DESTINATION_UID,
4365 |k, av| {
4366 assert_eq!(Domain::SELINUX, k.domain);
4367 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4368 assert!(av.is_none());
4369 Ok(())
4370 },
4371 )
4372 .unwrap();
4373
4374 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4375
4376 assert_eq!(
4377 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4378 db.load_key_entry(
4379 &source_descriptor,
4380 KeyType::Client,
4381 KeyEntryLoadBits::NONE,
4382 SOURCE_UID,
4383 |_k, _av| Ok(()),
4384 )
4385 .unwrap_err()
4386 .root_cause()
4387 .downcast_ref::<KsError>()
4388 );
4389
4390 Ok(())
4391 }
4392
4393 // Creates two keys and tries to migrate the first to the location of the second which
4394 // is expected to fail.
4395 #[test]
4396 fn test_migrate_key_destination_occupied() -> Result<()> {
4397 let mut db = new_test_db()?;
4398 const SOURCE_UID: u32 = 1u32;
4399 const DESTINATION_UID: u32 = 2u32;
4400 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4401 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4402 let key_id_guard =
4403 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4404 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4405 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4406 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4407
4408 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4409 domain: Domain::APP,
4410 nspace: -1,
4411 alias: Some(DESTINATION_ALIAS.to_string()),
4412 blob: None,
4413 };
4414
4415 assert_eq!(
4416 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4417 db.migrate_key_namespace(
4418 key_id_guard,
4419 &destination_descriptor,
4420 DESTINATION_UID,
4421 |_k| Ok(())
4422 )
4423 .unwrap_err()
4424 .root_cause()
4425 .downcast_ref::<KsError>()
4426 );
4427
4428 Ok(())
4429 }
4430
Janis Danisevskisaec14592020-11-12 09:41:49 -08004431 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4432
Janis Danisevskisaec14592020-11-12 09:41:49 -08004433 #[test]
4434 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4435 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004436 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4437 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004438 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004439 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004440 .context("test_insert_and_load_full_keyentry_domain_app")?
4441 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004442 let (_key_guard, key_entry) = db
4443 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004444 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004445 domain: Domain::APP,
4446 nspace: 0,
4447 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4448 blob: None,
4449 },
4450 KeyType::Client,
4451 KeyEntryLoadBits::BOTH,
4452 33,
4453 |_k, _av| Ok(()),
4454 )
4455 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004456 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004457 let state = Arc::new(AtomicU8::new(1));
4458 let state2 = state.clone();
4459
4460 // Spawning a second thread that attempts to acquire the key id lock
4461 // for the same key as the primary thread. The primary thread then
4462 // waits, thereby forcing the secondary thread into the second stage
4463 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4464 // The test succeeds if the secondary thread observes the transition
4465 // of `state` from 1 to 2, despite having a whole second to overtake
4466 // the primary thread.
4467 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004468 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004469 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004470 assert!(db
4471 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004472 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004473 domain: Domain::APP,
4474 nspace: 0,
4475 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4476 blob: None,
4477 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004478 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004479 KeyEntryLoadBits::BOTH,
4480 33,
4481 |_k, _av| Ok(()),
4482 )
4483 .is_ok());
4484 // We should only see a 2 here because we can only return
4485 // from load_key_entry when the `_key_guard` expires,
4486 // which happens at the end of the scope.
4487 assert_eq!(2, state2.load(Ordering::Relaxed));
4488 });
4489
4490 thread::sleep(std::time::Duration::from_millis(1000));
4491
4492 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4493
4494 // Return the handle from this scope so we can join with the
4495 // secondary thread after the key id lock has expired.
4496 handle
4497 // This is where the `_key_guard` goes out of scope,
4498 // which is the reason for concurrent load_key_entry on the same key
4499 // to unblock.
4500 };
4501 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4502 // main test thread. We will not see failing asserts in secondary threads otherwise.
4503 handle.join().unwrap();
4504 Ok(())
4505 }
4506
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004507 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004508 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004509 let temp_dir =
4510 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4511
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004512 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4513 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004514
4515 let _tx1 = db1
4516 .conn
4517 .transaction_with_behavior(TransactionBehavior::Immediate)
4518 .expect("Failed to create first transaction.");
4519
4520 let error = db2
4521 .conn
4522 .transaction_with_behavior(TransactionBehavior::Immediate)
4523 .context("Transaction begin failed.")
4524 .expect_err("This should fail.");
4525 let root_cause = error.root_cause();
4526 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4527 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4528 {
4529 return;
4530 }
4531 panic!(
4532 "Unexpected error {:?} \n{:?} \n{:?}",
4533 error,
4534 root_cause,
4535 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4536 )
4537 }
4538
4539 #[cfg(disabled)]
4540 #[test]
4541 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4542 let temp_dir = Arc::new(
4543 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4544 .expect("Failed to create temp dir."),
4545 );
4546
4547 let test_begin = Instant::now();
4548
4549 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4550 const KEY_COUNT: u32 = 500u32;
4551 const OPEN_DB_COUNT: u32 = 50u32;
4552
4553 let mut actual_key_count = KEY_COUNT;
4554 // First insert KEY_COUNT keys.
4555 for count in 0..KEY_COUNT {
4556 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4557 actual_key_count = count;
4558 break;
4559 }
4560 let alias = format!("test_alias_{}", count);
4561 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4562 .expect("Failed to make key entry.");
4563 }
4564
4565 // Insert more keys from a different thread and into a different namespace.
4566 let temp_dir1 = temp_dir.clone();
4567 let handle1 = thread::spawn(move || {
4568 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4569
4570 for count in 0..actual_key_count {
4571 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4572 return;
4573 }
4574 let alias = format!("test_alias_{}", count);
4575 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4576 .expect("Failed to make key entry.");
4577 }
4578
4579 // then unbind them again.
4580 for count in 0..actual_key_count {
4581 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4582 return;
4583 }
4584 let key = KeyDescriptor {
4585 domain: Domain::APP,
4586 nspace: -1,
4587 alias: Some(format!("test_alias_{}", count)),
4588 blob: None,
4589 };
4590 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4591 }
4592 });
4593
4594 // And start unbinding the first set of keys.
4595 let temp_dir2 = temp_dir.clone();
4596 let handle2 = thread::spawn(move || {
4597 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4598
4599 for count in 0..actual_key_count {
4600 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4601 return;
4602 }
4603 let key = KeyDescriptor {
4604 domain: Domain::APP,
4605 nspace: -1,
4606 alias: Some(format!("test_alias_{}", count)),
4607 blob: None,
4608 };
4609 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4610 }
4611 });
4612
4613 let stop_deleting = Arc::new(AtomicU8::new(0));
4614 let stop_deleting2 = stop_deleting.clone();
4615
4616 // And delete anything that is unreferenced keys.
4617 let temp_dir3 = temp_dir.clone();
4618 let handle3 = thread::spawn(move || {
4619 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4620
4621 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4622 while let Some((key_guard, _key)) =
4623 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4624 {
4625 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4626 return;
4627 }
4628 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4629 }
4630 std::thread::sleep(std::time::Duration::from_millis(100));
4631 }
4632 });
4633
4634 // While a lot of inserting and deleting is going on we have to open database connections
4635 // successfully and use them.
4636 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4637 // out of scope.
4638 #[allow(clippy::redundant_clone)]
4639 let temp_dir4 = temp_dir.clone();
4640 let handle4 = thread::spawn(move || {
4641 for count in 0..OPEN_DB_COUNT {
4642 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4643 return;
4644 }
4645 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4646
4647 let alias = format!("test_alias_{}", count);
4648 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4649 .expect("Failed to make key entry.");
4650 let key = KeyDescriptor {
4651 domain: Domain::APP,
4652 nspace: -1,
4653 alias: Some(alias),
4654 blob: None,
4655 };
4656 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4657 }
4658 });
4659
4660 handle1.join().expect("Thread 1 panicked.");
4661 handle2.join().expect("Thread 2 panicked.");
4662 handle4.join().expect("Thread 4 panicked.");
4663
4664 stop_deleting.store(1, Ordering::Relaxed);
4665 handle3.join().expect("Thread 3 panicked.");
4666
4667 Ok(())
4668 }
4669
4670 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004671 fn list() -> Result<()> {
4672 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004673 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004674 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4675 (Domain::APP, 1, "test1"),
4676 (Domain::APP, 1, "test2"),
4677 (Domain::APP, 1, "test3"),
4678 (Domain::APP, 1, "test4"),
4679 (Domain::APP, 1, "test5"),
4680 (Domain::APP, 1, "test6"),
4681 (Domain::APP, 1, "test7"),
4682 (Domain::APP, 2, "test1"),
4683 (Domain::APP, 2, "test2"),
4684 (Domain::APP, 2, "test3"),
4685 (Domain::APP, 2, "test4"),
4686 (Domain::APP, 2, "test5"),
4687 (Domain::APP, 2, "test6"),
4688 (Domain::APP, 2, "test8"),
4689 (Domain::SELINUX, 100, "test1"),
4690 (Domain::SELINUX, 100, "test2"),
4691 (Domain::SELINUX, 100, "test3"),
4692 (Domain::SELINUX, 100, "test4"),
4693 (Domain::SELINUX, 100, "test5"),
4694 (Domain::SELINUX, 100, "test6"),
4695 (Domain::SELINUX, 100, "test9"),
4696 ];
4697
4698 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4699 .iter()
4700 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004701 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4702 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004703 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4704 });
4705 (entry.id(), *ns)
4706 })
4707 .collect();
4708
4709 for (domain, namespace) in
4710 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4711 {
4712 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4713 .iter()
4714 .filter_map(|(domain, ns, alias)| match ns {
4715 ns if *ns == *namespace => Some(KeyDescriptor {
4716 domain: *domain,
4717 nspace: *ns,
4718 alias: Some(alias.to_string()),
4719 blob: None,
4720 }),
4721 _ => None,
4722 })
4723 .collect();
4724 list_o_descriptors.sort();
4725 let mut list_result = db.list(*domain, *namespace)?;
4726 list_result.sort();
4727 assert_eq!(list_o_descriptors, list_result);
4728
4729 let mut list_o_ids: Vec<i64> = list_o_descriptors
4730 .into_iter()
4731 .map(|d| {
4732 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004733 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004734 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004735 KeyType::Client,
4736 KeyEntryLoadBits::NONE,
4737 *namespace as u32,
4738 |_, _| Ok(()),
4739 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004740 .unwrap();
4741 entry.id()
4742 })
4743 .collect();
4744 list_o_ids.sort_unstable();
4745 let mut loaded_entries: Vec<i64> = list_o_keys
4746 .iter()
4747 .filter_map(|(id, ns)| match ns {
4748 ns if *ns == *namespace => Some(*id),
4749 _ => None,
4750 })
4751 .collect();
4752 loaded_entries.sort_unstable();
4753 assert_eq!(list_o_ids, loaded_entries);
4754 }
4755 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4756
4757 Ok(())
4758 }
4759
Joel Galenson0891bc12020-07-20 10:37:03 -07004760 // Helpers
4761
4762 // Checks that the given result is an error containing the given string.
4763 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4764 let error_str = format!(
4765 "{:#?}",
4766 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4767 );
4768 assert!(
4769 error_str.contains(target),
4770 "The string \"{}\" should contain \"{}\"",
4771 error_str,
4772 target
4773 );
4774 }
4775
Joel Galenson2aab4432020-07-22 15:27:57 -07004776 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004777 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004778 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004779 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004780 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004781 namespace: Option<i64>,
4782 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004783 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004784 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004785 }
4786
4787 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4788 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004789 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004790 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004791 Ok(KeyEntryRow {
4792 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004793 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004794 domain: match row.get(2)? {
4795 Some(i) => Some(Domain(i)),
4796 None => None,
4797 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004798 namespace: row.get(3)?,
4799 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004800 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004801 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004802 })
4803 })?
4804 .map(|r| r.context("Could not read keyentry row."))
4805 .collect::<Result<Vec<_>>>()
4806 }
4807
Max Biresb2e1d032021-02-08 21:35:05 -08004808 struct RemoteProvValues {
4809 cert_chain: Vec<u8>,
4810 priv_key: Vec<u8>,
4811 batch_cert: Vec<u8>,
4812 }
4813
Max Bires2b2e6562020-09-22 11:22:36 -07004814 fn load_attestation_key_pool(
4815 db: &mut KeystoreDB,
4816 expiration_date: i64,
4817 namespace: i64,
4818 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004819 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004820 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4821 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4822 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4823 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004824 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004825 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4826 db.store_signed_attestation_certificate_chain(
4827 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004828 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004829 &cert_chain,
4830 expiration_date,
4831 &KEYSTORE_UUID,
4832 )?;
4833 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004834 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004835 }
4836
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004837 // Note: The parameters and SecurityLevel associations are nonsensical. This
4838 // collection is only used to check if the parameters are preserved as expected by the
4839 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004840 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4841 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004842 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4843 KeyParameter::new(
4844 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4845 SecurityLevel::TRUSTED_ENVIRONMENT,
4846 ),
4847 KeyParameter::new(
4848 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4849 SecurityLevel::TRUSTED_ENVIRONMENT,
4850 ),
4851 KeyParameter::new(
4852 KeyParameterValue::Algorithm(Algorithm::RSA),
4853 SecurityLevel::TRUSTED_ENVIRONMENT,
4854 ),
4855 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4856 KeyParameter::new(
4857 KeyParameterValue::BlockMode(BlockMode::ECB),
4858 SecurityLevel::TRUSTED_ENVIRONMENT,
4859 ),
4860 KeyParameter::new(
4861 KeyParameterValue::BlockMode(BlockMode::GCM),
4862 SecurityLevel::TRUSTED_ENVIRONMENT,
4863 ),
4864 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4865 KeyParameter::new(
4866 KeyParameterValue::Digest(Digest::MD5),
4867 SecurityLevel::TRUSTED_ENVIRONMENT,
4868 ),
4869 KeyParameter::new(
4870 KeyParameterValue::Digest(Digest::SHA_2_224),
4871 SecurityLevel::TRUSTED_ENVIRONMENT,
4872 ),
4873 KeyParameter::new(
4874 KeyParameterValue::Digest(Digest::SHA_2_256),
4875 SecurityLevel::STRONGBOX,
4876 ),
4877 KeyParameter::new(
4878 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4879 SecurityLevel::TRUSTED_ENVIRONMENT,
4880 ),
4881 KeyParameter::new(
4882 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4883 SecurityLevel::TRUSTED_ENVIRONMENT,
4884 ),
4885 KeyParameter::new(
4886 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4887 SecurityLevel::STRONGBOX,
4888 ),
4889 KeyParameter::new(
4890 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4891 SecurityLevel::TRUSTED_ENVIRONMENT,
4892 ),
4893 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4894 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4895 KeyParameter::new(
4896 KeyParameterValue::EcCurve(EcCurve::P_224),
4897 SecurityLevel::TRUSTED_ENVIRONMENT,
4898 ),
4899 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4900 KeyParameter::new(
4901 KeyParameterValue::EcCurve(EcCurve::P_384),
4902 SecurityLevel::TRUSTED_ENVIRONMENT,
4903 ),
4904 KeyParameter::new(
4905 KeyParameterValue::EcCurve(EcCurve::P_521),
4906 SecurityLevel::TRUSTED_ENVIRONMENT,
4907 ),
4908 KeyParameter::new(
4909 KeyParameterValue::RSAPublicExponent(3),
4910 SecurityLevel::TRUSTED_ENVIRONMENT,
4911 ),
4912 KeyParameter::new(
4913 KeyParameterValue::IncludeUniqueID,
4914 SecurityLevel::TRUSTED_ENVIRONMENT,
4915 ),
4916 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4917 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4918 KeyParameter::new(
4919 KeyParameterValue::ActiveDateTime(1234567890),
4920 SecurityLevel::STRONGBOX,
4921 ),
4922 KeyParameter::new(
4923 KeyParameterValue::OriginationExpireDateTime(1234567890),
4924 SecurityLevel::TRUSTED_ENVIRONMENT,
4925 ),
4926 KeyParameter::new(
4927 KeyParameterValue::UsageExpireDateTime(1234567890),
4928 SecurityLevel::TRUSTED_ENVIRONMENT,
4929 ),
4930 KeyParameter::new(
4931 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4932 SecurityLevel::TRUSTED_ENVIRONMENT,
4933 ),
4934 KeyParameter::new(
4935 KeyParameterValue::MaxUsesPerBoot(1234567890),
4936 SecurityLevel::TRUSTED_ENVIRONMENT,
4937 ),
4938 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4939 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4940 KeyParameter::new(
4941 KeyParameterValue::NoAuthRequired,
4942 SecurityLevel::TRUSTED_ENVIRONMENT,
4943 ),
4944 KeyParameter::new(
4945 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4946 SecurityLevel::TRUSTED_ENVIRONMENT,
4947 ),
4948 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4949 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4950 KeyParameter::new(
4951 KeyParameterValue::TrustedUserPresenceRequired,
4952 SecurityLevel::TRUSTED_ENVIRONMENT,
4953 ),
4954 KeyParameter::new(
4955 KeyParameterValue::TrustedConfirmationRequired,
4956 SecurityLevel::TRUSTED_ENVIRONMENT,
4957 ),
4958 KeyParameter::new(
4959 KeyParameterValue::UnlockedDeviceRequired,
4960 SecurityLevel::TRUSTED_ENVIRONMENT,
4961 ),
4962 KeyParameter::new(
4963 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4964 SecurityLevel::SOFTWARE,
4965 ),
4966 KeyParameter::new(
4967 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4968 SecurityLevel::SOFTWARE,
4969 ),
4970 KeyParameter::new(
4971 KeyParameterValue::CreationDateTime(12345677890),
4972 SecurityLevel::SOFTWARE,
4973 ),
4974 KeyParameter::new(
4975 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4976 SecurityLevel::TRUSTED_ENVIRONMENT,
4977 ),
4978 KeyParameter::new(
4979 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4980 SecurityLevel::TRUSTED_ENVIRONMENT,
4981 ),
4982 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4983 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4984 KeyParameter::new(
4985 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4986 SecurityLevel::SOFTWARE,
4987 ),
4988 KeyParameter::new(
4989 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4990 SecurityLevel::TRUSTED_ENVIRONMENT,
4991 ),
4992 KeyParameter::new(
4993 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4994 SecurityLevel::TRUSTED_ENVIRONMENT,
4995 ),
4996 KeyParameter::new(
4997 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4998 SecurityLevel::TRUSTED_ENVIRONMENT,
4999 ),
5000 KeyParameter::new(
5001 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5002 SecurityLevel::TRUSTED_ENVIRONMENT,
5003 ),
5004 KeyParameter::new(
5005 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5006 SecurityLevel::TRUSTED_ENVIRONMENT,
5007 ),
5008 KeyParameter::new(
5009 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5010 SecurityLevel::TRUSTED_ENVIRONMENT,
5011 ),
5012 KeyParameter::new(
5013 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5014 SecurityLevel::TRUSTED_ENVIRONMENT,
5015 ),
5016 KeyParameter::new(
5017 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5018 SecurityLevel::TRUSTED_ENVIRONMENT,
5019 ),
5020 KeyParameter::new(
5021 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5022 SecurityLevel::TRUSTED_ENVIRONMENT,
5023 ),
5024 KeyParameter::new(
5025 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5026 SecurityLevel::TRUSTED_ENVIRONMENT,
5027 ),
5028 KeyParameter::new(
5029 KeyParameterValue::VendorPatchLevel(3),
5030 SecurityLevel::TRUSTED_ENVIRONMENT,
5031 ),
5032 KeyParameter::new(
5033 KeyParameterValue::BootPatchLevel(4),
5034 SecurityLevel::TRUSTED_ENVIRONMENT,
5035 ),
5036 KeyParameter::new(
5037 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5038 SecurityLevel::TRUSTED_ENVIRONMENT,
5039 ),
5040 KeyParameter::new(
5041 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5042 SecurityLevel::TRUSTED_ENVIRONMENT,
5043 ),
5044 KeyParameter::new(
5045 KeyParameterValue::MacLength(256),
5046 SecurityLevel::TRUSTED_ENVIRONMENT,
5047 ),
5048 KeyParameter::new(
5049 KeyParameterValue::ResetSinceIdRotation,
5050 SecurityLevel::TRUSTED_ENVIRONMENT,
5051 ),
5052 KeyParameter::new(
5053 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5054 SecurityLevel::TRUSTED_ENVIRONMENT,
5055 ),
Qi Wub9433b52020-12-01 14:52:46 +08005056 ];
5057 if let Some(value) = max_usage_count {
5058 params.push(KeyParameter::new(
5059 KeyParameterValue::UsageCountLimit(value),
5060 SecurityLevel::SOFTWARE,
5061 ));
5062 }
5063 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005064 }
5065
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005066 fn make_test_key_entry(
5067 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005068 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005069 namespace: i64,
5070 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005071 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005072 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005073 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005074 let mut blob_metadata = BlobMetaData::new();
5075 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5076 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5077 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5078 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5079 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5080
5081 db.set_blob(
5082 &key_id,
5083 SubComponentType::KEY_BLOB,
5084 Some(TEST_KEY_BLOB),
5085 Some(&blob_metadata),
5086 )?;
5087 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5088 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005089
5090 let params = make_test_params(max_usage_count);
5091 db.insert_keyparameter(&key_id, &params)?;
5092
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005093 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005094 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005095 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005096 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005097 Ok(key_id)
5098 }
5099
Qi Wub9433b52020-12-01 14:52:46 +08005100 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5101 let params = make_test_params(max_usage_count);
5102
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005103 let mut blob_metadata = BlobMetaData::new();
5104 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5105 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5106 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5107 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5108 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5109
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005110 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005111 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005112
5113 KeyEntry {
5114 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005115 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005116 cert: Some(TEST_CERT_BLOB.to_vec()),
5117 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005118 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005119 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005120 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005121 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005122 }
5123 }
5124
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005125 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005126 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005127 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005128 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005129 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005130 NO_PARAMS,
5131 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005132 Ok((
5133 row.get(0)?,
5134 row.get(1)?,
5135 row.get(2)?,
5136 row.get(3)?,
5137 row.get(4)?,
5138 row.get(5)?,
5139 row.get(6)?,
5140 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005141 },
5142 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005143
5144 println!("Key entry table rows:");
5145 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005146 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005147 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005148 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5149 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005150 );
5151 }
5152 Ok(())
5153 }
5154
5155 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005156 let mut stmt = db
5157 .conn
5158 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005159 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5160 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5161 })?;
5162
5163 println!("Grant table rows:");
5164 for r in rows {
5165 let (id, gt, ki, av) = r.unwrap();
5166 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5167 }
5168 Ok(())
5169 }
5170
Joel Galenson0891bc12020-07-20 10:37:03 -07005171 // Use a custom random number generator that repeats each number once.
5172 // This allows us to test repeated elements.
5173
5174 thread_local! {
5175 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5176 }
5177
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005178 fn reset_random() {
5179 RANDOM_COUNTER.with(|counter| {
5180 *counter.borrow_mut() = 0;
5181 })
5182 }
5183
Joel Galenson0891bc12020-07-20 10:37:03 -07005184 pub fn random() -> i64 {
5185 RANDOM_COUNTER.with(|counter| {
5186 let result = *counter.borrow() / 2;
5187 *counter.borrow_mut() += 1;
5188 result
5189 })
5190 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005191
5192 #[test]
5193 fn test_last_off_body() -> Result<()> {
5194 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005195 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005196 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005197 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005198 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005199 let one_second = Duration::from_secs(1);
5200 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005201 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005202 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005203 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005204 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005205 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5206 Ok(())
5207 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005208
5209 #[test]
5210 fn test_unbind_keys_for_user() -> Result<()> {
5211 let mut db = new_test_db()?;
5212 db.unbind_keys_for_user(1, false)?;
5213
5214 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5215 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5216 db.unbind_keys_for_user(2, false)?;
5217
5218 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5219 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5220
5221 db.unbind_keys_for_user(1, true)?;
5222 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5223
5224 Ok(())
5225 }
5226
5227 #[test]
5228 fn test_store_super_key() -> Result<()> {
5229 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005230 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005231 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005232 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005233 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005234 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005235
5236 let (encrypted_super_key, metadata) =
5237 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005238 db.store_super_key(
5239 1,
5240 &USER_SUPER_KEY,
5241 &encrypted_super_key,
5242 &metadata,
5243 &KeyMetaData::new(),
5244 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005245
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005246 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005247 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005248
Paul Crowley7a658392021-03-18 17:08:20 -07005249 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005250 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5251 USER_SUPER_KEY.algorithm,
5252 key_entry,
5253 &pw,
5254 None,
5255 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005256
Paul Crowley7a658392021-03-18 17:08:20 -07005257 let decrypted_secret_bytes =
5258 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5259 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005260 Ok(())
5261 }
Seth Moore78c091f2021-04-09 21:38:30 +00005262
5263 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5264 vec![
5265 StatsdStorageType::KeyEntry,
5266 StatsdStorageType::KeyEntryIdIndex,
5267 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5268 StatsdStorageType::BlobEntry,
5269 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5270 StatsdStorageType::KeyParameter,
5271 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5272 StatsdStorageType::KeyMetadata,
5273 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5274 StatsdStorageType::Grant,
5275 StatsdStorageType::AuthToken,
5276 StatsdStorageType::BlobMetadata,
5277 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5278 ]
5279 }
5280
5281 /// Perform a simple check to ensure that we can query all the storage types
5282 /// that are supported by the DB. Check for reasonable values.
5283 #[test]
5284 fn test_query_all_valid_table_sizes() -> Result<()> {
5285 const PAGE_SIZE: i64 = 4096;
5286
5287 let mut db = new_test_db()?;
5288
5289 for t in get_valid_statsd_storage_types() {
5290 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005291 // AuthToken can be less than a page since it's in a btree, not sqlite
5292 // TODO(b/187474736) stop using if-let here
5293 if let StatsdStorageType::AuthToken = t {
5294 } else {
5295 assert!(stat.size >= PAGE_SIZE);
5296 }
Seth Moore78c091f2021-04-09 21:38:30 +00005297 assert!(stat.size >= stat.unused_size);
5298 }
5299
5300 Ok(())
5301 }
5302
5303 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5304 get_valid_statsd_storage_types()
5305 .into_iter()
5306 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5307 .collect()
5308 }
5309
5310 fn assert_storage_increased(
5311 db: &mut KeystoreDB,
5312 increased_storage_types: Vec<StatsdStorageType>,
5313 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5314 ) {
5315 for storage in increased_storage_types {
5316 // Verify the expected storage increased.
5317 let new = db.get_storage_stat(storage).unwrap();
5318 let storage = storage as i32;
5319 let old = &baseline[&storage];
5320 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5321 assert!(
5322 new.unused_size <= old.unused_size,
5323 "{}: {} <= {}",
5324 storage,
5325 new.unused_size,
5326 old.unused_size
5327 );
5328
5329 // Update the baseline with the new value so that it succeeds in the
5330 // later comparison.
5331 baseline.insert(storage, new);
5332 }
5333
5334 // Get an updated map of the storage and verify there were no unexpected changes.
5335 let updated_stats = get_storage_stats_map(db);
5336 assert_eq!(updated_stats.len(), baseline.len());
5337
5338 for &k in baseline.keys() {
5339 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5340 let mut s = String::new();
5341 for &k in map.keys() {
5342 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5343 .expect("string concat failed");
5344 }
5345 s
5346 };
5347
5348 assert!(
5349 updated_stats[&k].size == baseline[&k].size
5350 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5351 "updated_stats:\n{}\nbaseline:\n{}",
5352 stringify(&updated_stats),
5353 stringify(&baseline)
5354 );
5355 }
5356 }
5357
5358 #[test]
5359 fn test_verify_key_table_size_reporting() -> Result<()> {
5360 let mut db = new_test_db()?;
5361 let mut working_stats = get_storage_stats_map(&mut db);
5362
5363 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5364 assert_storage_increased(
5365 &mut db,
5366 vec![
5367 StatsdStorageType::KeyEntry,
5368 StatsdStorageType::KeyEntryIdIndex,
5369 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5370 ],
5371 &mut working_stats,
5372 );
5373
5374 let mut blob_metadata = BlobMetaData::new();
5375 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5376 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5377 assert_storage_increased(
5378 &mut db,
5379 vec![
5380 StatsdStorageType::BlobEntry,
5381 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5382 StatsdStorageType::BlobMetadata,
5383 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5384 ],
5385 &mut working_stats,
5386 );
5387
5388 let params = make_test_params(None);
5389 db.insert_keyparameter(&key_id, &params)?;
5390 assert_storage_increased(
5391 &mut db,
5392 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5393 &mut working_stats,
5394 );
5395
5396 let mut metadata = KeyMetaData::new();
5397 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5398 db.insert_key_metadata(&key_id, &metadata)?;
5399 assert_storage_increased(
5400 &mut db,
5401 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5402 &mut working_stats,
5403 );
5404
5405 let mut sum = 0;
5406 for stat in working_stats.values() {
5407 sum += stat.size;
5408 }
5409 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5410 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5411
5412 Ok(())
5413 }
5414
5415 #[test]
5416 fn test_verify_auth_table_size_reporting() -> Result<()> {
5417 let mut db = new_test_db()?;
5418 let mut working_stats = get_storage_stats_map(&mut db);
5419 db.insert_auth_token(&HardwareAuthToken {
5420 challenge: 123,
5421 userId: 456,
5422 authenticatorId: 789,
5423 authenticatorType: kmhw_authenticator_type::ANY,
5424 timestamp: Timestamp { milliSeconds: 10 },
5425 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005426 });
Seth Moore78c091f2021-04-09 21:38:30 +00005427 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5428 Ok(())
5429 }
5430
5431 #[test]
5432 fn test_verify_grant_table_size_reporting() -> Result<()> {
5433 const OWNER: i64 = 1;
5434 let mut db = new_test_db()?;
5435 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5436
5437 let mut working_stats = get_storage_stats_map(&mut db);
5438 db.grant(
5439 &KeyDescriptor {
5440 domain: Domain::APP,
5441 nspace: 0,
5442 alias: Some(TEST_ALIAS.to_string()),
5443 blob: None,
5444 },
5445 OWNER as u32,
5446 123,
5447 key_perm_set![KeyPerm::use_()],
5448 |_, _| Ok(()),
5449 )?;
5450
5451 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5452
5453 Ok(())
5454 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005455
5456 #[test]
5457 fn find_auth_token_entry_returns_latest() -> Result<()> {
5458 let mut db = new_test_db()?;
5459 db.insert_auth_token(&HardwareAuthToken {
5460 challenge: 123,
5461 userId: 456,
5462 authenticatorId: 789,
5463 authenticatorType: kmhw_authenticator_type::ANY,
5464 timestamp: Timestamp { milliSeconds: 10 },
5465 mac: b"mac0".to_vec(),
5466 });
5467 std::thread::sleep(std::time::Duration::from_millis(1));
5468 db.insert_auth_token(&HardwareAuthToken {
5469 challenge: 123,
5470 userId: 457,
5471 authenticatorId: 789,
5472 authenticatorType: kmhw_authenticator_type::ANY,
5473 timestamp: Timestamp { milliSeconds: 12 },
5474 mac: b"mac1".to_vec(),
5475 });
5476 std::thread::sleep(std::time::Duration::from_millis(1));
5477 db.insert_auth_token(&HardwareAuthToken {
5478 challenge: 123,
5479 userId: 458,
5480 authenticatorId: 789,
5481 authenticatorType: kmhw_authenticator_type::ANY,
5482 timestamp: Timestamp { milliSeconds: 3 },
5483 mac: b"mac2".to_vec(),
5484 });
5485 // All three entries are in the database
5486 assert_eq!(db.perboot.auth_tokens_len(), 3);
5487 // It selected the most recent timestamp
5488 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5489 Ok(())
5490 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005491}