blob: 5eb5e307e993deeb18666fea0f18dec6dfb2c231 [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
Seth Moore472fcbb2021-05-12 10:07:51 -0700836 /// Set write-ahead logging mode on the persistent database found in `db_root`.
837 pub fn set_wal_mode(db_root: &Path) -> Result<()> {
838 let path = Self::make_persistent_path(&db_root)?;
839 let conn =
840 Connection::open(path).context("In KeystoreDB::set_wal_mode: Failed to open DB")?;
841 let mode: String = conn
842 .pragma_update_and_check(None, "journal_mode", &"WAL", |row| row.get(0))
843 .context("In KeystoreDB::set_wal_mode: Failed to set journal_mode")?;
844 match mode.as_str() {
845 "wal" => Ok(()),
846 _ => Err(anyhow!("Unable to set WAL mode, db is still in {} mode.", mode)),
847 }
848 }
849
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700850 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800851 /// files persistent.sqlite and perboot.sqlite in the given directory.
852 /// It also attempts to initialize all of the tables.
853 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700854 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700855 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700856 let _wp = wd::watch_millis("KeystoreDB::new", 500);
857
Seth Moore472fcbb2021-05-12 10:07:51 -0700858 let persistent_path = Self::make_persistent_path(&db_root)?;
859 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800860
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700861 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800862 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800863 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 })?;
865 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700866 }
867
Janis Danisevskis66784c42021-01-27 08:40:25 -0800868 fn init_tables(tx: &Transaction) -> Result<()> {
869 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700870 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700871 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800872 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700873 domain INTEGER,
874 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800875 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800876 state INTEGER,
877 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700878 NO_PARAMS,
879 )
880 .context("Failed to initialize \"keyentry\" table.")?;
881
Janis Danisevskis66784c42021-01-27 08:40:25 -0800882 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800883 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
884 ON keyentry(id);",
885 NO_PARAMS,
886 )
887 .context("Failed to create index keyentry_id_index.")?;
888
889 tx.execute(
890 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
891 ON keyentry(domain, namespace, alias);",
892 NO_PARAMS,
893 )
894 .context("Failed to create index keyentry_domain_namespace_index.")?;
895
896 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700897 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
898 id INTEGER PRIMARY KEY,
899 subcomponent_type INTEGER,
900 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800901 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700902 NO_PARAMS,
903 )
904 .context("Failed to initialize \"blobentry\" table.")?;
905
Janis Danisevskis66784c42021-01-27 08:40:25 -0800906 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800907 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
908 ON blobentry(keyentryid);",
909 NO_PARAMS,
910 )
911 .context("Failed to create index blobentry_keyentryid_index.")?;
912
913 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800914 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
915 id INTEGER PRIMARY KEY,
916 blobentryid INTEGER,
917 tag INTEGER,
918 data ANY,
919 UNIQUE (blobentryid, tag));",
920 NO_PARAMS,
921 )
922 .context("Failed to initialize \"blobmetadata\" table.")?;
923
924 tx.execute(
925 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
926 ON blobmetadata(blobentryid);",
927 NO_PARAMS,
928 )
929 .context("Failed to create index blobmetadata_blobentryid_index.")?;
930
931 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700932 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000933 keyentryid INTEGER,
934 tag INTEGER,
935 data ANY,
936 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700937 NO_PARAMS,
938 )
939 .context("Failed to initialize \"keyparameter\" table.")?;
940
Janis Danisevskis66784c42021-01-27 08:40:25 -0800941 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800942 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
943 ON keyparameter(keyentryid);",
944 NO_PARAMS,
945 )
946 .context("Failed to create index keyparameter_keyentryid_index.")?;
947
948 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800949 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
950 keyentryid INTEGER,
951 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000952 data ANY,
953 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800954 NO_PARAMS,
955 )
956 .context("Failed to initialize \"keymetadata\" table.")?;
957
Janis Danisevskis66784c42021-01-27 08:40:25 -0800958 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800959 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
960 ON keymetadata(keyentryid);",
961 NO_PARAMS,
962 )
963 .context("Failed to create index keymetadata_keyentryid_index.")?;
964
965 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800966 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700967 id INTEGER UNIQUE,
968 grantee INTEGER,
969 keyentryid INTEGER,
970 access_vector INTEGER);",
971 NO_PARAMS,
972 )
973 .context("Failed to initialize \"grant\" table.")?;
974
Joel Galenson0891bc12020-07-20 10:37:03 -0700975 Ok(())
976 }
977
Seth Moore472fcbb2021-05-12 10:07:51 -0700978 fn make_persistent_path(db_root: &Path) -> Result<String> {
979 // Build the path to the sqlite file.
980 let mut persistent_path = db_root.to_path_buf();
981 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
982
983 // Now convert them to strings prefixed with "file:"
984 let mut persistent_path_str = "file:".to_owned();
985 persistent_path_str.push_str(&persistent_path.to_string_lossy());
986
987 Ok(persistent_path_str)
988 }
989
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700990 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700991 let conn =
992 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
993
Janis Danisevskis66784c42021-01-27 08:40:25 -0800994 loop {
995 if let Err(e) = conn
996 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
997 .context("Failed to attach database persistent.")
998 {
999 if Self::is_locked_error(&e) {
1000 std::thread::sleep(std::time::Duration::from_micros(500));
1001 continue;
1002 } else {
1003 return Err(e);
1004 }
1005 }
1006 break;
1007 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001008
Matthew Maurer4fb19112021-05-06 15:40:44 -07001009 // Drop the cache size from default (2M) to 0.5M
1010 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1011 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001012
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001013 Ok(conn)
1014 }
1015
Seth Moore78c091f2021-04-09 21:38:30 +00001016 fn do_table_size_query(
1017 &mut self,
1018 storage_type: StatsdStorageType,
1019 query: &str,
1020 params: &[&str],
1021 ) -> Result<Keystore2StorageStats> {
1022 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1023 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1024 .with_context(|| {
1025 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1026 })
1027 .no_gc()
1028 })?;
1029 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1030 }
1031
1032 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1033 self.do_table_size_query(
1034 StatsdStorageType::Database,
1035 "SELECT page_count * page_size, freelist_count * page_size
1036 FROM pragma_page_count('persistent'),
1037 pragma_page_size('persistent'),
1038 persistent.pragma_freelist_count();",
1039 &[],
1040 )
1041 }
1042
1043 fn get_table_size(
1044 &mut self,
1045 storage_type: StatsdStorageType,
1046 schema: &str,
1047 table: &str,
1048 ) -> Result<Keystore2StorageStats> {
1049 self.do_table_size_query(
1050 storage_type,
1051 "SELECT pgsize,unused FROM dbstat(?1)
1052 WHERE name=?2 AND aggregate=TRUE;",
1053 &[schema, table],
1054 )
1055 }
1056
1057 /// Fetches a storage statisitics atom for a given storage type. For storage
1058 /// types that map to a table, information about the table's storage is
1059 /// returned. Requests for storage types that are not DB tables return None.
1060 pub fn get_storage_stat(
1061 &mut self,
1062 storage_type: StatsdStorageType,
1063 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001064 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1065
Seth Moore78c091f2021-04-09 21:38:30 +00001066 match storage_type {
1067 StatsdStorageType::Database => self.get_total_size(),
1068 StatsdStorageType::KeyEntry => {
1069 self.get_table_size(storage_type, "persistent", "keyentry")
1070 }
1071 StatsdStorageType::KeyEntryIdIndex => {
1072 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1073 }
1074 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1075 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1076 }
1077 StatsdStorageType::BlobEntry => {
1078 self.get_table_size(storage_type, "persistent", "blobentry")
1079 }
1080 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1081 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1082 }
1083 StatsdStorageType::KeyParameter => {
1084 self.get_table_size(storage_type, "persistent", "keyparameter")
1085 }
1086 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1087 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1088 }
1089 StatsdStorageType::KeyMetadata => {
1090 self.get_table_size(storage_type, "persistent", "keymetadata")
1091 }
1092 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1093 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1094 }
1095 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1096 StatsdStorageType::AuthToken => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001097 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1098 // reportable
1099 // Size provided is only an approximation
1100 Ok(Keystore2StorageStats {
1101 storage_type,
1102 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1103 as i64,
1104 unused_size: 0,
1105 })
Seth Moore78c091f2021-04-09 21:38:30 +00001106 }
1107 StatsdStorageType::BlobMetadata => {
1108 self.get_table_size(storage_type, "persistent", "blobmetadata")
1109 }
1110 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1111 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1112 }
1113 _ => Err(anyhow::Error::msg(format!(
1114 "Unsupported storage type: {}",
1115 storage_type as i32
1116 ))),
1117 }
1118 }
1119
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001120 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001121 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1122 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001123 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1124 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001125 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001126 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001127 blob_ids_to_delete: &[i64],
1128 max_blobs: usize,
1129 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001130 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001131 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001132 // Delete the given blobs.
1133 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001134 tx.execute(
1135 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001136 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001137 )
1138 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001139 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1140 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001141 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001142
1143 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1144
Janis Danisevskis3395f862021-05-06 10:54:17 -07001145 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1146 let result: Vec<(i64, Vec<u8>)> = {
1147 let mut stmt = tx
1148 .prepare(
1149 "SELECT id, blob FROM persistent.blobentry
1150 WHERE subcomponent_type = ?
1151 AND (
1152 id NOT IN (
1153 SELECT MAX(id) FROM persistent.blobentry
1154 WHERE subcomponent_type = ?
1155 GROUP BY keyentryid, subcomponent_type
1156 )
1157 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1158 ) LIMIT ?;",
1159 )
1160 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161
Janis Danisevskis3395f862021-05-06 10:54:17 -07001162 let rows = stmt
1163 .query_map(
1164 params![
1165 SubComponentType::KEY_BLOB,
1166 SubComponentType::KEY_BLOB,
1167 max_blobs as i64,
1168 ],
1169 |row| Ok((row.get(0)?, row.get(1)?)),
1170 )
1171 .context("Trying to query superseded blob.")?;
1172
1173 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1174 .context("Trying to extract superseded blobs.")?
1175 };
1176
1177 let result = result
1178 .into_iter()
1179 .map(|(blob_id, blob)| {
1180 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1181 })
1182 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1183 .context("Trying to load blob metadata.")?;
1184 if !result.is_empty() {
1185 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001186 }
1187
1188 // We did not find any superseded key blob, so let's remove other superseded blob in
1189 // one transaction.
1190 tx.execute(
1191 "DELETE FROM persistent.blobentry
1192 WHERE NOT subcomponent_type = ?
1193 AND (
1194 id NOT IN (
1195 SELECT MAX(id) FROM persistent.blobentry
1196 WHERE NOT subcomponent_type = ?
1197 GROUP BY keyentryid, subcomponent_type
1198 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1199 );",
1200 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1201 )
1202 .context("Trying to purge superseded blobs.")?;
1203
Janis Danisevskis3395f862021-05-06 10:54:17 -07001204 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001205 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001206 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001207 }
1208
1209 /// This maintenance function should be called only once before the database is used for the
1210 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1211 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1212 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1213 /// Keystore crashed at some point during key generation. Callers may want to log such
1214 /// occurrences.
1215 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1216 /// it to `KeyLifeCycle::Live` may have grants.
1217 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001218 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1219
Janis Danisevskis66784c42021-01-27 08:40:25 -08001220 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1221 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001222 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1223 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1224 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001225 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001226 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001227 })
1228 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001229 }
1230
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001231 /// Checks if a key exists with given key type and key descriptor properties.
1232 pub fn key_exists(
1233 &mut self,
1234 domain: Domain,
1235 nspace: i64,
1236 alias: &str,
1237 key_type: KeyType,
1238 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001239 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1240
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001241 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1242 let key_descriptor =
1243 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1244 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1245 match result {
1246 Ok(_) => Ok(true),
1247 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1248 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1249 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1250 },
1251 }
1252 .no_gc()
1253 })
1254 .context("In key_exists.")
1255 }
1256
Hasini Gunasingheda895552021-01-27 19:34:37 +00001257 /// Stores a super key in the database.
1258 pub fn store_super_key(
1259 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001260 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001261 key_type: &SuperKeyType,
1262 blob: &[u8],
1263 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001264 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001265 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001266 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1267
Hasini Gunasingheda895552021-01-27 19:34:37 +00001268 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1269 let key_id = Self::insert_with_retry(|id| {
1270 tx.execute(
1271 "INSERT into persistent.keyentry
1272 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001273 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001274 params![
1275 id,
1276 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001277 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001278 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001279 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001280 KeyLifeCycle::Live,
1281 &KEYSTORE_UUID,
1282 ],
1283 )
1284 })
1285 .context("Failed to insert into keyentry table.")?;
1286
Paul Crowley8d5b2532021-03-19 10:53:07 -07001287 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1288
Hasini Gunasingheda895552021-01-27 19:34:37 +00001289 Self::set_blob_internal(
1290 &tx,
1291 key_id,
1292 SubComponentType::KEY_BLOB,
1293 Some(blob),
1294 Some(blob_metadata),
1295 )
1296 .context("Failed to store key blob.")?;
1297
1298 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1299 .context("Trying to load key components.")
1300 .no_gc()
1301 })
1302 .context("In store_super_key.")
1303 }
1304
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001305 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001306 pub fn load_super_key(
1307 &mut self,
1308 key_type: &SuperKeyType,
1309 user_id: u32,
1310 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001311 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1312
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001313 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1314 let key_descriptor = KeyDescriptor {
1315 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001316 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001317 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001318 blob: None,
1319 };
1320 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1321 match id {
1322 Ok(id) => {
1323 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1324 .context("In load_super_key. Failed to load key entry.")?;
1325 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1326 }
1327 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1328 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1329 _ => Err(error).context("In load_super_key."),
1330 },
1331 }
1332 .no_gc()
1333 })
1334 .context("In load_super_key.")
1335 }
1336
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001337 /// Atomically loads a key entry and associated metadata or creates it using the
1338 /// callback create_new_key callback. The callback is called during a database
1339 /// transaction. This means that implementers should be mindful about using
1340 /// blocking operations such as IPC or grabbing mutexes.
1341 pub fn get_or_create_key_with<F>(
1342 &mut self,
1343 domain: Domain,
1344 namespace: i64,
1345 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001346 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001347 create_new_key: F,
1348 ) -> Result<(KeyIdGuard, KeyEntry)>
1349 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001350 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001351 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001352 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1353
Janis Danisevskis66784c42021-01-27 08:40:25 -08001354 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1355 let id = {
1356 let mut stmt = tx
1357 .prepare(
1358 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001359 WHERE
1360 key_type = ?
1361 AND domain = ?
1362 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001363 AND alias = ?
1364 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001365 )
1366 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1367 let mut rows = stmt
1368 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1369 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001370
Janis Danisevskis66784c42021-01-27 08:40:25 -08001371 db_utils::with_rows_extract_one(&mut rows, |row| {
1372 Ok(match row {
1373 Some(r) => r.get(0).context("Failed to unpack id.")?,
1374 None => None,
1375 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001376 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001377 .context("In get_or_create_key_with.")?
1378 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001379
Janis Danisevskis66784c42021-01-27 08:40:25 -08001380 let (id, entry) = match id {
1381 Some(id) => (
1382 id,
1383 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1384 .context("In get_or_create_key_with.")?,
1385 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001386
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 None => {
1388 let id = Self::insert_with_retry(|id| {
1389 tx.execute(
1390 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001391 (id, key_type, domain, namespace, alias, state, km_uuid)
1392 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001393 params![
1394 id,
1395 KeyType::Super,
1396 domain.0,
1397 namespace,
1398 alias,
1399 KeyLifeCycle::Live,
1400 km_uuid,
1401 ],
1402 )
1403 })
1404 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001405
Janis Danisevskis66784c42021-01-27 08:40:25 -08001406 let (blob, metadata) =
1407 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001408 Self::set_blob_internal(
1409 &tx,
1410 id,
1411 SubComponentType::KEY_BLOB,
1412 Some(&blob),
1413 Some(&metadata),
1414 )
Paul Crowley7a658392021-03-18 17:08:20 -07001415 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001417 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001418 KeyEntry {
1419 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001420 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001421 pure_cert: false,
1422 ..Default::default()
1423 },
1424 )
1425 }
1426 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001427 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001428 })
1429 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001430 }
1431
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001432 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001433 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1434 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001435 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1436 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001437 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001438 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001439 loop {
1440 match self
1441 .conn
1442 .transaction_with_behavior(behavior)
1443 .context("In with_transaction.")
1444 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1445 .and_then(|(result, tx)| {
1446 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1447 Ok(result)
1448 }) {
1449 Ok(result) => break Ok(result),
1450 Err(e) => {
1451 if Self::is_locked_error(&e) {
1452 std::thread::sleep(std::time::Duration::from_micros(500));
1453 continue;
1454 } else {
1455 return Err(e).context("In with_transaction.");
1456 }
1457 }
1458 }
1459 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001460 .map(|(need_gc, result)| {
1461 if need_gc {
1462 if let Some(ref gc) = self.gc {
1463 gc.notify_gc();
1464 }
1465 }
1466 result
1467 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001468 }
1469
1470 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001471 matches!(
1472 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1473 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1474 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1475 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001476 }
1477
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001478 /// Creates a new key entry and allocates a new randomized id for the new key.
1479 /// The key id gets associated with a domain and namespace but not with an alias.
1480 /// To complete key generation `rebind_alias` should be called after all of the
1481 /// key artifacts, i.e., blobs and parameters have been associated with the new
1482 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1483 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001484 pub fn create_key_entry(
1485 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001486 domain: &Domain,
1487 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001488 km_uuid: &Uuid,
1489 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001490 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1491
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001492 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001493 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001494 })
1495 .context("In create_key_entry.")
1496 }
1497
1498 fn create_key_entry_internal(
1499 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001500 domain: &Domain,
1501 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001502 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001503 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001504 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001505 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001506 _ => {
1507 return Err(KsError::sys())
1508 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1509 }
1510 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001511 Ok(KEY_ID_LOCK.get(
1512 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001513 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001514 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001515 (id, key_type, domain, namespace, alias, state, km_uuid)
1516 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001517 params![
1518 id,
1519 KeyType::Client,
1520 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001521 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001522 KeyLifeCycle::Existing,
1523 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001524 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001525 )
1526 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001527 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001528 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001529 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001530
Max Bires2b2e6562020-09-22 11:22:36 -07001531 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1532 /// The key id gets associated with a domain and namespace later but not with an alias. The
1533 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1534 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1535 /// a key.
1536 pub fn create_attestation_key_entry(
1537 &mut self,
1538 maced_public_key: &[u8],
1539 raw_public_key: &[u8],
1540 private_key: &[u8],
1541 km_uuid: &Uuid,
1542 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001543 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1544
Max Bires2b2e6562020-09-22 11:22:36 -07001545 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1546 let key_id = KEY_ID_LOCK.get(
1547 Self::insert_with_retry(|id| {
1548 tx.execute(
1549 "INSERT into persistent.keyentry
1550 (id, key_type, domain, namespace, alias, state, km_uuid)
1551 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1552 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1553 )
1554 })
1555 .context("In create_key_entry")?,
1556 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001557 Self::set_blob_internal(
1558 &tx,
1559 key_id.0,
1560 SubComponentType::KEY_BLOB,
1561 Some(private_key),
1562 None,
1563 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001564 let mut metadata = KeyMetaData::new();
1565 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1566 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1567 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001568 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001569 })
1570 .context("In create_attestation_key_entry")
1571 }
1572
Janis Danisevskis377d1002021-01-27 19:07:48 -08001573 /// Set a new blob and associates it with the given key id. Each blob
1574 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001575 /// Each key can have one of each sub component type associated. If more
1576 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001577 /// will get garbage collected.
1578 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1579 /// removed by setting blob to None.
1580 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001581 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001582 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001583 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001584 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001585 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001586 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001587 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1588
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001589 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001590 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001591 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001592 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001593 }
1594
Janis Danisevskiseed69842021-02-18 20:04:10 -08001595 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1596 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1597 /// We use this to insert key blobs into the database which can then be garbage collected
1598 /// lazily by the key garbage collector.
1599 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001600 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1601
Janis Danisevskiseed69842021-02-18 20:04:10 -08001602 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1603 Self::set_blob_internal(
1604 &tx,
1605 Self::UNASSIGNED_KEY_ID,
1606 SubComponentType::KEY_BLOB,
1607 Some(blob),
1608 Some(blob_metadata),
1609 )
1610 .need_gc()
1611 })
1612 .context("In set_deleted_blob.")
1613 }
1614
Janis Danisevskis377d1002021-01-27 19:07:48 -08001615 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001616 tx: &Transaction,
1617 key_id: i64,
1618 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001619 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001620 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001621 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001622 match (blob, sc_type) {
1623 (Some(blob), _) => {
1624 tx.execute(
1625 "INSERT INTO persistent.blobentry
1626 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1627 params![sc_type, key_id, blob],
1628 )
1629 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001630 if let Some(blob_metadata) = blob_metadata {
1631 let blob_id = tx
1632 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1633 row.get(0)
1634 })
1635 .context("In set_blob_internal: Failed to get new blob id.")?;
1636 blob_metadata
1637 .store_in_db(blob_id, tx)
1638 .context("In set_blob_internal: Trying to store blob metadata.")?;
1639 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001640 }
1641 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1642 tx.execute(
1643 "DELETE FROM persistent.blobentry
1644 WHERE subcomponent_type = ? AND keyentryid = ?;",
1645 params![sc_type, key_id],
1646 )
1647 .context("In set_blob_internal: Failed to delete blob.")?;
1648 }
1649 (None, _) => {
1650 return Err(KsError::sys())
1651 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1652 }
1653 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001654 Ok(())
1655 }
1656
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001657 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1658 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001659 #[cfg(test)]
1660 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001661 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001662 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001663 })
1664 .context("In insert_keyparameter.")
1665 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001666
Janis Danisevskis66784c42021-01-27 08:40:25 -08001667 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001668 tx: &Transaction,
1669 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001670 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001671 ) -> Result<()> {
1672 let mut stmt = tx
1673 .prepare(
1674 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1675 VALUES (?, ?, ?, ?);",
1676 )
1677 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1678
Janis Danisevskis66784c42021-01-27 08:40:25 -08001679 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001680 stmt.insert(params![
1681 key_id.0,
1682 p.get_tag().0,
1683 p.key_parameter_value(),
1684 p.security_level().0
1685 ])
1686 .with_context(|| {
1687 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1688 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001689 }
1690 Ok(())
1691 }
1692
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001693 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001694 #[cfg(test)]
1695 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001696 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001697 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001698 })
1699 .context("In insert_key_metadata.")
1700 }
1701
Max Bires2b2e6562020-09-22 11:22:36 -07001702 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1703 /// on the public key.
1704 pub fn store_signed_attestation_certificate_chain(
1705 &mut self,
1706 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001707 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001708 cert_chain: &[u8],
1709 expiration_date: i64,
1710 km_uuid: &Uuid,
1711 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001712 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1713
Max Bires2b2e6562020-09-22 11:22:36 -07001714 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1715 let mut stmt = tx
1716 .prepare(
1717 "SELECT keyentryid
1718 FROM persistent.keymetadata
1719 WHERE tag = ? AND data = ? AND keyentryid IN
1720 (SELECT id
1721 FROM persistent.keyentry
1722 WHERE
1723 alias IS NULL AND
1724 domain IS NULL AND
1725 namespace IS NULL AND
1726 key_type = ? AND
1727 km_uuid = ?);",
1728 )
1729 .context("Failed to store attestation certificate chain.")?;
1730 let mut rows = stmt
1731 .query(params![
1732 KeyMetaData::AttestationRawPubKey,
1733 raw_public_key,
1734 KeyType::Attestation,
1735 km_uuid
1736 ])
1737 .context("Failed to fetch keyid")?;
1738 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1739 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1740 .get(0)
1741 .context("Failed to unpack id.")
1742 })
1743 .context("Failed to get key_id.")?;
1744 let num_updated = tx
1745 .execute(
1746 "UPDATE persistent.keyentry
1747 SET alias = ?
1748 WHERE id = ?;",
1749 params!["signed", key_id],
1750 )
1751 .context("Failed to update alias.")?;
1752 if num_updated != 1 {
1753 return Err(KsError::sys()).context("Alias not updated for the key.");
1754 }
1755 let mut metadata = KeyMetaData::new();
1756 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1757 expiration_date,
1758 )));
1759 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001760 Self::set_blob_internal(
1761 &tx,
1762 key_id,
1763 SubComponentType::CERT_CHAIN,
1764 Some(cert_chain),
1765 None,
1766 )
1767 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001768 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1769 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001770 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001771 })
1772 .context("In store_signed_attestation_certificate_chain: ")
1773 }
1774
1775 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1776 /// currently have a key assigned to it.
1777 pub fn assign_attestation_key(
1778 &mut self,
1779 domain: Domain,
1780 namespace: i64,
1781 km_uuid: &Uuid,
1782 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001783 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1784
Max Bires2b2e6562020-09-22 11:22:36 -07001785 match domain {
1786 Domain::APP | Domain::SELINUX => {}
1787 _ => {
1788 return Err(KsError::sys()).context(format!(
1789 concat!(
1790 "In assign_attestation_key: Domain {:?} ",
1791 "must be either App or SELinux.",
1792 ),
1793 domain
1794 ));
1795 }
1796 }
1797 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1798 let result = tx
1799 .execute(
1800 "UPDATE persistent.keyentry
1801 SET domain=?1, namespace=?2
1802 WHERE
1803 id =
1804 (SELECT MIN(id)
1805 FROM persistent.keyentry
1806 WHERE ALIAS IS NOT NULL
1807 AND domain IS NULL
1808 AND key_type IS ?3
1809 AND state IS ?4
1810 AND km_uuid IS ?5)
1811 AND
1812 (SELECT COUNT(*)
1813 FROM persistent.keyentry
1814 WHERE domain=?1
1815 AND namespace=?2
1816 AND key_type IS ?3
1817 AND state IS ?4
1818 AND km_uuid IS ?5) = 0;",
1819 params![
1820 domain.0 as u32,
1821 namespace,
1822 KeyType::Attestation,
1823 KeyLifeCycle::Live,
1824 km_uuid,
1825 ],
1826 )
1827 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001828 if result == 0 {
1829 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1830 } else if result > 1 {
1831 return Err(KsError::sys())
1832 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001833 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001834 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001835 })
1836 .context("In assign_attestation_key: ")
1837 }
1838
1839 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1840 /// provisioning server, or the maximum number available if there are not num_keys number of
1841 /// entries in the table.
1842 pub fn fetch_unsigned_attestation_keys(
1843 &mut self,
1844 num_keys: i32,
1845 km_uuid: &Uuid,
1846 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001847 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1848
Max Bires2b2e6562020-09-22 11:22:36 -07001849 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1850 let mut stmt = tx
1851 .prepare(
1852 "SELECT data
1853 FROM persistent.keymetadata
1854 WHERE tag = ? AND keyentryid IN
1855 (SELECT id
1856 FROM persistent.keyentry
1857 WHERE
1858 alias IS NULL AND
1859 domain IS NULL AND
1860 namespace IS NULL AND
1861 key_type = ? AND
1862 km_uuid = ?
1863 LIMIT ?);",
1864 )
1865 .context("Failed to prepare statement")?;
1866 let rows = stmt
1867 .query_map(
1868 params![
1869 KeyMetaData::AttestationMacedPublicKey,
1870 KeyType::Attestation,
1871 km_uuid,
1872 num_keys
1873 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001874 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001875 )?
1876 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1877 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001878 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001879 })
1880 .context("In fetch_unsigned_attestation_keys")
1881 }
1882
1883 /// Removes any keys that have expired as of the current time. Returns the number of keys
1884 /// marked unreferenced that are bound to be garbage collected.
1885 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001886 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1887
Max Bires2b2e6562020-09-22 11:22:36 -07001888 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1889 let mut stmt = tx
1890 .prepare(
1891 "SELECT keyentryid, data
1892 FROM persistent.keymetadata
1893 WHERE tag = ? AND keyentryid IN
1894 (SELECT id
1895 FROM persistent.keyentry
1896 WHERE key_type = ?);",
1897 )
1898 .context("Failed to prepare query")?;
1899 let key_ids_to_check = stmt
1900 .query_map(
1901 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1902 |row| Ok((row.get(0)?, row.get(1)?)),
1903 )?
1904 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1905 .context("Failed to get date metadata")?;
1906 let curr_time = DateTime::from_millis_epoch(
1907 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1908 );
1909 let mut num_deleted = 0;
1910 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1911 if Self::mark_unreferenced(&tx, id)? {
1912 num_deleted += 1;
1913 }
1914 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001915 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001916 })
1917 .context("In delete_expired_attestation_keys: ")
1918 }
1919
Max Bires60d7ed12021-03-05 15:59:22 -08001920 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1921 /// they are in. This is useful primarily as a testing mechanism.
1922 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001923 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1924
Max Bires60d7ed12021-03-05 15:59:22 -08001925 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1926 let mut stmt = tx
1927 .prepare(
1928 "SELECT id FROM persistent.keyentry
1929 WHERE key_type IS ?;",
1930 )
1931 .context("Failed to prepare statement")?;
1932 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001933 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001934 .collect::<rusqlite::Result<Vec<i64>>>()
1935 .context("Failed to execute statement")?;
1936 let num_deleted = keys_to_delete
1937 .iter()
1938 .map(|id| Self::mark_unreferenced(&tx, *id))
1939 .collect::<Result<Vec<bool>>>()
1940 .context("Failed to execute mark_unreferenced on a keyid")?
1941 .into_iter()
1942 .filter(|result| *result)
1943 .count() as i64;
1944 Ok(num_deleted).do_gc(num_deleted != 0)
1945 })
1946 .context("In delete_all_attestation_keys: ")
1947 }
1948
Max Bires2b2e6562020-09-22 11:22:36 -07001949 /// Counts the number of keys that will expire by the provided epoch date and the number of
1950 /// keys not currently assigned to a domain.
1951 pub fn get_attestation_pool_status(
1952 &mut self,
1953 date: i64,
1954 km_uuid: &Uuid,
1955 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001956 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1957
Max Bires2b2e6562020-09-22 11:22:36 -07001958 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1959 let mut stmt = tx.prepare(
1960 "SELECT data
1961 FROM persistent.keymetadata
1962 WHERE tag = ? AND keyentryid IN
1963 (SELECT id
1964 FROM persistent.keyentry
1965 WHERE alias IS NOT NULL
1966 AND key_type = ?
1967 AND km_uuid = ?
1968 AND state = ?);",
1969 )?;
1970 let times = stmt
1971 .query_map(
1972 params![
1973 KeyMetaData::AttestationExpirationDate,
1974 KeyType::Attestation,
1975 km_uuid,
1976 KeyLifeCycle::Live
1977 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001978 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001979 )?
1980 .collect::<rusqlite::Result<Vec<DateTime>>>()
1981 .context("Failed to execute metadata statement")?;
1982 let expiring =
1983 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1984 as i32;
1985 stmt = tx.prepare(
1986 "SELECT alias, domain
1987 FROM persistent.keyentry
1988 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1989 )?;
1990 let rows = stmt
1991 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1992 Ok((row.get(0)?, row.get(1)?))
1993 })?
1994 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1995 .context("Failed to execute keyentry statement")?;
1996 let mut unassigned = 0i32;
1997 let mut attested = 0i32;
1998 let total = rows.len() as i32;
1999 for (alias, domain) in rows {
2000 match (alias, domain) {
2001 (Some(_alias), None) => {
2002 attested += 1;
2003 unassigned += 1;
2004 }
2005 (Some(_alias), Some(_domain)) => {
2006 attested += 1;
2007 }
2008 _ => {}
2009 }
2010 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002011 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002012 })
2013 .context("In get_attestation_pool_status: ")
2014 }
2015
2016 /// Fetches the private key and corresponding certificate chain assigned to a
2017 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2018 /// not assigned, or one CertificateChain.
2019 pub fn retrieve_attestation_key_and_cert_chain(
2020 &mut self,
2021 domain: Domain,
2022 namespace: i64,
2023 km_uuid: &Uuid,
2024 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002025 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2026
Max Bires2b2e6562020-09-22 11:22:36 -07002027 match domain {
2028 Domain::APP | Domain::SELINUX => {}
2029 _ => {
2030 return Err(KsError::sys())
2031 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2032 }
2033 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002034 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2035 let mut stmt = tx.prepare(
2036 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002037 FROM persistent.blobentry
2038 WHERE keyentryid IN
2039 (SELECT id
2040 FROM persistent.keyentry
2041 WHERE key_type = ?
2042 AND domain = ?
2043 AND namespace = ?
2044 AND state = ?
2045 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002046 )?;
2047 let rows = stmt
2048 .query_map(
2049 params![
2050 KeyType::Attestation,
2051 domain.0 as u32,
2052 namespace,
2053 KeyLifeCycle::Live,
2054 km_uuid
2055 ],
2056 |row| Ok((row.get(0)?, row.get(1)?)),
2057 )?
2058 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002059 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002060 if rows.is_empty() {
2061 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002062 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002063 return Err(KsError::sys()).context(format!(
2064 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002065 "Expected to get a single attestation",
2066 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2067 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002068 rows.len()
2069 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002070 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002071 let mut km_blob: Vec<u8> = Vec::new();
2072 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002073 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002074 for row in rows {
2075 let sub_type: SubComponentType = row.0;
2076 match sub_type {
2077 SubComponentType::KEY_BLOB => {
2078 km_blob = row.1;
2079 }
2080 SubComponentType::CERT_CHAIN => {
2081 cert_chain_blob = row.1;
2082 }
Max Biresb2e1d032021-02-08 21:35:05 -08002083 SubComponentType::CERT => {
2084 batch_cert_blob = row.1;
2085 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002086 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2087 }
2088 }
2089 Ok(Some(CertificateChain {
2090 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002091 batch_cert: batch_cert_blob,
2092 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002093 }))
2094 .no_gc()
2095 })
Max Biresb2e1d032021-02-08 21:35:05 -08002096 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002097 }
2098
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002099 /// Updates the alias column of the given key id `newid` with the given alias,
2100 /// and atomically, removes the alias, domain, and namespace from another row
2101 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002102 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2103 /// collector.
2104 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002105 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002106 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002107 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002108 domain: &Domain,
2109 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002110 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002111 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002112 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002113 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002114 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002115 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002116 domain
2117 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002118 }
2119 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002120 let updated = tx
2121 .execute(
2122 "UPDATE persistent.keyentry
2123 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002124 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002125 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2126 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002127 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002128 let result = tx
2129 .execute(
2130 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002131 SET alias = ?, state = ?
2132 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2133 params![
2134 alias,
2135 KeyLifeCycle::Live,
2136 newid.0,
2137 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002138 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002139 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002140 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002141 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002142 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002143 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002144 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002145 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002146 result
2147 ));
2148 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002149 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002150 }
2151
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002152 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2153 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2154 pub fn migrate_key_namespace(
2155 &mut self,
2156 key_id_guard: KeyIdGuard,
2157 destination: &KeyDescriptor,
2158 caller_uid: u32,
2159 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2160 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002161 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2162
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002163 let destination = match destination.domain {
2164 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2165 Domain::SELINUX => (*destination).clone(),
2166 domain => {
2167 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2168 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2169 }
2170 };
2171
2172 // Security critical: Must return immediately on failure. Do not remove the '?';
2173 check_permission(&destination)
2174 .context("In migrate_key_namespace: Trying to check permission.")?;
2175
2176 let alias = destination
2177 .alias
2178 .as_ref()
2179 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2180 .context("In migrate_key_namespace: Alias must be specified.")?;
2181
2182 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2183 // Query the destination location. If there is a key, the migration request fails.
2184 if tx
2185 .query_row(
2186 "SELECT id FROM persistent.keyentry
2187 WHERE alias = ? AND domain = ? AND namespace = ?;",
2188 params![alias, destination.domain.0, destination.nspace],
2189 |_| Ok(()),
2190 )
2191 .optional()
2192 .context("Failed to query destination.")?
2193 .is_some()
2194 {
2195 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2196 .context("Target already exists.");
2197 }
2198
2199 let updated = tx
2200 .execute(
2201 "UPDATE persistent.keyentry
2202 SET alias = ?, domain = ?, namespace = ?
2203 WHERE id = ?;",
2204 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2205 )
2206 .context("Failed to update key entry.")?;
2207
2208 if updated != 1 {
2209 return Err(KsError::sys())
2210 .context(format!("Update succeeded, but {} rows were updated.", updated));
2211 }
2212 Ok(()).no_gc()
2213 })
2214 .context("In migrate_key_namespace:")
2215 }
2216
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002217 /// Store a new key in a single transaction.
2218 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2219 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002220 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2221 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002222 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002223 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002224 key: &KeyDescriptor,
2225 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002226 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002227 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002228 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002229 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002230 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002231 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2232
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002233 let (alias, domain, namespace) = match key {
2234 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2235 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2236 (alias, key.domain, nspace)
2237 }
2238 _ => {
2239 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2240 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2241 }
2242 };
2243 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002244 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002245 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002246 let (blob, blob_metadata) = *blob_info;
2247 Self::set_blob_internal(
2248 tx,
2249 key_id.id(),
2250 SubComponentType::KEY_BLOB,
2251 Some(blob),
2252 Some(&blob_metadata),
2253 )
2254 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002255 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002256 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002257 .context("Trying to insert the certificate.")?;
2258 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002259 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002260 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002261 tx,
2262 key_id.id(),
2263 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002264 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002265 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002266 )
2267 .context("Trying to insert the certificate chain.")?;
2268 }
2269 Self::insert_keyparameter_internal(tx, &key_id, params)
2270 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002271 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002272 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002274 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002275 })
2276 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002277 }
2278
Janis Danisevskis377d1002021-01-27 19:07:48 -08002279 /// Store a new certificate
2280 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2281 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002282 pub fn store_new_certificate(
2283 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002284 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002285 cert: &[u8],
2286 km_uuid: &Uuid,
2287 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002288 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2289
Janis Danisevskis377d1002021-01-27 19:07:48 -08002290 let (alias, domain, namespace) = match key {
2291 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2292 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2293 (alias, key.domain, nspace)
2294 }
2295 _ => {
2296 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2297 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2298 )
2299 }
2300 };
2301 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002302 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002303 .context("Trying to create new key entry.")?;
2304
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002305 Self::set_blob_internal(
2306 tx,
2307 key_id.id(),
2308 SubComponentType::CERT_CHAIN,
2309 Some(cert),
2310 None,
2311 )
2312 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002313
2314 let mut metadata = KeyMetaData::new();
2315 metadata.add(KeyMetaEntry::CreationDate(
2316 DateTime::now().context("Trying to make creation time.")?,
2317 ));
2318
2319 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2320
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002321 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002322 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002323 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002324 })
2325 .context("In store_new_certificate.")
2326 }
2327
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002328 // Helper function loading the key_id given the key descriptor
2329 // tuple comprising domain, namespace, and alias.
2330 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002331 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002332 let alias = key
2333 .alias
2334 .as_ref()
2335 .map_or_else(|| Err(KsError::sys()), Ok)
2336 .context("In load_key_entry_id: Alias must be specified.")?;
2337 let mut stmt = tx
2338 .prepare(
2339 "SELECT id FROM persistent.keyentry
2340 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002341 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002342 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002343 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002344 AND alias = ?
2345 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002346 )
2347 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2348 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002349 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002350 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002351 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002352 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002353 .get(0)
2354 .context("Failed to unpack id.")
2355 })
2356 .context("In load_key_entry_id.")
2357 }
2358
2359 /// This helper function completes the access tuple of a key, which is required
2360 /// to perform access control. The strategy depends on the `domain` field in the
2361 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002362 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002363 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002364 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002365 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002366 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002367 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002368 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002369 /// `namespace`.
2370 /// In each case the information returned is sufficient to perform the access
2371 /// check and the key id can be used to load further key artifacts.
2372 fn load_access_tuple(
2373 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002374 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002375 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002376 caller_uid: u32,
2377 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2378 match key.domain {
2379 // Domain App or SELinux. In this case we load the key_id from
2380 // the keyentry database for further loading of key components.
2381 // We already have the full access tuple to perform access control.
2382 // The only distinction is that we use the caller_uid instead
2383 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002384 // Domain::APP.
2385 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002386 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002387 if access_key.domain == Domain::APP {
2388 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002389 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002390 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002391 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002392
2393 Ok((key_id, access_key, None))
2394 }
2395
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002396 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002397 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002398 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002399 let mut stmt = tx
2400 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002401 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002402 WHERE grantee = ? AND id = ? AND
2403 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002404 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002405 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002406 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002407 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408 .context("Domain:Grant: query failed.")?;
2409 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002410 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002411 let r =
2412 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002413 Ok((
2414 r.get(0).context("Failed to unpack key_id.")?,
2415 r.get(1).context("Failed to unpack access_vector.")?,
2416 ))
2417 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002418 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002419 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002420 }
2421
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002422 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002423 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002424 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002425 let (domain, namespace): (Domain, i64) = {
2426 let mut stmt = tx
2427 .prepare(
2428 "SELECT domain, namespace FROM persistent.keyentry
2429 WHERE
2430 id = ?
2431 AND state = ?;",
2432 )
2433 .context("Domain::KEY_ID: prepare statement failed")?;
2434 let mut rows = stmt
2435 .query(params![key.nspace, KeyLifeCycle::Live])
2436 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002437 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002438 let r =
2439 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002440 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002441 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002442 r.get(1).context("Failed to unpack namespace.")?,
2443 ))
2444 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002445 .context("Domain::KEY_ID.")?
2446 };
2447
2448 // We may use a key by id after loading it by grant.
2449 // In this case we have to check if the caller has a grant for this particular
2450 // key. We can skip this if we already know that the caller is the owner.
2451 // But we cannot know this if domain is anything but App. E.g. in the case
2452 // of Domain::SELINUX we have to speculatively check for grants because we have to
2453 // consult the SEPolicy before we know if the caller is the owner.
2454 let access_vector: Option<KeyPermSet> =
2455 if domain != Domain::APP || namespace != caller_uid as i64 {
2456 let access_vector: Option<i32> = tx
2457 .query_row(
2458 "SELECT access_vector FROM persistent.grant
2459 WHERE grantee = ? AND keyentryid = ?;",
2460 params![caller_uid as i64, key.nspace],
2461 |row| row.get(0),
2462 )
2463 .optional()
2464 .context("Domain::KEY_ID: query grant failed.")?;
2465 access_vector.map(|p| p.into())
2466 } else {
2467 None
2468 };
2469
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002470 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002471 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002472 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002473 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002474
Janis Danisevskis45760022021-01-19 16:34:10 -08002475 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002476 }
2477 _ => Err(anyhow!(KsError::sys())),
2478 }
2479 }
2480
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002481 fn load_blob_components(
2482 key_id: i64,
2483 load_bits: KeyEntryLoadBits,
2484 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002485 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002486 let mut stmt = tx
2487 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002488 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002489 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2490 )
2491 .context("In load_blob_components: prepare statement failed.")?;
2492
2493 let mut rows =
2494 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2495
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002496 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002497 let mut cert_blob: Option<Vec<u8>> = None;
2498 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002499 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002500 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002501 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002502 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002503 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002504 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2505 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002506 key_blob = Some((
2507 row.get(0).context("Failed to extract key blob id.")?,
2508 row.get(2).context("Failed to extract key blob.")?,
2509 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002510 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002511 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002512 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002513 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002514 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002515 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002516 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002517 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002518 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002519 (SubComponentType::CERT, _, _)
2520 | (SubComponentType::CERT_CHAIN, _, _)
2521 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002522 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2523 }
2524 Ok(())
2525 })
2526 .context("In load_blob_components.")?;
2527
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002528 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2529 Ok(Some((
2530 blob,
2531 BlobMetaData::load_from_db(blob_id, tx)
2532 .context("In load_blob_components: Trying to load blob_metadata.")?,
2533 )))
2534 })?;
2535
2536 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002537 }
2538
2539 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2540 let mut stmt = tx
2541 .prepare(
2542 "SELECT tag, data, security_level from persistent.keyparameter
2543 WHERE keyentryid = ?;",
2544 )
2545 .context("In load_key_parameters: prepare statement failed.")?;
2546
2547 let mut parameters: Vec<KeyParameter> = Vec::new();
2548
2549 let mut rows =
2550 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002551 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002552 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2553 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002554 parameters.push(
2555 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2556 .context("Failed to read KeyParameter.")?,
2557 );
2558 Ok(())
2559 })
2560 .context("In load_key_parameters.")?;
2561
2562 Ok(parameters)
2563 }
2564
Qi Wub9433b52020-12-01 14:52:46 +08002565 /// Decrements the usage count of a limited use key. This function first checks whether the
2566 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2567 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2568 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002569 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002570 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2571
Qi Wub9433b52020-12-01 14:52:46 +08002572 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2573 let limit: Option<i32> = tx
2574 .query_row(
2575 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2576 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2577 |row| row.get(0),
2578 )
2579 .optional()
2580 .context("Trying to load usage count")?;
2581
2582 let limit = limit
2583 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2584 .context("The Key no longer exists. Key is exhausted.")?;
2585
2586 tx.execute(
2587 "UPDATE persistent.keyparameter
2588 SET data = data - 1
2589 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2590 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2591 )
2592 .context("Failed to update key usage count.")?;
2593
2594 match limit {
2595 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002596 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002597 .context("Trying to mark limited use key for deletion."),
2598 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002599 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002600 }
2601 })
2602 .context("In check_and_update_key_usage_count.")
2603 }
2604
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002605 /// Load a key entry by the given key descriptor.
2606 /// It uses the `check_permission` callback to verify if the access is allowed
2607 /// given the key access tuple read from the database using `load_access_tuple`.
2608 /// With `load_bits` the caller may specify which blobs shall be loaded from
2609 /// the blob database.
2610 pub fn load_key_entry(
2611 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002612 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002613 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002614 load_bits: KeyEntryLoadBits,
2615 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002616 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2617 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002618 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2619
Janis Danisevskis66784c42021-01-27 08:40:25 -08002620 loop {
2621 match self.load_key_entry_internal(
2622 key,
2623 key_type,
2624 load_bits,
2625 caller_uid,
2626 &check_permission,
2627 ) {
2628 Ok(result) => break Ok(result),
2629 Err(e) => {
2630 if Self::is_locked_error(&e) {
2631 std::thread::sleep(std::time::Duration::from_micros(500));
2632 continue;
2633 } else {
2634 return Err(e).context("In load_key_entry.");
2635 }
2636 }
2637 }
2638 }
2639 }
2640
2641 fn load_key_entry_internal(
2642 &mut self,
2643 key: &KeyDescriptor,
2644 key_type: KeyType,
2645 load_bits: KeyEntryLoadBits,
2646 caller_uid: u32,
2647 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002648 ) -> Result<(KeyIdGuard, KeyEntry)> {
2649 // KEY ID LOCK 1/2
2650 // If we got a key descriptor with a key id we can get the lock right away.
2651 // Otherwise we have to defer it until we know the key id.
2652 let key_id_guard = match key.domain {
2653 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2654 _ => None,
2655 };
2656
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002657 let tx = self
2658 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002659 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002660 .context("In load_key_entry: Failed to initialize transaction.")?;
2661
2662 // Load the key_id and complete the access control tuple.
2663 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002664 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2665 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002666
2667 // Perform access control. It is vital that we return here if the permission is denied.
2668 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002669 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002670
Janis Danisevskisaec14592020-11-12 09:41:49 -08002671 // KEY ID LOCK 2/2
2672 // If we did not get a key id lock by now, it was because we got a key descriptor
2673 // without a key id. At this point we got the key id, so we can try and get a lock.
2674 // However, we cannot block here, because we are in the middle of the transaction.
2675 // So first we try to get the lock non blocking. If that fails, we roll back the
2676 // transaction and block until we get the lock. After we successfully got the lock,
2677 // we start a new transaction and load the access tuple again.
2678 //
2679 // We don't need to perform access control again, because we already established
2680 // that the caller had access to the given key. But we need to make sure that the
2681 // key id still exists. So we have to load the key entry by key id this time.
2682 let (key_id_guard, tx) = match key_id_guard {
2683 None => match KEY_ID_LOCK.try_get(key_id) {
2684 None => {
2685 // Roll back the transaction.
2686 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002687
Janis Danisevskisaec14592020-11-12 09:41:49 -08002688 // Block until we have a key id lock.
2689 let key_id_guard = KEY_ID_LOCK.get(key_id);
2690
2691 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002692 let tx = self
2693 .conn
2694 .unchecked_transaction()
2695 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002696
2697 Self::load_access_tuple(
2698 &tx,
2699 // This time we have to load the key by the retrieved key id, because the
2700 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002701 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002702 domain: Domain::KEY_ID,
2703 nspace: key_id,
2704 ..Default::default()
2705 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002706 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002707 caller_uid,
2708 )
2709 .context("In load_key_entry. (deferred key lock)")?;
2710 (key_id_guard, tx)
2711 }
2712 Some(l) => (l, tx),
2713 },
2714 Some(key_id_guard) => (key_id_guard, tx),
2715 };
2716
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002717 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2718 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002719
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002720 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2721
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002722 Ok((key_id_guard, key_entry))
2723 }
2724
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002725 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002726 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002727 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2728 .context("Trying to delete keyentry.")?;
2729 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2730 .context("Trying to delete keymetadata.")?;
2731 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2732 .context("Trying to delete keyparameters.")?;
2733 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2734 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002735 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002736 }
2737
2738 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002739 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002740 pub fn unbind_key(
2741 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002742 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002743 key_type: KeyType,
2744 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002745 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002746 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002747 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2748
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002749 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2750 let (key_id, access_key_descriptor, access_vector) =
2751 Self::load_access_tuple(tx, key, key_type, caller_uid)
2752 .context("Trying to get access tuple.")?;
2753
2754 // Perform access control. It is vital that we return here if the permission is denied.
2755 // So do not touch that '?' at the end.
2756 check_permission(&access_key_descriptor, access_vector)
2757 .context("While checking permission.")?;
2758
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002759 Self::mark_unreferenced(tx, key_id)
2760 .map(|need_gc| (need_gc, ()))
2761 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002762 })
2763 .context("In unbind_key.")
2764 }
2765
Max Bires8e93d2b2021-01-14 13:17:59 -08002766 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2767 tx.query_row(
2768 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2769 params![key_id],
2770 |row| row.get(0),
2771 )
2772 .context("In get_key_km_uuid.")
2773 }
2774
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002775 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2776 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2777 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002778 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2779
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002780 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2781 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2782 .context("In unbind_keys_for_namespace.");
2783 }
2784 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2785 tx.execute(
2786 "DELETE FROM persistent.keymetadata
2787 WHERE keyentryid IN (
2788 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002789 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002790 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002791 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002792 )
2793 .context("Trying to delete keymetadata.")?;
2794 tx.execute(
2795 "DELETE FROM persistent.keyparameter
2796 WHERE keyentryid IN (
2797 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002798 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002799 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002800 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002801 )
2802 .context("Trying to delete keyparameters.")?;
2803 tx.execute(
2804 "DELETE FROM persistent.grant
2805 WHERE keyentryid IN (
2806 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002807 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002808 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002809 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002810 )
2811 .context("Trying to delete grants.")?;
2812 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002813 "DELETE FROM persistent.keyentry
2814 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2815 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002816 )
2817 .context("Trying to delete keyentry.")?;
2818 Ok(()).need_gc()
2819 })
2820 .context("In unbind_keys_for_namespace")
2821 }
2822
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002823 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2824 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2825 {
2826 tx.execute(
2827 "DELETE FROM persistent.keymetadata
2828 WHERE keyentryid IN (
2829 SELECT id FROM persistent.keyentry
2830 WHERE state = ?
2831 );",
2832 params![KeyLifeCycle::Unreferenced],
2833 )
2834 .context("Trying to delete keymetadata.")?;
2835 tx.execute(
2836 "DELETE FROM persistent.keyparameter
2837 WHERE keyentryid IN (
2838 SELECT id FROM persistent.keyentry
2839 WHERE state = ?
2840 );",
2841 params![KeyLifeCycle::Unreferenced],
2842 )
2843 .context("Trying to delete keyparameters.")?;
2844 tx.execute(
2845 "DELETE FROM persistent.grant
2846 WHERE keyentryid IN (
2847 SELECT id FROM persistent.keyentry
2848 WHERE state = ?
2849 );",
2850 params![KeyLifeCycle::Unreferenced],
2851 )
2852 .context("Trying to delete grants.")?;
2853 tx.execute(
2854 "DELETE FROM persistent.keyentry
2855 WHERE state = ?;",
2856 params![KeyLifeCycle::Unreferenced],
2857 )
2858 .context("Trying to delete keyentry.")?;
2859 Result::<()>::Ok(())
2860 }
2861 .context("In cleanup_unreferenced")
2862 }
2863
Hasini Gunasingheda895552021-01-27 19:34:37 +00002864 /// Delete the keys created on behalf of the user, denoted by the user id.
2865 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2866 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2867 /// The caller of this function should notify the gc if the returned value is true.
2868 pub fn unbind_keys_for_user(
2869 &mut self,
2870 user_id: u32,
2871 keep_non_super_encrypted_keys: bool,
2872 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002873 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2874
Hasini Gunasingheda895552021-01-27 19:34:37 +00002875 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2876 let mut stmt = tx
2877 .prepare(&format!(
2878 "SELECT id from persistent.keyentry
2879 WHERE (
2880 key_type = ?
2881 AND domain = ?
2882 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2883 AND state = ?
2884 ) OR (
2885 key_type = ?
2886 AND namespace = ?
2887 AND alias = ?
2888 AND state = ?
2889 );",
2890 aid_user_offset = AID_USER_OFFSET
2891 ))
2892 .context(concat!(
2893 "In unbind_keys_for_user. ",
2894 "Failed to prepare the query to find the keys created by apps."
2895 ))?;
2896
2897 let mut rows = stmt
2898 .query(params![
2899 // WHERE client key:
2900 KeyType::Client,
2901 Domain::APP.0 as u32,
2902 user_id,
2903 KeyLifeCycle::Live,
2904 // OR super key:
2905 KeyType::Super,
2906 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002907 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002908 KeyLifeCycle::Live
2909 ])
2910 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2911
2912 let mut key_ids: Vec<i64> = Vec::new();
2913 db_utils::with_rows_extract_all(&mut rows, |row| {
2914 key_ids
2915 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2916 Ok(())
2917 })
2918 .context("In unbind_keys_for_user.")?;
2919
2920 let mut notify_gc = false;
2921 for key_id in key_ids {
2922 if keep_non_super_encrypted_keys {
2923 // Load metadata and filter out non-super-encrypted keys.
2924 if let (_, Some((_, blob_metadata)), _, _) =
2925 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2926 .context("In unbind_keys_for_user: Trying to load blob info.")?
2927 {
2928 if blob_metadata.encrypted_by().is_none() {
2929 continue;
2930 }
2931 }
2932 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002933 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002934 .context("In unbind_keys_for_user.")?
2935 || notify_gc;
2936 }
2937 Ok(()).do_gc(notify_gc)
2938 })
2939 .context("In unbind_keys_for_user.")
2940 }
2941
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002942 fn load_key_components(
2943 tx: &Transaction,
2944 load_bits: KeyEntryLoadBits,
2945 key_id: i64,
2946 ) -> Result<KeyEntry> {
2947 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2948
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002949 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002950 Self::load_blob_components(key_id, load_bits, &tx)
2951 .context("In load_key_components.")?;
2952
Max Bires8e93d2b2021-01-14 13:17:59 -08002953 let parameters = Self::load_key_parameters(key_id, &tx)
2954 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002955
Max Bires8e93d2b2021-01-14 13:17:59 -08002956 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2957 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002958
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002959 Ok(KeyEntry {
2960 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002961 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002962 cert: cert_blob,
2963 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002964 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002965 parameters,
2966 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002967 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002968 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002969 }
2970
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002971 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2972 /// The key descriptors will have the domain, nspace, and alias field set.
2973 /// Domain must be APP or SELINUX, the caller must make sure of that.
2974 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002975 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2976
Janis Danisevskis66784c42021-01-27 08:40:25 -08002977 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2978 let mut stmt = tx
2979 .prepare(
2980 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002981 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002982 )
2983 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002984
Janis Danisevskis66784c42021-01-27 08:40:25 -08002985 let mut rows = stmt
2986 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2987 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002988
Janis Danisevskis66784c42021-01-27 08:40:25 -08002989 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2990 db_utils::with_rows_extract_all(&mut rows, |row| {
2991 descriptors.push(KeyDescriptor {
2992 domain,
2993 nspace: namespace,
2994 alias: Some(row.get(0).context("Trying to extract alias.")?),
2995 blob: None,
2996 });
2997 Ok(())
2998 })
2999 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003000 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003001 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003002 }
3003
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003004 /// Adds a grant to the grant table.
3005 /// Like `load_key_entry` this function loads the access tuple before
3006 /// it uses the callback for a permission check. Upon success,
3007 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3008 /// grant table. The new row will have a randomized id, which is used as
3009 /// grant id in the namespace field of the resulting KeyDescriptor.
3010 pub fn grant(
3011 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003012 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003013 caller_uid: u32,
3014 grantee_uid: u32,
3015 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003016 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003017 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003018 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3019
Janis Danisevskis66784c42021-01-27 08:40:25 -08003020 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3021 // Load the key_id and complete the access control tuple.
3022 // We ignore the access vector here because grants cannot be granted.
3023 // The access vector returned here expresses the permissions the
3024 // grantee has if key.domain == Domain::GRANT. But this vector
3025 // cannot include the grant permission by design, so there is no way the
3026 // subsequent permission check can pass.
3027 // We could check key.domain == Domain::GRANT and fail early.
3028 // But even if we load the access tuple by grant here, the permission
3029 // check denies the attempt to create a grant by grant descriptor.
3030 let (key_id, access_key_descriptor, _) =
3031 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3032 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003033
Janis Danisevskis66784c42021-01-27 08:40:25 -08003034 // Perform access control. It is vital that we return here if the permission
3035 // was denied. So do not touch that '?' at the end of the line.
3036 // This permission check checks if the caller has the grant permission
3037 // for the given key and in addition to all of the permissions
3038 // expressed in `access_vector`.
3039 check_permission(&access_key_descriptor, &access_vector)
3040 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003041
Janis Danisevskis66784c42021-01-27 08:40:25 -08003042 let grant_id = if let Some(grant_id) = tx
3043 .query_row(
3044 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003045 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003046 params![key_id, grantee_uid],
3047 |row| row.get(0),
3048 )
3049 .optional()
3050 .context("In grant: Failed get optional existing grant id.")?
3051 {
3052 tx.execute(
3053 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003054 SET access_vector = ?
3055 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003056 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003057 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003058 .context("In grant: Failed to update existing grant.")?;
3059 grant_id
3060 } else {
3061 Self::insert_with_retry(|id| {
3062 tx.execute(
3063 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3064 VALUES (?, ?, ?, ?);",
3065 params![id, grantee_uid, key_id, i32::from(access_vector)],
3066 )
3067 })
3068 .context("In grant")?
3069 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003070
Janis Danisevskis66784c42021-01-27 08:40:25 -08003071 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003072 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003073 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003074 }
3075
3076 /// This function checks permissions like `grant` and `load_key_entry`
3077 /// before removing a grant from the grant table.
3078 pub fn ungrant(
3079 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003080 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003081 caller_uid: u32,
3082 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003084 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003085 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3086
Janis Danisevskis66784c42021-01-27 08:40:25 -08003087 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3088 // Load the key_id and complete the access control tuple.
3089 // We ignore the access vector here because grants cannot be granted.
3090 let (key_id, access_key_descriptor, _) =
3091 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3092 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003093
Janis Danisevskis66784c42021-01-27 08:40:25 -08003094 // Perform access control. We must return here if the permission
3095 // was denied. So do not touch the '?' at the end of this line.
3096 check_permission(&access_key_descriptor)
3097 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003098
Janis Danisevskis66784c42021-01-27 08:40:25 -08003099 tx.execute(
3100 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003102 params![key_id, grantee_uid],
3103 )
3104 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003105
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003106 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003107 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003108 }
3109
Joel Galenson845f74b2020-09-09 14:11:55 -07003110 // Generates a random id and passes it to the given function, which will
3111 // try to insert it into a database. If that insertion fails, retry;
3112 // otherwise return the id.
3113 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3114 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003115 let newid: i64 = match random() {
3116 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3117 i => i,
3118 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003119 match inserter(newid) {
3120 // If the id already existed, try again.
3121 Err(rusqlite::Error::SqliteFailure(
3122 libsqlite3_sys::Error {
3123 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3124 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3125 },
3126 _,
3127 )) => (),
3128 Err(e) => {
3129 return Err(e).context("In insert_with_retry: failed to insert into database.")
3130 }
3131 _ => return Ok(newid),
3132 }
3133 }
3134 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003135
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003136 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3137 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3138 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3139 auth_token.clone(),
3140 MonotonicRawTime::now(),
3141 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003142 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003143
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003144 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003145 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003146 where
3147 F: Fn(&AuthTokenEntry) -> bool,
3148 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003149 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003150 }
3151
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003152 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003153 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3154 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003155 }
3156
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003157 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003158 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3159 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003160 }
3161
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003162 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003163 fn get_last_off_body(&self) -> MonotonicRawTime {
3164 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003165 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003166}
3167
3168#[cfg(test)]
3169mod tests {
3170
3171 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003172 use crate::key_parameter::{
3173 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3174 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3175 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003176 use crate::key_perm_set;
3177 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003178 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003179 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003180 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3181 HardwareAuthToken::HardwareAuthToken,
3182 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003183 };
3184 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003185 Timestamp::Timestamp,
3186 };
Seth Moore472fcbb2021-05-12 10:07:51 -07003187 use rusqlite::DatabaseName::Attached;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003188 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003189 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003190 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003191 use std::collections::BTreeMap;
3192 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003193 use std::sync::atomic::{AtomicU8, Ordering};
3194 use std::sync::Arc;
3195 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003196 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003197 #[cfg(disabled)]
3198 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003199
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003200 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003201 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003202
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003203 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003204 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003205 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003206 })?;
3207 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003208 }
3209
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003210 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3211 where
3212 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3213 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003214 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003215
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003216 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003217 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003218
Janis Danisevskis3395f862021-05-06 10:54:17 -07003219 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003220 }
3221
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003222 fn rebind_alias(
3223 db: &mut KeystoreDB,
3224 newid: &KeyIdGuard,
3225 alias: &str,
3226 domain: Domain,
3227 namespace: i64,
3228 ) -> Result<bool> {
3229 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003230 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003231 })
3232 .context("In rebind_alias.")
3233 }
3234
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003235 #[test]
3236 fn datetime() -> Result<()> {
3237 let conn = Connection::open_in_memory()?;
3238 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3239 let now = SystemTime::now();
3240 let duration = Duration::from_secs(1000);
3241 let then = now.checked_sub(duration).unwrap();
3242 let soon = now.checked_add(duration).unwrap();
3243 conn.execute(
3244 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3245 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3246 )?;
3247 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3248 let mut rows = stmt.query(NO_PARAMS)?;
3249 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3250 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3251 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3252 assert!(rows.next()?.is_none());
3253 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3254 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3255 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3256 Ok(())
3257 }
3258
Joel Galenson0891bc12020-07-20 10:37:03 -07003259 // Ensure that we're using the "injected" random function, not the real one.
3260 #[test]
3261 fn test_mocked_random() {
3262 let rand1 = random();
3263 let rand2 = random();
3264 let rand3 = random();
3265 if rand1 == rand2 {
3266 assert_eq!(rand2 + 1, rand3);
3267 } else {
3268 assert_eq!(rand1 + 1, rand2);
3269 assert_eq!(rand2, rand3);
3270 }
3271 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003272
Joel Galenson26f4d012020-07-17 14:57:21 -07003273 // Test that we have the correct tables.
3274 #[test]
3275 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003276 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003277 let tables = db
3278 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003279 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003280 .query_map(params![], |row| row.get(0))?
3281 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003282 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003283 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003284 assert_eq!(tables[1], "blobmetadata");
3285 assert_eq!(tables[2], "grant");
3286 assert_eq!(tables[3], "keyentry");
3287 assert_eq!(tables[4], "keymetadata");
3288 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003289 Ok(())
3290 }
3291
3292 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003293 fn test_auth_token_table_invariant() -> Result<()> {
3294 let mut db = new_test_db()?;
3295 let auth_token1 = HardwareAuthToken {
3296 challenge: i64::MAX,
3297 userId: 200,
3298 authenticatorId: 200,
3299 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3300 timestamp: Timestamp { milliSeconds: 500 },
3301 mac: String::from("mac").into_bytes(),
3302 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003303 db.insert_auth_token(&auth_token1);
3304 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003305 assert_eq!(auth_tokens_returned.len(), 1);
3306
3307 // insert another auth token with the same values for the columns in the UNIQUE constraint
3308 // of the auth token table and different value for timestamp
3309 let auth_token2 = HardwareAuthToken {
3310 challenge: i64::MAX,
3311 userId: 200,
3312 authenticatorId: 200,
3313 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3314 timestamp: Timestamp { milliSeconds: 600 },
3315 mac: String::from("mac").into_bytes(),
3316 };
3317
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003318 db.insert_auth_token(&auth_token2);
3319 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003320 assert_eq!(auth_tokens_returned.len(), 1);
3321
3322 if let Some(auth_token) = auth_tokens_returned.pop() {
3323 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3324 }
3325
3326 // insert another auth token with the different values for the columns in the UNIQUE
3327 // constraint of the auth token table
3328 let auth_token3 = HardwareAuthToken {
3329 challenge: i64::MAX,
3330 userId: 201,
3331 authenticatorId: 200,
3332 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3333 timestamp: Timestamp { milliSeconds: 600 },
3334 mac: String::from("mac").into_bytes(),
3335 };
3336
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003337 db.insert_auth_token(&auth_token3);
3338 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003339 assert_eq!(auth_tokens_returned.len(), 2);
3340
3341 Ok(())
3342 }
3343
3344 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003345 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3346 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003347 }
3348
3349 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003350 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003351 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003352 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003353
Janis Danisevskis66784c42021-01-27 08:40:25 -08003354 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003355 let entries = get_keyentry(&db)?;
3356 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003357
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003358 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003359
3360 let entries_new = get_keyentry(&db)?;
3361 assert_eq!(entries, entries_new);
3362 Ok(())
3363 }
3364
3365 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003366 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003367 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3368 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003369 }
3370
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003371 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003372
Janis Danisevskis66784c42021-01-27 08:40:25 -08003373 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3374 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003375
3376 let entries = get_keyentry(&db)?;
3377 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003378 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3379 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003380
3381 // Test that we must pass in a valid Domain.
3382 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003383 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003384 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003385 );
3386 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003387 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003388 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003389 );
3390 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003391 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003392 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003393 );
3394
3395 Ok(())
3396 }
3397
Joel Galenson33c04ad2020-08-03 11:04:38 -07003398 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003399 fn test_add_unsigned_key() -> Result<()> {
3400 let mut db = new_test_db()?;
3401 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3402 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3403 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3404 db.create_attestation_key_entry(
3405 &public_key,
3406 &raw_public_key,
3407 &private_key,
3408 &KEYSTORE_UUID,
3409 )?;
3410 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3411 assert_eq!(keys.len(), 1);
3412 assert_eq!(keys[0], public_key);
3413 Ok(())
3414 }
3415
3416 #[test]
3417 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3418 let mut db = new_test_db()?;
3419 let expiration_date: i64 = 20;
3420 let namespace: i64 = 30;
3421 let base_byte: u8 = 1;
3422 let loaded_values =
3423 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3424 let chain =
3425 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3426 assert_eq!(true, chain.is_some());
3427 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003428 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003429 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3430 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003431 Ok(())
3432 }
3433
3434 #[test]
3435 fn test_get_attestation_pool_status() -> Result<()> {
3436 let mut db = new_test_db()?;
3437 let namespace: i64 = 30;
3438 load_attestation_key_pool(
3439 &mut db, 10, /* expiration */
3440 namespace, 0x01, /* base_byte */
3441 )?;
3442 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3443 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3444 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3445 assert_eq!(status.expiring, 0);
3446 assert_eq!(status.attested, 3);
3447 assert_eq!(status.unassigned, 0);
3448 assert_eq!(status.total, 3);
3449 assert_eq!(
3450 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3451 1
3452 );
3453 assert_eq!(
3454 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3455 2
3456 );
3457 assert_eq!(
3458 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3459 3
3460 );
3461 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3462 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3463 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3464 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003465 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003466 db.create_attestation_key_entry(
3467 &public_key,
3468 &raw_public_key,
3469 &private_key,
3470 &KEYSTORE_UUID,
3471 )?;
3472 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3473 assert_eq!(status.attested, 3);
3474 assert_eq!(status.unassigned, 0);
3475 assert_eq!(status.total, 4);
3476 db.store_signed_attestation_certificate_chain(
3477 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003478 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003479 &cert_chain,
3480 20,
3481 &KEYSTORE_UUID,
3482 )?;
3483 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3484 assert_eq!(status.attested, 4);
3485 assert_eq!(status.unassigned, 1);
3486 assert_eq!(status.total, 4);
3487 Ok(())
3488 }
3489
3490 #[test]
3491 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003492 let temp_dir =
3493 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3494 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003495 let expiration_date: i64 =
3496 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3497 let namespace: i64 = 30;
3498 let namespace_del1: i64 = 45;
3499 let namespace_del2: i64 = 60;
3500 let entry_values = load_attestation_key_pool(
3501 &mut db,
3502 expiration_date,
3503 namespace,
3504 0x01, /* base_byte */
3505 )?;
3506 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3507 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003508
3509 let blob_entry_row_count: u32 = db
3510 .conn
3511 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3512 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003513 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3514 // one key, one certificate chain, and one certificate.
3515 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003516
Max Bires2b2e6562020-09-22 11:22:36 -07003517 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3518
3519 let mut cert_chain =
3520 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003521 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003522 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003523 assert_eq!(entry_values.batch_cert, value.batch_cert);
3524 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003525 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003526
3527 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3528 Domain::APP,
3529 namespace_del1,
3530 &KEYSTORE_UUID,
3531 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003532 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003533 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3534 Domain::APP,
3535 namespace_del2,
3536 &KEYSTORE_UUID,
3537 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003538 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003539
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003540 // Give the garbage collector half a second to catch up.
3541 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003542
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003543 let blob_entry_row_count: u32 = db
3544 .conn
3545 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3546 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003547 // There shound be 3 blob entries left, because we deleted two of the attestation
3548 // key entries with three blobs each.
3549 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003550
Max Bires2b2e6562020-09-22 11:22:36 -07003551 Ok(())
3552 }
3553
3554 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003555 fn test_delete_all_attestation_keys() -> Result<()> {
3556 let mut db = new_test_db()?;
3557 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3558 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3559 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3560 let result = db.delete_all_attestation_keys()?;
3561
3562 // Give the garbage collector half a second to catch up.
3563 std::thread::sleep(Duration::from_millis(500));
3564
3565 // Attestation keys should be deleted, and the regular key should remain.
3566 assert_eq!(result, 2);
3567
3568 Ok(())
3569 }
3570
3571 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003572 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003573 fn extractor(
3574 ke: &KeyEntryRow,
3575 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3576 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003577 }
3578
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003579 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003580 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3581 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003582 let entries = get_keyentry(&db)?;
3583 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003584 assert_eq!(
3585 extractor(&entries[0]),
3586 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3587 );
3588 assert_eq!(
3589 extractor(&entries[1]),
3590 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3591 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003592
3593 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003594 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003595 let entries = get_keyentry(&db)?;
3596 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003597 assert_eq!(
3598 extractor(&entries[0]),
3599 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3600 );
3601 assert_eq!(
3602 extractor(&entries[1]),
3603 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3604 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003605
3606 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003607 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003608 let entries = get_keyentry(&db)?;
3609 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003610 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3611 assert_eq!(
3612 extractor(&entries[1]),
3613 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3614 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003615
3616 // Test that we must pass in a valid Domain.
3617 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003618 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003619 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003620 );
3621 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003622 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003623 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003624 );
3625 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003626 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003627 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003628 );
3629
3630 // Test that we correctly handle setting an alias for something that does not exist.
3631 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003632 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003633 "Expected to update a single entry but instead updated 0",
3634 );
3635 // Test that we correctly abort the transaction in this case.
3636 let entries = get_keyentry(&db)?;
3637 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003638 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3639 assert_eq!(
3640 extractor(&entries[1]),
3641 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3642 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003643
3644 Ok(())
3645 }
3646
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003647 #[test]
3648 fn test_grant_ungrant() -> Result<()> {
3649 const CALLER_UID: u32 = 15;
3650 const GRANTEE_UID: u32 = 12;
3651 const SELINUX_NAMESPACE: i64 = 7;
3652
3653 let mut db = new_test_db()?;
3654 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003655 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3656 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3657 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003658 )?;
3659 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003660 domain: super::Domain::APP,
3661 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003662 alias: Some("key".to_string()),
3663 blob: None,
3664 };
3665 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3666 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3667
3668 // Reset totally predictable random number generator in case we
3669 // are not the first test running on this thread.
3670 reset_random();
3671 let next_random = 0i64;
3672
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003673 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003674 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003675 assert_eq!(*a, PVEC1);
3676 assert_eq!(
3677 *k,
3678 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003679 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003680 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003681 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003682 alias: Some("key".to_string()),
3683 blob: None,
3684 }
3685 );
3686 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003687 })
3688 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003689
3690 assert_eq!(
3691 app_granted_key,
3692 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003693 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003694 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003695 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003696 alias: None,
3697 blob: None,
3698 }
3699 );
3700
3701 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003702 domain: super::Domain::SELINUX,
3703 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003704 alias: Some("yek".to_string()),
3705 blob: None,
3706 };
3707
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003708 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003709 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003710 assert_eq!(*a, PVEC1);
3711 assert_eq!(
3712 *k,
3713 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003714 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003715 // namespace must be the supplied SELinux
3716 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003717 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003718 alias: Some("yek".to_string()),
3719 blob: None,
3720 }
3721 );
3722 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003723 })
3724 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725
3726 assert_eq!(
3727 selinux_granted_key,
3728 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003729 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003730 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003731 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003732 alias: None,
3733 blob: None,
3734 }
3735 );
3736
3737 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003738 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003739 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003740 assert_eq!(*a, PVEC2);
3741 assert_eq!(
3742 *k,
3743 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003744 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003745 // namespace must be the supplied SELinux
3746 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003747 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003748 alias: Some("yek".to_string()),
3749 blob: None,
3750 }
3751 );
3752 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003753 })
3754 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755
3756 assert_eq!(
3757 selinux_granted_key,
3758 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003759 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003760 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003761 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003762 alias: None,
3763 blob: None,
3764 }
3765 );
3766
3767 {
3768 // Limiting scope of stmt, because it borrows db.
3769 let mut stmt = db
3770 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003771 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003772 let mut rows =
3773 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3774 Ok((
3775 row.get(0)?,
3776 row.get(1)?,
3777 row.get(2)?,
3778 KeyPermSet::from(row.get::<_, i32>(3)?),
3779 ))
3780 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003781
3782 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003783 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003784 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003785 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003786 assert!(rows.next().is_none());
3787 }
3788
3789 debug_dump_keyentry_table(&mut db)?;
3790 println!("app_key {:?}", app_key);
3791 println!("selinux_key {:?}", selinux_key);
3792
Janis Danisevskis66784c42021-01-27 08:40:25 -08003793 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3794 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003795
3796 Ok(())
3797 }
3798
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003799 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003800 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3801 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3802
3803 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003804 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003805 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003806 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003807 let mut blob_metadata = BlobMetaData::new();
3808 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3809 db.set_blob(
3810 &key_id,
3811 SubComponentType::KEY_BLOB,
3812 Some(TEST_KEY_BLOB),
3813 Some(&blob_metadata),
3814 )?;
3815 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3816 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003817 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003818
3819 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003820 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003821 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003822 )?;
3823 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003824 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3825 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003826 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003827 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003828 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003829 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003830 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003831 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003832 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003833
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003834 drop(rows);
3835 drop(stmt);
3836
3837 assert_eq!(
3838 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3839 BlobMetaData::load_from_db(id, tx).no_gc()
3840 })
3841 .expect("Should find blob metadata."),
3842 blob_metadata
3843 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003844 Ok(())
3845 }
3846
3847 static TEST_ALIAS: &str = "my super duper key";
3848
3849 #[test]
3850 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3851 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003852 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003853 .context("test_insert_and_load_full_keyentry_domain_app")?
3854 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003855 let (_key_guard, key_entry) = db
3856 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003857 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003858 domain: Domain::APP,
3859 nspace: 0,
3860 alias: Some(TEST_ALIAS.to_string()),
3861 blob: None,
3862 },
3863 KeyType::Client,
3864 KeyEntryLoadBits::BOTH,
3865 1,
3866 |_k, _av| Ok(()),
3867 )
3868 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003869 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003870
3871 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003872 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003873 domain: Domain::APP,
3874 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003875 alias: Some(TEST_ALIAS.to_string()),
3876 blob: None,
3877 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003878 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003879 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003880 |_, _| Ok(()),
3881 )
3882 .unwrap();
3883
3884 assert_eq!(
3885 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3886 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003887 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003888 domain: Domain::APP,
3889 nspace: 0,
3890 alias: Some(TEST_ALIAS.to_string()),
3891 blob: None,
3892 },
3893 KeyType::Client,
3894 KeyEntryLoadBits::NONE,
3895 1,
3896 |_k, _av| Ok(()),
3897 )
3898 .unwrap_err()
3899 .root_cause()
3900 .downcast_ref::<KsError>()
3901 );
3902
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003903 Ok(())
3904 }
3905
3906 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003907 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3908 let mut db = new_test_db()?;
3909
3910 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003911 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003912 domain: Domain::APP,
3913 nspace: 1,
3914 alias: Some(TEST_ALIAS.to_string()),
3915 blob: None,
3916 },
3917 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003918 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003919 )
3920 .expect("Trying to insert cert.");
3921
3922 let (_key_guard, mut key_entry) = db
3923 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003924 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003925 domain: Domain::APP,
3926 nspace: 1,
3927 alias: Some(TEST_ALIAS.to_string()),
3928 blob: None,
3929 },
3930 KeyType::Client,
3931 KeyEntryLoadBits::PUBLIC,
3932 1,
3933 |_k, _av| Ok(()),
3934 )
3935 .expect("Trying to read certificate entry.");
3936
3937 assert!(key_entry.pure_cert());
3938 assert!(key_entry.cert().is_none());
3939 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3940
3941 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003942 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003943 domain: Domain::APP,
3944 nspace: 1,
3945 alias: Some(TEST_ALIAS.to_string()),
3946 blob: None,
3947 },
3948 KeyType::Client,
3949 1,
3950 |_, _| Ok(()),
3951 )
3952 .unwrap();
3953
3954 assert_eq!(
3955 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3956 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003957 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003958 domain: Domain::APP,
3959 nspace: 1,
3960 alias: Some(TEST_ALIAS.to_string()),
3961 blob: None,
3962 },
3963 KeyType::Client,
3964 KeyEntryLoadBits::NONE,
3965 1,
3966 |_k, _av| Ok(()),
3967 )
3968 .unwrap_err()
3969 .root_cause()
3970 .downcast_ref::<KsError>()
3971 );
3972
3973 Ok(())
3974 }
3975
3976 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003977 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3978 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003979 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003980 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3981 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003982 let (_key_guard, key_entry) = db
3983 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003984 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003985 domain: Domain::SELINUX,
3986 nspace: 1,
3987 alias: Some(TEST_ALIAS.to_string()),
3988 blob: None,
3989 },
3990 KeyType::Client,
3991 KeyEntryLoadBits::BOTH,
3992 1,
3993 |_k, _av| Ok(()),
3994 )
3995 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003996 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003997
3998 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003999 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004000 domain: Domain::SELINUX,
4001 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004002 alias: Some(TEST_ALIAS.to_string()),
4003 blob: None,
4004 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004005 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004006 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004007 |_, _| Ok(()),
4008 )
4009 .unwrap();
4010
4011 assert_eq!(
4012 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4013 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004014 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004015 domain: Domain::SELINUX,
4016 nspace: 1,
4017 alias: Some(TEST_ALIAS.to_string()),
4018 blob: None,
4019 },
4020 KeyType::Client,
4021 KeyEntryLoadBits::NONE,
4022 1,
4023 |_k, _av| Ok(()),
4024 )
4025 .unwrap_err()
4026 .root_cause()
4027 .downcast_ref::<KsError>()
4028 );
4029
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004030 Ok(())
4031 }
4032
4033 #[test]
4034 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4035 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004036 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004037 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4038 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004039 let (_, key_entry) = db
4040 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004041 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004042 KeyType::Client,
4043 KeyEntryLoadBits::BOTH,
4044 1,
4045 |_k, _av| Ok(()),
4046 )
4047 .unwrap();
4048
Qi Wub9433b52020-12-01 14:52:46 +08004049 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004050
4051 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004052 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004053 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004054 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004055 |_, _| Ok(()),
4056 )
4057 .unwrap();
4058
4059 assert_eq!(
4060 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4061 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004062 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004063 KeyType::Client,
4064 KeyEntryLoadBits::NONE,
4065 1,
4066 |_k, _av| Ok(()),
4067 )
4068 .unwrap_err()
4069 .root_cause()
4070 .downcast_ref::<KsError>()
4071 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004072
4073 Ok(())
4074 }
4075
4076 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004077 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4078 let mut db = new_test_db()?;
4079 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4080 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4081 .0;
4082 // Update the usage count of the limited use key.
4083 db.check_and_update_key_usage_count(key_id)?;
4084
4085 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004086 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004087 KeyType::Client,
4088 KeyEntryLoadBits::BOTH,
4089 1,
4090 |_k, _av| Ok(()),
4091 )?;
4092
4093 // The usage count is decremented now.
4094 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4095
4096 Ok(())
4097 }
4098
4099 #[test]
4100 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4101 let mut db = new_test_db()?;
4102 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4103 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4104 .0;
4105 // Update the usage count of the limited use key.
4106 db.check_and_update_key_usage_count(key_id).expect(concat!(
4107 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4108 "This should succeed."
4109 ));
4110
4111 // Try to update the exhausted limited use key.
4112 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4113 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4114 "This should fail."
4115 ));
4116 assert_eq!(
4117 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4118 e.root_cause().downcast_ref::<KsError>().unwrap()
4119 );
4120
4121 Ok(())
4122 }
4123
4124 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004125 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4126 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004127 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004128 .context("test_insert_and_load_full_keyentry_from_grant")?
4129 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004130
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004131 let granted_key = db
4132 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004133 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004134 domain: Domain::APP,
4135 nspace: 0,
4136 alias: Some(TEST_ALIAS.to_string()),
4137 blob: None,
4138 },
4139 1,
4140 2,
4141 key_perm_set![KeyPerm::use_()],
4142 |_k, _av| Ok(()),
4143 )
4144 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004145
4146 debug_dump_grant_table(&mut db)?;
4147
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004148 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004149 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4150 assert_eq!(Domain::GRANT, k.domain);
4151 assert!(av.unwrap().includes(KeyPerm::use_()));
4152 Ok(())
4153 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004154 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004155
Qi Wub9433b52020-12-01 14:52:46 +08004156 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004157
Janis Danisevskis66784c42021-01-27 08:40:25 -08004158 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004159
4160 assert_eq!(
4161 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4162 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004163 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004164 KeyType::Client,
4165 KeyEntryLoadBits::NONE,
4166 2,
4167 |_k, _av| Ok(()),
4168 )
4169 .unwrap_err()
4170 .root_cause()
4171 .downcast_ref::<KsError>()
4172 );
4173
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004174 Ok(())
4175 }
4176
Janis Danisevskis45760022021-01-19 16:34:10 -08004177 // This test attempts to load a key by key id while the caller is not the owner
4178 // but a grant exists for the given key and the caller.
4179 #[test]
4180 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4181 let mut db = new_test_db()?;
4182 const OWNER_UID: u32 = 1u32;
4183 const GRANTEE_UID: u32 = 2u32;
4184 const SOMEONE_ELSE_UID: u32 = 3u32;
4185 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4186 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4187 .0;
4188
4189 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004190 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004191 domain: Domain::APP,
4192 nspace: 0,
4193 alias: Some(TEST_ALIAS.to_string()),
4194 blob: None,
4195 },
4196 OWNER_UID,
4197 GRANTEE_UID,
4198 key_perm_set![KeyPerm::use_()],
4199 |_k, _av| Ok(()),
4200 )
4201 .unwrap();
4202
4203 debug_dump_grant_table(&mut db)?;
4204
4205 let id_descriptor =
4206 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4207
4208 let (_, key_entry) = db
4209 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004210 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004211 KeyType::Client,
4212 KeyEntryLoadBits::BOTH,
4213 GRANTEE_UID,
4214 |k, av| {
4215 assert_eq!(Domain::APP, k.domain);
4216 assert_eq!(OWNER_UID as i64, k.nspace);
4217 assert!(av.unwrap().includes(KeyPerm::use_()));
4218 Ok(())
4219 },
4220 )
4221 .unwrap();
4222
4223 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4224
4225 let (_, key_entry) = db
4226 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004227 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004228 KeyType::Client,
4229 KeyEntryLoadBits::BOTH,
4230 SOMEONE_ELSE_UID,
4231 |k, av| {
4232 assert_eq!(Domain::APP, k.domain);
4233 assert_eq!(OWNER_UID as i64, k.nspace);
4234 assert!(av.is_none());
4235 Ok(())
4236 },
4237 )
4238 .unwrap();
4239
4240 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4241
Janis Danisevskis66784c42021-01-27 08:40:25 -08004242 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004243
4244 assert_eq!(
4245 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4246 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004247 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004248 KeyType::Client,
4249 KeyEntryLoadBits::NONE,
4250 GRANTEE_UID,
4251 |_k, _av| Ok(()),
4252 )
4253 .unwrap_err()
4254 .root_cause()
4255 .downcast_ref::<KsError>()
4256 );
4257
4258 Ok(())
4259 }
4260
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004261 // Creates a key migrates it to a different location and then tries to access it by the old
4262 // and new location.
4263 #[test]
4264 fn test_migrate_key_app_to_app() -> Result<()> {
4265 let mut db = new_test_db()?;
4266 const SOURCE_UID: u32 = 1u32;
4267 const DESTINATION_UID: u32 = 2u32;
4268 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4269 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4270 let key_id_guard =
4271 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4272 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4273
4274 let source_descriptor: KeyDescriptor = KeyDescriptor {
4275 domain: Domain::APP,
4276 nspace: -1,
4277 alias: Some(SOURCE_ALIAS.to_string()),
4278 blob: None,
4279 };
4280
4281 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4282 domain: Domain::APP,
4283 nspace: -1,
4284 alias: Some(DESTINATION_ALIAS.to_string()),
4285 blob: None,
4286 };
4287
4288 let key_id = key_id_guard.id();
4289
4290 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4291 Ok(())
4292 })
4293 .unwrap();
4294
4295 let (_, key_entry) = db
4296 .load_key_entry(
4297 &destination_descriptor,
4298 KeyType::Client,
4299 KeyEntryLoadBits::BOTH,
4300 DESTINATION_UID,
4301 |k, av| {
4302 assert_eq!(Domain::APP, k.domain);
4303 assert_eq!(DESTINATION_UID as i64, k.nspace);
4304 assert!(av.is_none());
4305 Ok(())
4306 },
4307 )
4308 .unwrap();
4309
4310 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4311
4312 assert_eq!(
4313 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4314 db.load_key_entry(
4315 &source_descriptor,
4316 KeyType::Client,
4317 KeyEntryLoadBits::NONE,
4318 SOURCE_UID,
4319 |_k, _av| Ok(()),
4320 )
4321 .unwrap_err()
4322 .root_cause()
4323 .downcast_ref::<KsError>()
4324 );
4325
4326 Ok(())
4327 }
4328
4329 // Creates a key migrates it to a different location and then tries to access it by the old
4330 // and new location.
4331 #[test]
4332 fn test_migrate_key_app_to_selinux() -> Result<()> {
4333 let mut db = new_test_db()?;
4334 const SOURCE_UID: u32 = 1u32;
4335 const DESTINATION_UID: u32 = 2u32;
4336 const DESTINATION_NAMESPACE: i64 = 1000i64;
4337 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4338 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4339 let key_id_guard =
4340 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4341 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4342
4343 let source_descriptor: KeyDescriptor = KeyDescriptor {
4344 domain: Domain::APP,
4345 nspace: -1,
4346 alias: Some(SOURCE_ALIAS.to_string()),
4347 blob: None,
4348 };
4349
4350 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4351 domain: Domain::SELINUX,
4352 nspace: DESTINATION_NAMESPACE,
4353 alias: Some(DESTINATION_ALIAS.to_string()),
4354 blob: None,
4355 };
4356
4357 let key_id = key_id_guard.id();
4358
4359 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4360 Ok(())
4361 })
4362 .unwrap();
4363
4364 let (_, key_entry) = db
4365 .load_key_entry(
4366 &destination_descriptor,
4367 KeyType::Client,
4368 KeyEntryLoadBits::BOTH,
4369 DESTINATION_UID,
4370 |k, av| {
4371 assert_eq!(Domain::SELINUX, k.domain);
4372 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4373 assert!(av.is_none());
4374 Ok(())
4375 },
4376 )
4377 .unwrap();
4378
4379 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4380
4381 assert_eq!(
4382 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4383 db.load_key_entry(
4384 &source_descriptor,
4385 KeyType::Client,
4386 KeyEntryLoadBits::NONE,
4387 SOURCE_UID,
4388 |_k, _av| Ok(()),
4389 )
4390 .unwrap_err()
4391 .root_cause()
4392 .downcast_ref::<KsError>()
4393 );
4394
4395 Ok(())
4396 }
4397
4398 // Creates two keys and tries to migrate the first to the location of the second which
4399 // is expected to fail.
4400 #[test]
4401 fn test_migrate_key_destination_occupied() -> Result<()> {
4402 let mut db = new_test_db()?;
4403 const SOURCE_UID: u32 = 1u32;
4404 const DESTINATION_UID: u32 = 2u32;
4405 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4406 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4407 let key_id_guard =
4408 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4409 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4410 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4411 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4412
4413 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4414 domain: Domain::APP,
4415 nspace: -1,
4416 alias: Some(DESTINATION_ALIAS.to_string()),
4417 blob: None,
4418 };
4419
4420 assert_eq!(
4421 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4422 db.migrate_key_namespace(
4423 key_id_guard,
4424 &destination_descriptor,
4425 DESTINATION_UID,
4426 |_k| Ok(())
4427 )
4428 .unwrap_err()
4429 .root_cause()
4430 .downcast_ref::<KsError>()
4431 );
4432
4433 Ok(())
4434 }
4435
Janis Danisevskisaec14592020-11-12 09:41:49 -08004436 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4437
Janis Danisevskisaec14592020-11-12 09:41:49 -08004438 #[test]
4439 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4440 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004441 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4442 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004443 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004444 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004445 .context("test_insert_and_load_full_keyentry_domain_app")?
4446 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004447 let (_key_guard, key_entry) = db
4448 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004449 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004450 domain: Domain::APP,
4451 nspace: 0,
4452 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4453 blob: None,
4454 },
4455 KeyType::Client,
4456 KeyEntryLoadBits::BOTH,
4457 33,
4458 |_k, _av| Ok(()),
4459 )
4460 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004461 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004462 let state = Arc::new(AtomicU8::new(1));
4463 let state2 = state.clone();
4464
4465 // Spawning a second thread that attempts to acquire the key id lock
4466 // for the same key as the primary thread. The primary thread then
4467 // waits, thereby forcing the secondary thread into the second stage
4468 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4469 // The test succeeds if the secondary thread observes the transition
4470 // of `state` from 1 to 2, despite having a whole second to overtake
4471 // the primary thread.
4472 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004473 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004474 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004475 assert!(db
4476 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004477 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004478 domain: Domain::APP,
4479 nspace: 0,
4480 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4481 blob: None,
4482 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004483 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004484 KeyEntryLoadBits::BOTH,
4485 33,
4486 |_k, _av| Ok(()),
4487 )
4488 .is_ok());
4489 // We should only see a 2 here because we can only return
4490 // from load_key_entry when the `_key_guard` expires,
4491 // which happens at the end of the scope.
4492 assert_eq!(2, state2.load(Ordering::Relaxed));
4493 });
4494
4495 thread::sleep(std::time::Duration::from_millis(1000));
4496
4497 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4498
4499 // Return the handle from this scope so we can join with the
4500 // secondary thread after the key id lock has expired.
4501 handle
4502 // This is where the `_key_guard` goes out of scope,
4503 // which is the reason for concurrent load_key_entry on the same key
4504 // to unblock.
4505 };
4506 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4507 // main test thread. We will not see failing asserts in secondary threads otherwise.
4508 handle.join().unwrap();
4509 Ok(())
4510 }
4511
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004512 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004513 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004514 let temp_dir =
4515 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4516
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004517 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4518 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004519
4520 let _tx1 = db1
4521 .conn
4522 .transaction_with_behavior(TransactionBehavior::Immediate)
4523 .expect("Failed to create first transaction.");
4524
4525 let error = db2
4526 .conn
4527 .transaction_with_behavior(TransactionBehavior::Immediate)
4528 .context("Transaction begin failed.")
4529 .expect_err("This should fail.");
4530 let root_cause = error.root_cause();
4531 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4532 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4533 {
4534 return;
4535 }
4536 panic!(
4537 "Unexpected error {:?} \n{:?} \n{:?}",
4538 error,
4539 root_cause,
4540 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4541 )
4542 }
4543
4544 #[cfg(disabled)]
4545 #[test]
4546 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4547 let temp_dir = Arc::new(
4548 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4549 .expect("Failed to create temp dir."),
4550 );
4551
4552 let test_begin = Instant::now();
4553
4554 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4555 const KEY_COUNT: u32 = 500u32;
4556 const OPEN_DB_COUNT: u32 = 50u32;
4557
4558 let mut actual_key_count = KEY_COUNT;
4559 // First insert KEY_COUNT keys.
4560 for count in 0..KEY_COUNT {
4561 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4562 actual_key_count = count;
4563 break;
4564 }
4565 let alias = format!("test_alias_{}", count);
4566 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4567 .expect("Failed to make key entry.");
4568 }
4569
4570 // Insert more keys from a different thread and into a different namespace.
4571 let temp_dir1 = temp_dir.clone();
4572 let handle1 = thread::spawn(move || {
4573 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4574
4575 for count in 0..actual_key_count {
4576 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4577 return;
4578 }
4579 let alias = format!("test_alias_{}", count);
4580 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4581 .expect("Failed to make key entry.");
4582 }
4583
4584 // then unbind them again.
4585 for count in 0..actual_key_count {
4586 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4587 return;
4588 }
4589 let key = KeyDescriptor {
4590 domain: Domain::APP,
4591 nspace: -1,
4592 alias: Some(format!("test_alias_{}", count)),
4593 blob: None,
4594 };
4595 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4596 }
4597 });
4598
4599 // And start unbinding the first set of keys.
4600 let temp_dir2 = temp_dir.clone();
4601 let handle2 = thread::spawn(move || {
4602 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4603
4604 for count in 0..actual_key_count {
4605 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4606 return;
4607 }
4608 let key = KeyDescriptor {
4609 domain: Domain::APP,
4610 nspace: -1,
4611 alias: Some(format!("test_alias_{}", count)),
4612 blob: None,
4613 };
4614 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4615 }
4616 });
4617
4618 let stop_deleting = Arc::new(AtomicU8::new(0));
4619 let stop_deleting2 = stop_deleting.clone();
4620
4621 // And delete anything that is unreferenced keys.
4622 let temp_dir3 = temp_dir.clone();
4623 let handle3 = thread::spawn(move || {
4624 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4625
4626 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4627 while let Some((key_guard, _key)) =
4628 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4629 {
4630 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4631 return;
4632 }
4633 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4634 }
4635 std::thread::sleep(std::time::Duration::from_millis(100));
4636 }
4637 });
4638
4639 // While a lot of inserting and deleting is going on we have to open database connections
4640 // successfully and use them.
4641 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4642 // out of scope.
4643 #[allow(clippy::redundant_clone)]
4644 let temp_dir4 = temp_dir.clone();
4645 let handle4 = thread::spawn(move || {
4646 for count in 0..OPEN_DB_COUNT {
4647 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4648 return;
4649 }
4650 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4651
4652 let alias = format!("test_alias_{}", count);
4653 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4654 .expect("Failed to make key entry.");
4655 let key = KeyDescriptor {
4656 domain: Domain::APP,
4657 nspace: -1,
4658 alias: Some(alias),
4659 blob: None,
4660 };
4661 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4662 }
4663 });
4664
4665 handle1.join().expect("Thread 1 panicked.");
4666 handle2.join().expect("Thread 2 panicked.");
4667 handle4.join().expect("Thread 4 panicked.");
4668
4669 stop_deleting.store(1, Ordering::Relaxed);
4670 handle3.join().expect("Thread 3 panicked.");
4671
4672 Ok(())
4673 }
4674
4675 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004676 fn list() -> Result<()> {
4677 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004678 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004679 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4680 (Domain::APP, 1, "test1"),
4681 (Domain::APP, 1, "test2"),
4682 (Domain::APP, 1, "test3"),
4683 (Domain::APP, 1, "test4"),
4684 (Domain::APP, 1, "test5"),
4685 (Domain::APP, 1, "test6"),
4686 (Domain::APP, 1, "test7"),
4687 (Domain::APP, 2, "test1"),
4688 (Domain::APP, 2, "test2"),
4689 (Domain::APP, 2, "test3"),
4690 (Domain::APP, 2, "test4"),
4691 (Domain::APP, 2, "test5"),
4692 (Domain::APP, 2, "test6"),
4693 (Domain::APP, 2, "test8"),
4694 (Domain::SELINUX, 100, "test1"),
4695 (Domain::SELINUX, 100, "test2"),
4696 (Domain::SELINUX, 100, "test3"),
4697 (Domain::SELINUX, 100, "test4"),
4698 (Domain::SELINUX, 100, "test5"),
4699 (Domain::SELINUX, 100, "test6"),
4700 (Domain::SELINUX, 100, "test9"),
4701 ];
4702
4703 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4704 .iter()
4705 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004706 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4707 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004708 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4709 });
4710 (entry.id(), *ns)
4711 })
4712 .collect();
4713
4714 for (domain, namespace) in
4715 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4716 {
4717 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4718 .iter()
4719 .filter_map(|(domain, ns, alias)| match ns {
4720 ns if *ns == *namespace => Some(KeyDescriptor {
4721 domain: *domain,
4722 nspace: *ns,
4723 alias: Some(alias.to_string()),
4724 blob: None,
4725 }),
4726 _ => None,
4727 })
4728 .collect();
4729 list_o_descriptors.sort();
4730 let mut list_result = db.list(*domain, *namespace)?;
4731 list_result.sort();
4732 assert_eq!(list_o_descriptors, list_result);
4733
4734 let mut list_o_ids: Vec<i64> = list_o_descriptors
4735 .into_iter()
4736 .map(|d| {
4737 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004738 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004739 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004740 KeyType::Client,
4741 KeyEntryLoadBits::NONE,
4742 *namespace as u32,
4743 |_, _| Ok(()),
4744 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004745 .unwrap();
4746 entry.id()
4747 })
4748 .collect();
4749 list_o_ids.sort_unstable();
4750 let mut loaded_entries: Vec<i64> = list_o_keys
4751 .iter()
4752 .filter_map(|(id, ns)| match ns {
4753 ns if *ns == *namespace => Some(*id),
4754 _ => None,
4755 })
4756 .collect();
4757 loaded_entries.sort_unstable();
4758 assert_eq!(list_o_ids, loaded_entries);
4759 }
4760 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4761
4762 Ok(())
4763 }
4764
Joel Galenson0891bc12020-07-20 10:37:03 -07004765 // Helpers
4766
4767 // Checks that the given result is an error containing the given string.
4768 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4769 let error_str = format!(
4770 "{:#?}",
4771 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4772 );
4773 assert!(
4774 error_str.contains(target),
4775 "The string \"{}\" should contain \"{}\"",
4776 error_str,
4777 target
4778 );
4779 }
4780
Joel Galenson2aab4432020-07-22 15:27:57 -07004781 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004782 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004783 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004784 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004785 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004786 namespace: Option<i64>,
4787 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004788 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004789 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004790 }
4791
4792 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4793 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004794 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004795 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004796 Ok(KeyEntryRow {
4797 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004798 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004799 domain: match row.get(2)? {
4800 Some(i) => Some(Domain(i)),
4801 None => None,
4802 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004803 namespace: row.get(3)?,
4804 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004805 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004806 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004807 })
4808 })?
4809 .map(|r| r.context("Could not read keyentry row."))
4810 .collect::<Result<Vec<_>>>()
4811 }
4812
Max Biresb2e1d032021-02-08 21:35:05 -08004813 struct RemoteProvValues {
4814 cert_chain: Vec<u8>,
4815 priv_key: Vec<u8>,
4816 batch_cert: Vec<u8>,
4817 }
4818
Max Bires2b2e6562020-09-22 11:22:36 -07004819 fn load_attestation_key_pool(
4820 db: &mut KeystoreDB,
4821 expiration_date: i64,
4822 namespace: i64,
4823 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004824 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004825 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4826 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4827 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4828 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004829 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004830 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4831 db.store_signed_attestation_certificate_chain(
4832 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004833 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004834 &cert_chain,
4835 expiration_date,
4836 &KEYSTORE_UUID,
4837 )?;
4838 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004839 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004840 }
4841
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004842 // Note: The parameters and SecurityLevel associations are nonsensical. This
4843 // collection is only used to check if the parameters are preserved as expected by the
4844 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004845 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4846 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004847 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4848 KeyParameter::new(
4849 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4850 SecurityLevel::TRUSTED_ENVIRONMENT,
4851 ),
4852 KeyParameter::new(
4853 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4854 SecurityLevel::TRUSTED_ENVIRONMENT,
4855 ),
4856 KeyParameter::new(
4857 KeyParameterValue::Algorithm(Algorithm::RSA),
4858 SecurityLevel::TRUSTED_ENVIRONMENT,
4859 ),
4860 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4861 KeyParameter::new(
4862 KeyParameterValue::BlockMode(BlockMode::ECB),
4863 SecurityLevel::TRUSTED_ENVIRONMENT,
4864 ),
4865 KeyParameter::new(
4866 KeyParameterValue::BlockMode(BlockMode::GCM),
4867 SecurityLevel::TRUSTED_ENVIRONMENT,
4868 ),
4869 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4870 KeyParameter::new(
4871 KeyParameterValue::Digest(Digest::MD5),
4872 SecurityLevel::TRUSTED_ENVIRONMENT,
4873 ),
4874 KeyParameter::new(
4875 KeyParameterValue::Digest(Digest::SHA_2_224),
4876 SecurityLevel::TRUSTED_ENVIRONMENT,
4877 ),
4878 KeyParameter::new(
4879 KeyParameterValue::Digest(Digest::SHA_2_256),
4880 SecurityLevel::STRONGBOX,
4881 ),
4882 KeyParameter::new(
4883 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4884 SecurityLevel::TRUSTED_ENVIRONMENT,
4885 ),
4886 KeyParameter::new(
4887 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4888 SecurityLevel::TRUSTED_ENVIRONMENT,
4889 ),
4890 KeyParameter::new(
4891 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4892 SecurityLevel::STRONGBOX,
4893 ),
4894 KeyParameter::new(
4895 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4896 SecurityLevel::TRUSTED_ENVIRONMENT,
4897 ),
4898 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4899 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4900 KeyParameter::new(
4901 KeyParameterValue::EcCurve(EcCurve::P_224),
4902 SecurityLevel::TRUSTED_ENVIRONMENT,
4903 ),
4904 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4905 KeyParameter::new(
4906 KeyParameterValue::EcCurve(EcCurve::P_384),
4907 SecurityLevel::TRUSTED_ENVIRONMENT,
4908 ),
4909 KeyParameter::new(
4910 KeyParameterValue::EcCurve(EcCurve::P_521),
4911 SecurityLevel::TRUSTED_ENVIRONMENT,
4912 ),
4913 KeyParameter::new(
4914 KeyParameterValue::RSAPublicExponent(3),
4915 SecurityLevel::TRUSTED_ENVIRONMENT,
4916 ),
4917 KeyParameter::new(
4918 KeyParameterValue::IncludeUniqueID,
4919 SecurityLevel::TRUSTED_ENVIRONMENT,
4920 ),
4921 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4922 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4923 KeyParameter::new(
4924 KeyParameterValue::ActiveDateTime(1234567890),
4925 SecurityLevel::STRONGBOX,
4926 ),
4927 KeyParameter::new(
4928 KeyParameterValue::OriginationExpireDateTime(1234567890),
4929 SecurityLevel::TRUSTED_ENVIRONMENT,
4930 ),
4931 KeyParameter::new(
4932 KeyParameterValue::UsageExpireDateTime(1234567890),
4933 SecurityLevel::TRUSTED_ENVIRONMENT,
4934 ),
4935 KeyParameter::new(
4936 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4937 SecurityLevel::TRUSTED_ENVIRONMENT,
4938 ),
4939 KeyParameter::new(
4940 KeyParameterValue::MaxUsesPerBoot(1234567890),
4941 SecurityLevel::TRUSTED_ENVIRONMENT,
4942 ),
4943 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4944 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4945 KeyParameter::new(
4946 KeyParameterValue::NoAuthRequired,
4947 SecurityLevel::TRUSTED_ENVIRONMENT,
4948 ),
4949 KeyParameter::new(
4950 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4951 SecurityLevel::TRUSTED_ENVIRONMENT,
4952 ),
4953 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4954 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4955 KeyParameter::new(
4956 KeyParameterValue::TrustedUserPresenceRequired,
4957 SecurityLevel::TRUSTED_ENVIRONMENT,
4958 ),
4959 KeyParameter::new(
4960 KeyParameterValue::TrustedConfirmationRequired,
4961 SecurityLevel::TRUSTED_ENVIRONMENT,
4962 ),
4963 KeyParameter::new(
4964 KeyParameterValue::UnlockedDeviceRequired,
4965 SecurityLevel::TRUSTED_ENVIRONMENT,
4966 ),
4967 KeyParameter::new(
4968 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4969 SecurityLevel::SOFTWARE,
4970 ),
4971 KeyParameter::new(
4972 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4973 SecurityLevel::SOFTWARE,
4974 ),
4975 KeyParameter::new(
4976 KeyParameterValue::CreationDateTime(12345677890),
4977 SecurityLevel::SOFTWARE,
4978 ),
4979 KeyParameter::new(
4980 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4981 SecurityLevel::TRUSTED_ENVIRONMENT,
4982 ),
4983 KeyParameter::new(
4984 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4985 SecurityLevel::TRUSTED_ENVIRONMENT,
4986 ),
4987 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4988 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4989 KeyParameter::new(
4990 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4991 SecurityLevel::SOFTWARE,
4992 ),
4993 KeyParameter::new(
4994 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4995 SecurityLevel::TRUSTED_ENVIRONMENT,
4996 ),
4997 KeyParameter::new(
4998 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4999 SecurityLevel::TRUSTED_ENVIRONMENT,
5000 ),
5001 KeyParameter::new(
5002 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5003 SecurityLevel::TRUSTED_ENVIRONMENT,
5004 ),
5005 KeyParameter::new(
5006 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5007 SecurityLevel::TRUSTED_ENVIRONMENT,
5008 ),
5009 KeyParameter::new(
5010 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5011 SecurityLevel::TRUSTED_ENVIRONMENT,
5012 ),
5013 KeyParameter::new(
5014 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5015 SecurityLevel::TRUSTED_ENVIRONMENT,
5016 ),
5017 KeyParameter::new(
5018 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5019 SecurityLevel::TRUSTED_ENVIRONMENT,
5020 ),
5021 KeyParameter::new(
5022 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5023 SecurityLevel::TRUSTED_ENVIRONMENT,
5024 ),
5025 KeyParameter::new(
5026 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5027 SecurityLevel::TRUSTED_ENVIRONMENT,
5028 ),
5029 KeyParameter::new(
5030 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5031 SecurityLevel::TRUSTED_ENVIRONMENT,
5032 ),
5033 KeyParameter::new(
5034 KeyParameterValue::VendorPatchLevel(3),
5035 SecurityLevel::TRUSTED_ENVIRONMENT,
5036 ),
5037 KeyParameter::new(
5038 KeyParameterValue::BootPatchLevel(4),
5039 SecurityLevel::TRUSTED_ENVIRONMENT,
5040 ),
5041 KeyParameter::new(
5042 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5043 SecurityLevel::TRUSTED_ENVIRONMENT,
5044 ),
5045 KeyParameter::new(
5046 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5047 SecurityLevel::TRUSTED_ENVIRONMENT,
5048 ),
5049 KeyParameter::new(
5050 KeyParameterValue::MacLength(256),
5051 SecurityLevel::TRUSTED_ENVIRONMENT,
5052 ),
5053 KeyParameter::new(
5054 KeyParameterValue::ResetSinceIdRotation,
5055 SecurityLevel::TRUSTED_ENVIRONMENT,
5056 ),
5057 KeyParameter::new(
5058 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5059 SecurityLevel::TRUSTED_ENVIRONMENT,
5060 ),
Qi Wub9433b52020-12-01 14:52:46 +08005061 ];
5062 if let Some(value) = max_usage_count {
5063 params.push(KeyParameter::new(
5064 KeyParameterValue::UsageCountLimit(value),
5065 SecurityLevel::SOFTWARE,
5066 ));
5067 }
5068 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005069 }
5070
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005071 fn make_test_key_entry(
5072 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005073 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005074 namespace: i64,
5075 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005076 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005077 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005078 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005079 let mut blob_metadata = BlobMetaData::new();
5080 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5081 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5082 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5083 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5084 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5085
5086 db.set_blob(
5087 &key_id,
5088 SubComponentType::KEY_BLOB,
5089 Some(TEST_KEY_BLOB),
5090 Some(&blob_metadata),
5091 )?;
5092 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5093 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005094
5095 let params = make_test_params(max_usage_count);
5096 db.insert_keyparameter(&key_id, &params)?;
5097
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005098 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005099 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005100 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005101 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005102 Ok(key_id)
5103 }
5104
Qi Wub9433b52020-12-01 14:52:46 +08005105 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5106 let params = make_test_params(max_usage_count);
5107
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005108 let mut blob_metadata = BlobMetaData::new();
5109 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5110 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5111 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5112 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5113 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5114
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005115 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005116 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005117
5118 KeyEntry {
5119 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005120 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005121 cert: Some(TEST_CERT_BLOB.to_vec()),
5122 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005123 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005124 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005125 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005126 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005127 }
5128 }
5129
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005130 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005131 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005132 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005133 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005134 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005135 NO_PARAMS,
5136 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005137 Ok((
5138 row.get(0)?,
5139 row.get(1)?,
5140 row.get(2)?,
5141 row.get(3)?,
5142 row.get(4)?,
5143 row.get(5)?,
5144 row.get(6)?,
5145 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005146 },
5147 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005148
5149 println!("Key entry table rows:");
5150 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005151 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005152 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005153 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5154 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005155 );
5156 }
5157 Ok(())
5158 }
5159
5160 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005161 let mut stmt = db
5162 .conn
5163 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005164 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5165 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5166 })?;
5167
5168 println!("Grant table rows:");
5169 for r in rows {
5170 let (id, gt, ki, av) = r.unwrap();
5171 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5172 }
5173 Ok(())
5174 }
5175
Joel Galenson0891bc12020-07-20 10:37:03 -07005176 // Use a custom random number generator that repeats each number once.
5177 // This allows us to test repeated elements.
5178
5179 thread_local! {
5180 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5181 }
5182
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005183 fn reset_random() {
5184 RANDOM_COUNTER.with(|counter| {
5185 *counter.borrow_mut() = 0;
5186 })
5187 }
5188
Joel Galenson0891bc12020-07-20 10:37:03 -07005189 pub fn random() -> i64 {
5190 RANDOM_COUNTER.with(|counter| {
5191 let result = *counter.borrow() / 2;
5192 *counter.borrow_mut() += 1;
5193 result
5194 })
5195 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005196
5197 #[test]
5198 fn test_last_off_body() -> Result<()> {
5199 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005200 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005201 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005202 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005203 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005204 let one_second = Duration::from_secs(1);
5205 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005206 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005207 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005208 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005209 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005210 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5211 Ok(())
5212 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005213
5214 #[test]
5215 fn test_unbind_keys_for_user() -> Result<()> {
5216 let mut db = new_test_db()?;
5217 db.unbind_keys_for_user(1, false)?;
5218
5219 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5220 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5221 db.unbind_keys_for_user(2, false)?;
5222
5223 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5224 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5225
5226 db.unbind_keys_for_user(1, true)?;
5227 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5228
5229 Ok(())
5230 }
5231
5232 #[test]
5233 fn test_store_super_key() -> Result<()> {
5234 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005235 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005236 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005237 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005238 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005239 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005240
5241 let (encrypted_super_key, metadata) =
5242 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005243 db.store_super_key(
5244 1,
5245 &USER_SUPER_KEY,
5246 &encrypted_super_key,
5247 &metadata,
5248 &KeyMetaData::new(),
5249 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005250
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005251 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005252 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005253
Paul Crowley7a658392021-03-18 17:08:20 -07005254 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005255 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5256 USER_SUPER_KEY.algorithm,
5257 key_entry,
5258 &pw,
5259 None,
5260 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005261
Paul Crowley7a658392021-03-18 17:08:20 -07005262 let decrypted_secret_bytes =
5263 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5264 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005265 Ok(())
5266 }
Seth Moore78c091f2021-04-09 21:38:30 +00005267
5268 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5269 vec![
5270 StatsdStorageType::KeyEntry,
5271 StatsdStorageType::KeyEntryIdIndex,
5272 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5273 StatsdStorageType::BlobEntry,
5274 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5275 StatsdStorageType::KeyParameter,
5276 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5277 StatsdStorageType::KeyMetadata,
5278 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5279 StatsdStorageType::Grant,
5280 StatsdStorageType::AuthToken,
5281 StatsdStorageType::BlobMetadata,
5282 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5283 ]
5284 }
5285
5286 /// Perform a simple check to ensure that we can query all the storage types
5287 /// that are supported by the DB. Check for reasonable values.
5288 #[test]
5289 fn test_query_all_valid_table_sizes() -> Result<()> {
5290 const PAGE_SIZE: i64 = 4096;
5291
5292 let mut db = new_test_db()?;
5293
5294 for t in get_valid_statsd_storage_types() {
5295 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005296 // AuthToken can be less than a page since it's in a btree, not sqlite
5297 // TODO(b/187474736) stop using if-let here
5298 if let StatsdStorageType::AuthToken = t {
5299 } else {
5300 assert!(stat.size >= PAGE_SIZE);
5301 }
Seth Moore78c091f2021-04-09 21:38:30 +00005302 assert!(stat.size >= stat.unused_size);
5303 }
5304
5305 Ok(())
5306 }
5307
5308 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5309 get_valid_statsd_storage_types()
5310 .into_iter()
5311 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5312 .collect()
5313 }
5314
5315 fn assert_storage_increased(
5316 db: &mut KeystoreDB,
5317 increased_storage_types: Vec<StatsdStorageType>,
5318 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5319 ) {
5320 for storage in increased_storage_types {
5321 // Verify the expected storage increased.
5322 let new = db.get_storage_stat(storage).unwrap();
5323 let storage = storage as i32;
5324 let old = &baseline[&storage];
5325 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5326 assert!(
5327 new.unused_size <= old.unused_size,
5328 "{}: {} <= {}",
5329 storage,
5330 new.unused_size,
5331 old.unused_size
5332 );
5333
5334 // Update the baseline with the new value so that it succeeds in the
5335 // later comparison.
5336 baseline.insert(storage, new);
5337 }
5338
5339 // Get an updated map of the storage and verify there were no unexpected changes.
5340 let updated_stats = get_storage_stats_map(db);
5341 assert_eq!(updated_stats.len(), baseline.len());
5342
5343 for &k in baseline.keys() {
5344 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5345 let mut s = String::new();
5346 for &k in map.keys() {
5347 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5348 .expect("string concat failed");
5349 }
5350 s
5351 };
5352
5353 assert!(
5354 updated_stats[&k].size == baseline[&k].size
5355 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5356 "updated_stats:\n{}\nbaseline:\n{}",
5357 stringify(&updated_stats),
5358 stringify(&baseline)
5359 );
5360 }
5361 }
5362
5363 #[test]
5364 fn test_verify_key_table_size_reporting() -> Result<()> {
5365 let mut db = new_test_db()?;
5366 let mut working_stats = get_storage_stats_map(&mut db);
5367
5368 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5369 assert_storage_increased(
5370 &mut db,
5371 vec![
5372 StatsdStorageType::KeyEntry,
5373 StatsdStorageType::KeyEntryIdIndex,
5374 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5375 ],
5376 &mut working_stats,
5377 );
5378
5379 let mut blob_metadata = BlobMetaData::new();
5380 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5381 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5382 assert_storage_increased(
5383 &mut db,
5384 vec![
5385 StatsdStorageType::BlobEntry,
5386 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5387 StatsdStorageType::BlobMetadata,
5388 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5389 ],
5390 &mut working_stats,
5391 );
5392
5393 let params = make_test_params(None);
5394 db.insert_keyparameter(&key_id, &params)?;
5395 assert_storage_increased(
5396 &mut db,
5397 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5398 &mut working_stats,
5399 );
5400
5401 let mut metadata = KeyMetaData::new();
5402 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5403 db.insert_key_metadata(&key_id, &metadata)?;
5404 assert_storage_increased(
5405 &mut db,
5406 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5407 &mut working_stats,
5408 );
5409
5410 let mut sum = 0;
5411 for stat in working_stats.values() {
5412 sum += stat.size;
5413 }
5414 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5415 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5416
5417 Ok(())
5418 }
5419
5420 #[test]
5421 fn test_verify_auth_table_size_reporting() -> Result<()> {
5422 let mut db = new_test_db()?;
5423 let mut working_stats = get_storage_stats_map(&mut db);
5424 db.insert_auth_token(&HardwareAuthToken {
5425 challenge: 123,
5426 userId: 456,
5427 authenticatorId: 789,
5428 authenticatorType: kmhw_authenticator_type::ANY,
5429 timestamp: Timestamp { milliSeconds: 10 },
5430 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005431 });
Seth Moore78c091f2021-04-09 21:38:30 +00005432 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5433 Ok(())
5434 }
5435
5436 #[test]
5437 fn test_verify_grant_table_size_reporting() -> Result<()> {
5438 const OWNER: i64 = 1;
5439 let mut db = new_test_db()?;
5440 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5441
5442 let mut working_stats = get_storage_stats_map(&mut db);
5443 db.grant(
5444 &KeyDescriptor {
5445 domain: Domain::APP,
5446 nspace: 0,
5447 alias: Some(TEST_ALIAS.to_string()),
5448 blob: None,
5449 },
5450 OWNER as u32,
5451 123,
5452 key_perm_set![KeyPerm::use_()],
5453 |_, _| Ok(()),
5454 )?;
5455
5456 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5457
5458 Ok(())
5459 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005460
5461 #[test]
5462 fn find_auth_token_entry_returns_latest() -> Result<()> {
5463 let mut db = new_test_db()?;
5464 db.insert_auth_token(&HardwareAuthToken {
5465 challenge: 123,
5466 userId: 456,
5467 authenticatorId: 789,
5468 authenticatorType: kmhw_authenticator_type::ANY,
5469 timestamp: Timestamp { milliSeconds: 10 },
5470 mac: b"mac0".to_vec(),
5471 });
5472 std::thread::sleep(std::time::Duration::from_millis(1));
5473 db.insert_auth_token(&HardwareAuthToken {
5474 challenge: 123,
5475 userId: 457,
5476 authenticatorId: 789,
5477 authenticatorType: kmhw_authenticator_type::ANY,
5478 timestamp: Timestamp { milliSeconds: 12 },
5479 mac: b"mac1".to_vec(),
5480 });
5481 std::thread::sleep(std::time::Duration::from_millis(1));
5482 db.insert_auth_token(&HardwareAuthToken {
5483 challenge: 123,
5484 userId: 458,
5485 authenticatorId: 789,
5486 authenticatorType: kmhw_authenticator_type::ANY,
5487 timestamp: Timestamp { milliSeconds: 3 },
5488 mac: b"mac2".to_vec(),
5489 });
5490 // All three entries are in the database
5491 assert_eq!(db.perboot.auth_tokens_len(), 3);
5492 // It selected the most recent timestamp
5493 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5494 Ok(())
5495 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005496
5497 #[test]
5498 fn test_set_wal_mode() -> Result<()> {
5499 let temp_dir = TempDir::new("test_set_wal_mode")?;
5500 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5501 let mode: String =
5502 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5503 row.get(0)
5504 })?;
5505 assert_eq!(mode, "delete");
5506 db.conn.close().expect("Close didn't work");
5507
5508 KeystoreDB::set_wal_mode(temp_dir.path())?;
5509
5510 db = KeystoreDB::new(temp_dir.path(), None)?;
5511 let mode: String =
5512 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5513 row.get(0)
5514 })?;
5515 assert_eq!(mode, "wal");
5516 Ok(())
5517 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005518}