blob: 84eb9877c2e6567a534d208ad5bf04e48747a5c3 [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;
Janis Danisevskisa0648e02021-05-26 11:15:30 -070045pub(crate) mod utils;
Janis Danisevskis97c83872021-05-26 16:31:02 -070046mod versioning;
Matthew Maurerd7815ca2021-05-06 21:58:45 -070047
Janis Danisevskisb42fc182020-12-15 08:41:27 -080048use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080049use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070050use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000051use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080052use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070053 error::{Error as KsError, ErrorCode, ResponseCode},
54 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080055};
Janis Danisevskisa0648e02021-05-26 11:15:30 -070056use crate::{gc::Gc, super_key::USER_SUPER_KEY};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080057use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080058use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskisa0648e02021-05-26 11:15:30 -070059use utils as db_utils;
60use utils::SqlField;
Janis Danisevskis60400fe2020-08-26 15:24:42 -070061
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080063 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080065};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070066use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070067 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070068};
Max Bires2b2e6562020-09-22 11:22:36 -070069use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
70 AttestationPoolStatus::AttestationPoolStatus,
71};
Seth Moore78c091f2021-04-09 21:38:30 +000072use statslog_rust::keystore2_storage_stats::{
73 Keystore2StorageStats, StorageType as StatsdStorageType,
74};
Max Bires2b2e6562020-09-22 11:22:36 -070075
76use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080077use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000078use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070079#[cfg(not(test))]
80use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070081use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080082 params,
83 types::FromSql,
84 types::FromSqlResult,
85 types::ToSqlOutput,
86 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080087 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070088};
Max Bires2b2e6562020-09-22 11:22:36 -070089
Janis Danisevskisaec14592020-11-12 09:41:49 -080090use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080091 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080092 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070093 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080095};
Max Bires2b2e6562020-09-22 11:22:36 -070096
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800100impl_metadata!(
101 /// A set of metadata for key entries.
102 #[derive(Debug, Default, Eq, PartialEq)]
103 pub struct KeyMetaData;
104 /// A metadata entry for key entries.
105 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
106 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800107 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800108 CreationDate(DateTime) with accessor creation_date,
109 /// Expiration date for attestation keys.
110 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700111 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
112 /// provisioning
113 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
114 /// Vector representing the raw public key so results from the server can be matched
115 /// to the right entry
116 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700117 /// SEC1 public key for ECDH encryption
118 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800119 // --- ADD NEW META DATA FIELDS HERE ---
120 // For backwards compatibility add new entries only to
121 // end of this list and above this comment.
122 };
123);
124
125impl KeyMetaData {
126 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
127 let mut stmt = tx
128 .prepare(
129 "SELECT tag, data from persistent.keymetadata
130 WHERE keyentryid = ?;",
131 )
132 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
133
134 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
135
136 let mut rows =
137 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
138 db_utils::with_rows_extract_all(&mut rows, |row| {
139 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
140 metadata.insert(
141 db_tag,
142 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
143 .context("Failed to read KeyMetaEntry.")?,
144 );
145 Ok(())
146 })
147 .context("In KeyMetaData::load_from_db.")?;
148
149 Ok(Self { data: metadata })
150 }
151
152 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
153 let mut stmt = tx
154 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000155 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800156 VALUES (?, ?, ?);",
157 )
158 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
159
160 let iter = self.data.iter();
161 for (tag, entry) in iter {
162 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
163 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
164 })?;
165 }
166 Ok(())
167 }
168}
169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170impl_metadata!(
171 /// A set of metadata for key blobs.
172 #[derive(Debug, Default, Eq, PartialEq)]
173 pub struct BlobMetaData;
174 /// A metadata entry for key blobs.
175 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
176 pub enum BlobMetaEntry {
177 /// If present, indicates that the blob is encrypted with another key or a key derived
178 /// from a password.
179 EncryptedBy(EncryptedBy) with accessor encrypted_by,
180 /// If the blob is password encrypted this field is set to the
181 /// salt used for the key derivation.
182 Salt(Vec<u8>) with accessor salt,
183 /// If the blob is encrypted, this field is set to the initialization vector.
184 Iv(Vec<u8>) with accessor iv,
185 /// If the blob is encrypted, this field holds the AEAD TAG.
186 AeadTag(Vec<u8>) with accessor aead_tag,
187 /// The uuid of the owning KeyMint instance.
188 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700189 /// If the key is ECDH encrypted, this is the ephemeral public key
190 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000191 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
192 /// of that key
193 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800194 // --- ADD NEW META DATA FIELDS HERE ---
195 // For backwards compatibility add new entries only to
196 // end of this list and above this comment.
197 };
198);
199
200impl BlobMetaData {
201 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
202 let mut stmt = tx
203 .prepare(
204 "SELECT tag, data from persistent.blobmetadata
205 WHERE blobentryid = ?;",
206 )
207 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
208
209 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
210
211 let mut rows =
212 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
213 db_utils::with_rows_extract_all(&mut rows, |row| {
214 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
215 metadata.insert(
216 db_tag,
217 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
218 .context("Failed to read BlobMetaEntry.")?,
219 );
220 Ok(())
221 })
222 .context("In BlobMetaData::load_from_db.")?;
223
224 Ok(Self { data: metadata })
225 }
226
227 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
228 let mut stmt = tx
229 .prepare(
230 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
231 VALUES (?, ?, ?);",
232 )
233 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
234
235 let iter = self.data.iter();
236 for (tag, entry) in iter {
237 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
238 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
239 })?;
240 }
241 Ok(())
242 }
243}
244
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800245/// Indicates the type of the keyentry.
246#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
247pub enum KeyType {
248 /// This is a client key type. These keys are created or imported through the Keystore 2.0
249 /// AIDL interface android.system.keystore2.
250 Client,
251 /// This is a super key type. These keys are created by keystore itself and used to encrypt
252 /// other key blobs to provide LSKF binding.
253 Super,
254 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
255 Attestation,
256}
257
258impl ToSql for KeyType {
259 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
260 Ok(ToSqlOutput::Owned(Value::Integer(match self {
261 KeyType::Client => 0,
262 KeyType::Super => 1,
263 KeyType::Attestation => 2,
264 })))
265 }
266}
267
268impl FromSql for KeyType {
269 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
270 match i64::column_result(value)? {
271 0 => Ok(KeyType::Client),
272 1 => Ok(KeyType::Super),
273 2 => Ok(KeyType::Attestation),
274 v => Err(FromSqlError::OutOfRange(v)),
275 }
276 }
277}
278
Max Bires8e93d2b2021-01-14 13:17:59 -0800279/// Uuid representation that can be stored in the database.
280/// Right now it can only be initialized from SecurityLevel.
281/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
282#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
283pub struct Uuid([u8; 16]);
284
285impl Deref for Uuid {
286 type Target = [u8; 16];
287
288 fn deref(&self) -> &Self::Target {
289 &self.0
290 }
291}
292
293impl From<SecurityLevel> for Uuid {
294 fn from(sec_level: SecurityLevel) -> Self {
295 Self((sec_level.0 as u128).to_be_bytes())
296 }
297}
298
299impl ToSql for Uuid {
300 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
301 self.0.to_sql()
302 }
303}
304
305impl FromSql for Uuid {
306 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
307 let blob = Vec::<u8>::column_result(value)?;
308 if blob.len() != 16 {
309 return Err(FromSqlError::OutOfRange(blob.len() as i64));
310 }
311 let mut arr = [0u8; 16];
312 arr.copy_from_slice(&blob);
313 Ok(Self(arr))
314 }
315}
316
317/// Key entries that are not associated with any KeyMint instance, such as pure certificate
318/// entries are associated with this UUID.
319pub static KEYSTORE_UUID: Uuid = Uuid([
320 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
321]);
322
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800323/// Indicates how the sensitive part of this key blob is encrypted.
324#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
325pub enum EncryptedBy {
326 /// The keyblob is encrypted by a user password.
327 /// In the database this variant is represented as NULL.
328 Password,
329 /// The keyblob is encrypted by another key with wrapped key id.
330 /// In the database this variant is represented as non NULL value
331 /// that is convertible to i64, typically NUMERIC.
332 KeyId(i64),
333}
334
335impl ToSql for EncryptedBy {
336 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
337 match self {
338 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
339 Self::KeyId(id) => id.to_sql(),
340 }
341 }
342}
343
344impl FromSql for EncryptedBy {
345 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
346 match value {
347 ValueRef::Null => Ok(Self::Password),
348 _ => Ok(Self::KeyId(i64::column_result(value)?)),
349 }
350 }
351}
352
353/// A database representation of wall clock time. DateTime stores unix epoch time as
354/// i64 in milliseconds.
355#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
356pub struct DateTime(i64);
357
358/// Error type returned when creating DateTime or converting it from and to
359/// SystemTime.
360#[derive(thiserror::Error, Debug)]
361pub enum DateTimeError {
362 /// This is returned when SystemTime and Duration computations fail.
363 #[error(transparent)]
364 SystemTimeError(#[from] SystemTimeError),
365
366 /// This is returned when type conversions fail.
367 #[error(transparent)]
368 TypeConversion(#[from] std::num::TryFromIntError),
369
370 /// This is returned when checked time arithmetic failed.
371 #[error("Time arithmetic failed.")]
372 TimeArithmetic,
373}
374
375impl DateTime {
376 /// Constructs a new DateTime object denoting the current time. This may fail during
377 /// conversion to unix epoch time and during conversion to the internal i64 representation.
378 pub fn now() -> Result<Self, DateTimeError> {
379 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
380 }
381
382 /// Constructs a new DateTime object from milliseconds.
383 pub fn from_millis_epoch(millis: i64) -> Self {
384 Self(millis)
385 }
386
387 /// Returns unix epoch time in milliseconds.
388 pub fn to_millis_epoch(&self) -> i64 {
389 self.0
390 }
391
392 /// Returns unix epoch time in seconds.
393 pub fn to_secs_epoch(&self) -> i64 {
394 self.0 / 1000
395 }
396}
397
398impl ToSql for DateTime {
399 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
400 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
401 }
402}
403
404impl FromSql for DateTime {
405 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
406 Ok(Self(i64::column_result(value)?))
407 }
408}
409
410impl TryInto<SystemTime> for DateTime {
411 type Error = DateTimeError;
412
413 fn try_into(self) -> Result<SystemTime, Self::Error> {
414 // We want to construct a SystemTime representation equivalent to self, denoting
415 // a point in time THEN, but we cannot set the time directly. We can only construct
416 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
417 // and between EPOCH and THEN. With this common reference we can construct the
418 // duration between NOW and THEN which we can add to our SystemTime representation
419 // of NOW to get a SystemTime representation of THEN.
420 // Durations can only be positive, thus the if statement below.
421 let now = SystemTime::now();
422 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
423 let then_epoch = Duration::from_millis(self.0.try_into()?);
424 Ok(if now_epoch > then_epoch {
425 // then = now - (now_epoch - then_epoch)
426 now_epoch
427 .checked_sub(then_epoch)
428 .and_then(|d| now.checked_sub(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 } else {
431 // then = now + (then_epoch - now_epoch)
432 then_epoch
433 .checked_sub(now_epoch)
434 .and_then(|d| now.checked_add(d))
435 .ok_or(DateTimeError::TimeArithmetic)?
436 })
437 }
438}
439
440impl TryFrom<SystemTime> for DateTime {
441 type Error = DateTimeError;
442
443 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
444 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
445 }
446}
447
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800448#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
449enum KeyLifeCycle {
450 /// Existing keys have a key ID but are not fully populated yet.
451 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
452 /// them to Unreferenced for garbage collection.
453 Existing,
454 /// A live key is fully populated and usable by clients.
455 Live,
456 /// An unreferenced key is scheduled for garbage collection.
457 Unreferenced,
458}
459
460impl ToSql for KeyLifeCycle {
461 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
462 match self {
463 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
464 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
465 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
466 }
467 }
468}
469
470impl FromSql for KeyLifeCycle {
471 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
472 match i64::column_result(value)? {
473 0 => Ok(KeyLifeCycle::Existing),
474 1 => Ok(KeyLifeCycle::Live),
475 2 => Ok(KeyLifeCycle::Unreferenced),
476 v => Err(FromSqlError::OutOfRange(v)),
477 }
478 }
479}
480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700481/// Keys have a KeyMint blob component and optional public certificate and
482/// certificate chain components.
483/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
484/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800485#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700486pub struct KeyEntryLoadBits(u32);
487
488impl KeyEntryLoadBits {
489 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
490 pub const NONE: KeyEntryLoadBits = Self(0);
491 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
492 pub const KM: KeyEntryLoadBits = Self(1);
493 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
494 pub const PUBLIC: KeyEntryLoadBits = Self(2);
495 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
496 pub const BOTH: KeyEntryLoadBits = Self(3);
497
498 /// Returns true if this object indicates that the public components shall be loaded.
499 pub const fn load_public(&self) -> bool {
500 self.0 & Self::PUBLIC.0 != 0
501 }
502
503 /// Returns true if the object indicates that the KeyMint component shall be loaded.
504 pub const fn load_km(&self) -> bool {
505 self.0 & Self::KM.0 != 0
506 }
507}
508
Janis Danisevskisaec14592020-11-12 09:41:49 -0800509lazy_static! {
510 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
511}
512
513struct KeyIdLockDb {
514 locked_keys: Mutex<HashSet<i64>>,
515 cond_var: Condvar,
516}
517
518/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
519/// from the database a second time. Most functions manipulating the key blob database
520/// require a KeyIdGuard.
521#[derive(Debug)]
522pub struct KeyIdGuard(i64);
523
524impl KeyIdLockDb {
525 fn new() -> Self {
526 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
527 }
528
529 /// This function blocks until an exclusive lock for the given key entry id can
530 /// be acquired. It returns a guard object, that represents the lifecycle of the
531 /// acquired lock.
532 pub fn get(&self, key_id: i64) -> KeyIdGuard {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 while locked_keys.contains(&key_id) {
535 locked_keys = self.cond_var.wait(locked_keys).unwrap();
536 }
537 locked_keys.insert(key_id);
538 KeyIdGuard(key_id)
539 }
540
541 /// This function attempts to acquire an exclusive lock on a given key id. If the
542 /// given key id is already taken the function returns None immediately. If a lock
543 /// can be acquired this function returns a guard object, that represents the
544 /// lifecycle of the acquired lock.
545 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
546 let mut locked_keys = self.locked_keys.lock().unwrap();
547 if locked_keys.insert(key_id) {
548 Some(KeyIdGuard(key_id))
549 } else {
550 None
551 }
552 }
553}
554
555impl KeyIdGuard {
556 /// Get the numeric key id of the locked key.
557 pub fn id(&self) -> i64 {
558 self.0
559 }
560}
561
562impl Drop for KeyIdGuard {
563 fn drop(&mut self) {
564 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
565 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800566 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800567 KEY_ID_LOCK.cond_var.notify_all();
568 }
569}
570
Max Bires8e93d2b2021-01-14 13:17:59 -0800571/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700572#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800573pub struct CertificateInfo {
574 cert: Option<Vec<u8>>,
575 cert_chain: Option<Vec<u8>>,
576}
577
578impl CertificateInfo {
579 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
580 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
581 Self { cert, cert_chain }
582 }
583
584 /// Take the cert
585 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
586 self.cert.take()
587 }
588
589 /// Take the cert chain
590 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
591 self.cert_chain.take()
592 }
593}
594
Max Bires2b2e6562020-09-22 11:22:36 -0700595/// This type represents a certificate chain with a private key corresponding to the leaf
596/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
Max Bires2b2e6562020-09-22 11:22:36 -0700597pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800598 /// A KM key blob
599 pub private_key: ZVec,
600 /// A batch cert for private_key
601 pub batch_cert: Vec<u8>,
602 /// A full certificate chain from root signing authority to private_key, including batch_cert
603 /// for convenience.
604 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700605}
606
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700607/// This type represents a Keystore 2.0 key entry.
608/// An entry has a unique `id` by which it can be found in the database.
609/// It has a security level field, key parameters, and three optional fields
610/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800611#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700612pub struct KeyEntry {
613 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800614 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615 cert: Option<Vec<u8>>,
616 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800617 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700618 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800619 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800620 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700621}
622
623impl KeyEntry {
624 /// Returns the unique id of the Key entry.
625 pub fn id(&self) -> i64 {
626 self.id
627 }
628 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800629 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
630 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 /// Extracts the Optional KeyMint blob including its metadata.
633 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
634 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700635 }
636 /// Exposes the optional public certificate.
637 pub fn cert(&self) -> &Option<Vec<u8>> {
638 &self.cert
639 }
640 /// Extracts the optional public certificate.
641 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
642 self.cert.take()
643 }
644 /// Exposes the optional public certificate chain.
645 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
646 &self.cert_chain
647 }
648 /// Extracts the optional public certificate_chain.
649 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
650 self.cert_chain.take()
651 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800652 /// Returns the uuid of the owning KeyMint instance.
653 pub fn km_uuid(&self) -> &Uuid {
654 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700656 /// Exposes the key parameters of this key entry.
657 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
658 &self.parameters
659 }
660 /// Consumes this key entry and extracts the keyparameters from it.
661 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
662 self.parameters
663 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800664 /// Exposes the key metadata of this key entry.
665 pub fn metadata(&self) -> &KeyMetaData {
666 &self.metadata
667 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800668 /// This returns true if the entry is a pure certificate entry with no
669 /// private key component.
670 pub fn pure_cert(&self) -> bool {
671 self.pure_cert
672 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000673 /// Consumes this key entry and extracts the keyparameters and metadata from it.
674 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
675 (self.parameters, self.metadata)
676 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700677}
678
679/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800680#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681pub struct SubComponentType(u32);
682impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800683 /// Persistent identifier for a key blob.
684 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700685 /// Persistent identifier for a certificate blob.
686 pub const CERT: SubComponentType = Self(1);
687 /// Persistent identifier for a certificate chain blob.
688 pub const CERT_CHAIN: SubComponentType = Self(2);
689}
690
691impl ToSql for SubComponentType {
692 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
693 self.0.to_sql()
694 }
695}
696
697impl FromSql for SubComponentType {
698 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
699 Ok(Self(u32::column_result(value)?))
700 }
701}
702
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800703/// This trait is private to the database module. It is used to convey whether or not the garbage
704/// collector shall be invoked after a database access. All closures passed to
705/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
706/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
707/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
708/// `.need_gc()`.
709trait DoGc<T> {
710 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
711
712 fn no_gc(self) -> Result<(bool, T)>;
713
714 fn need_gc(self) -> Result<(bool, T)>;
715}
716
717impl<T> DoGc<T> for Result<T> {
718 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
719 self.map(|r| (need_gc, r))
720 }
721
722 fn no_gc(self) -> Result<(bool, T)> {
723 self.do_gc(false)
724 }
725
726 fn need_gc(self) -> Result<(bool, T)> {
727 self.do_gc(true)
728 }
729}
730
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700731/// KeystoreDB wraps a connection to an SQLite database and tracks its
732/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700733pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700734 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700735 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700736 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700737}
738
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000739/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000741#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
742pub struct MonotonicRawTime(i64);
743
744impl MonotonicRawTime {
745 /// Constructs a new MonotonicRawTime
746 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000747 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000748 }
749
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000750 /// Returns the value of MonotonicRawTime in milliseconds as i64
751 pub fn milliseconds(&self) -> i64 {
752 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000757 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000758 }
759
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800760 /// Like i64::checked_sub.
761 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
762 self.0.checked_sub(other.0).map(Self)
763 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000764}
765
766impl ToSql for MonotonicRawTime {
767 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
768 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
769 }
770}
771
772impl FromSql for MonotonicRawTime {
773 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
774 Ok(Self(i64::column_result(value)?))
775 }
776}
777
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000778/// This struct encapsulates the information to be stored in the database about the auth tokens
779/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700780#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000781pub struct AuthTokenEntry {
782 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000783 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000784 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000785}
786
787impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000789 AuthTokenEntry { auth_token, time_received }
790 }
791
792 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800793 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000794 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800795 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
796 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 })
798 }
799
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800801 pub fn auth_token(&self) -> &HardwareAuthToken {
802 &self.auth_token
803 }
804
805 /// Returns the auth token wrapped by the AuthTokenEntry
806 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000807 self.auth_token
808 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800809
810 /// Returns the time that this auth token was received.
811 pub fn time_received(&self) -> MonotonicRawTime {
812 self.time_received
813 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000814
815 /// Returns the challenge value of the auth token.
816 pub fn challenge(&self) -> i64 {
817 self.auth_token.challenge
818 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000819}
820
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800821/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
822/// This object does not allow access to the database connection. But it keeps a database
823/// connection alive in order to keep the in memory per boot database alive.
824pub struct PerBootDbKeepAlive(Connection);
825
Joel Galenson26f4d012020-07-17 14:57:21 -0700826impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800827 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskis97c83872021-05-26 16:31:02 -0700828 const CURRENT_DB_VERSION: u32 = 1;
829 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800830
Seth Moore78c091f2021-04-09 21:38:30 +0000831 /// Name of the file that holds the cross-boot persistent database.
832 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
833
Seth Moore472fcbb2021-05-12 10:07:51 -0700834 /// Set write-ahead logging mode on the persistent database found in `db_root`.
835 pub fn set_wal_mode(db_root: &Path) -> Result<()> {
836 let path = Self::make_persistent_path(&db_root)?;
837 let conn =
838 Connection::open(path).context("In KeystoreDB::set_wal_mode: Failed to open DB")?;
839 let mode: String = conn
840 .pragma_update_and_check(None, "journal_mode", &"WAL", |row| row.get(0))
841 .context("In KeystoreDB::set_wal_mode: Failed to set journal_mode")?;
842 match mode.as_str() {
843 "wal" => Ok(()),
844 _ => Err(anyhow!("Unable to set WAL mode, db is still in {} mode.", mode)),
845 }
846 }
847
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700848 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800849 /// files persistent.sqlite and perboot.sqlite in the given directory.
850 /// It also attempts to initialize all of the tables.
851 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700852 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700853 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700854 let _wp = wd::watch_millis("KeystoreDB::new", 500);
855
Seth Moore472fcbb2021-05-12 10:07:51 -0700856 let persistent_path = Self::make_persistent_path(&db_root)?;
857 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800858
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700859 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800860 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis97c83872021-05-26 16:31:02 -0700861 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
862 .context("In KeystoreDB::new: trying to upgrade database.")?;
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 Danisevskis97c83872021-05-26 16:31:02 -0700868 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
869 // cryptographic binding to the boot level keys was implemented.
870 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
871 tx.execute(
872 "UPDATE persistent.keyentry SET state = ?
873 WHERE
874 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
875 AND
876 id NOT IN (
877 SELECT keyentryid FROM persistent.blobentry
878 WHERE id IN (
879 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
880 )
881 );",
882 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
883 )
884 .context("In from_0_to_1: Failed to delete logical boot level keys.")?;
885 Ok(1)
886 }
887
Janis Danisevskis66784c42021-01-27 08:40:25 -0800888 fn init_tables(tx: &Transaction) -> Result<()> {
889 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700890 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700891 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800892 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700893 domain INTEGER,
894 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800895 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800896 state INTEGER,
897 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700898 NO_PARAMS,
899 )
900 .context("Failed to initialize \"keyentry\" table.")?;
901
Janis Danisevskis66784c42021-01-27 08:40:25 -0800902 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800903 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
904 ON keyentry(id);",
905 NO_PARAMS,
906 )
907 .context("Failed to create index keyentry_id_index.")?;
908
909 tx.execute(
910 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
911 ON keyentry(domain, namespace, alias);",
912 NO_PARAMS,
913 )
914 .context("Failed to create index keyentry_domain_namespace_index.")?;
915
916 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700917 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
918 id INTEGER PRIMARY KEY,
919 subcomponent_type INTEGER,
920 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800921 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700922 NO_PARAMS,
923 )
924 .context("Failed to initialize \"blobentry\" table.")?;
925
Janis Danisevskis66784c42021-01-27 08:40:25 -0800926 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800927 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
928 ON blobentry(keyentryid);",
929 NO_PARAMS,
930 )
931 .context("Failed to create index blobentry_keyentryid_index.")?;
932
933 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800934 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
935 id INTEGER PRIMARY KEY,
936 blobentryid INTEGER,
937 tag INTEGER,
938 data ANY,
939 UNIQUE (blobentryid, tag));",
940 NO_PARAMS,
941 )
942 .context("Failed to initialize \"blobmetadata\" table.")?;
943
944 tx.execute(
945 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
946 ON blobmetadata(blobentryid);",
947 NO_PARAMS,
948 )
949 .context("Failed to create index blobmetadata_blobentryid_index.")?;
950
951 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700952 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000953 keyentryid INTEGER,
954 tag INTEGER,
955 data ANY,
956 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700957 NO_PARAMS,
958 )
959 .context("Failed to initialize \"keyparameter\" table.")?;
960
Janis Danisevskis66784c42021-01-27 08:40:25 -0800961 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800962 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
963 ON keyparameter(keyentryid);",
964 NO_PARAMS,
965 )
966 .context("Failed to create index keyparameter_keyentryid_index.")?;
967
968 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800969 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
970 keyentryid INTEGER,
971 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000972 data ANY,
973 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800974 NO_PARAMS,
975 )
976 .context("Failed to initialize \"keymetadata\" table.")?;
977
Janis Danisevskis66784c42021-01-27 08:40:25 -0800978 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800979 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
980 ON keymetadata(keyentryid);",
981 NO_PARAMS,
982 )
983 .context("Failed to create index keymetadata_keyentryid_index.")?;
984
985 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800986 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700987 id INTEGER UNIQUE,
988 grantee INTEGER,
989 keyentryid INTEGER,
990 access_vector INTEGER);",
991 NO_PARAMS,
992 )
993 .context("Failed to initialize \"grant\" table.")?;
994
Joel Galenson0891bc12020-07-20 10:37:03 -0700995 Ok(())
996 }
997
Seth Moore472fcbb2021-05-12 10:07:51 -0700998 fn make_persistent_path(db_root: &Path) -> Result<String> {
999 // Build the path to the sqlite file.
1000 let mut persistent_path = db_root.to_path_buf();
1001 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1002
1003 // Now convert them to strings prefixed with "file:"
1004 let mut persistent_path_str = "file:".to_owned();
1005 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1006
1007 Ok(persistent_path_str)
1008 }
1009
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001010 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001011 let conn =
1012 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1013
Janis Danisevskis66784c42021-01-27 08:40:25 -08001014 loop {
1015 if let Err(e) = conn
1016 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1017 .context("Failed to attach database persistent.")
1018 {
1019 if Self::is_locked_error(&e) {
1020 std::thread::sleep(std::time::Duration::from_micros(500));
1021 continue;
1022 } else {
1023 return Err(e);
1024 }
1025 }
1026 break;
1027 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001028
Matthew Maurer4fb19112021-05-06 15:40:44 -07001029 // Drop the cache size from default (2M) to 0.5M
1030 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1031 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001032
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001033 Ok(conn)
1034 }
1035
Seth Moore78c091f2021-04-09 21:38:30 +00001036 fn do_table_size_query(
1037 &mut self,
1038 storage_type: StatsdStorageType,
1039 query: &str,
1040 params: &[&str],
1041 ) -> Result<Keystore2StorageStats> {
1042 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1043 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1044 .with_context(|| {
1045 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1046 })
1047 .no_gc()
1048 })?;
1049 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1050 }
1051
1052 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1053 self.do_table_size_query(
1054 StatsdStorageType::Database,
1055 "SELECT page_count * page_size, freelist_count * page_size
1056 FROM pragma_page_count('persistent'),
1057 pragma_page_size('persistent'),
1058 persistent.pragma_freelist_count();",
1059 &[],
1060 )
1061 }
1062
1063 fn get_table_size(
1064 &mut self,
1065 storage_type: StatsdStorageType,
1066 schema: &str,
1067 table: &str,
1068 ) -> Result<Keystore2StorageStats> {
1069 self.do_table_size_query(
1070 storage_type,
1071 "SELECT pgsize,unused FROM dbstat(?1)
1072 WHERE name=?2 AND aggregate=TRUE;",
1073 &[schema, table],
1074 )
1075 }
1076
1077 /// Fetches a storage statisitics atom for a given storage type. For storage
1078 /// types that map to a table, information about the table's storage is
1079 /// returned. Requests for storage types that are not DB tables return None.
1080 pub fn get_storage_stat(
1081 &mut self,
1082 storage_type: StatsdStorageType,
1083 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001084 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1085
Seth Moore78c091f2021-04-09 21:38:30 +00001086 match storage_type {
1087 StatsdStorageType::Database => self.get_total_size(),
1088 StatsdStorageType::KeyEntry => {
1089 self.get_table_size(storage_type, "persistent", "keyentry")
1090 }
1091 StatsdStorageType::KeyEntryIdIndex => {
1092 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1093 }
1094 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1095 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1096 }
1097 StatsdStorageType::BlobEntry => {
1098 self.get_table_size(storage_type, "persistent", "blobentry")
1099 }
1100 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1101 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1102 }
1103 StatsdStorageType::KeyParameter => {
1104 self.get_table_size(storage_type, "persistent", "keyparameter")
1105 }
1106 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1107 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1108 }
1109 StatsdStorageType::KeyMetadata => {
1110 self.get_table_size(storage_type, "persistent", "keymetadata")
1111 }
1112 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1113 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1114 }
1115 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1116 StatsdStorageType::AuthToken => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001117 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1118 // reportable
1119 // Size provided is only an approximation
1120 Ok(Keystore2StorageStats {
1121 storage_type,
1122 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1123 as i64,
1124 unused_size: 0,
1125 })
Seth Moore78c091f2021-04-09 21:38:30 +00001126 }
1127 StatsdStorageType::BlobMetadata => {
1128 self.get_table_size(storage_type, "persistent", "blobmetadata")
1129 }
1130 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1131 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1132 }
1133 _ => Err(anyhow::Error::msg(format!(
1134 "Unsupported storage type: {}",
1135 storage_type as i32
1136 ))),
1137 }
1138 }
1139
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001140 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001141 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1142 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001143 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1144 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001145 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001146 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001147 blob_ids_to_delete: &[i64],
1148 max_blobs: usize,
1149 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001150 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001151 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001152 // Delete the given blobs.
1153 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001154 tx.execute(
1155 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001156 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001157 )
1158 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001159 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1160 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001161 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001162
1163 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1164
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1166 let result: Vec<(i64, Vec<u8>)> = {
1167 let mut stmt = tx
1168 .prepare(
1169 "SELECT id, blob FROM persistent.blobentry
1170 WHERE subcomponent_type = ?
1171 AND (
1172 id NOT IN (
1173 SELECT MAX(id) FROM persistent.blobentry
1174 WHERE subcomponent_type = ?
1175 GROUP BY keyentryid, subcomponent_type
1176 )
1177 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1178 ) LIMIT ?;",
1179 )
1180 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001181
Janis Danisevskis3395f862021-05-06 10:54:17 -07001182 let rows = stmt
1183 .query_map(
1184 params![
1185 SubComponentType::KEY_BLOB,
1186 SubComponentType::KEY_BLOB,
1187 max_blobs as i64,
1188 ],
1189 |row| Ok((row.get(0)?, row.get(1)?)),
1190 )
1191 .context("Trying to query superseded blob.")?;
1192
1193 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1194 .context("Trying to extract superseded blobs.")?
1195 };
1196
1197 let result = result
1198 .into_iter()
1199 .map(|(blob_id, blob)| {
1200 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1201 })
1202 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1203 .context("Trying to load blob metadata.")?;
1204 if !result.is_empty() {
1205 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001206 }
1207
1208 // We did not find any superseded key blob, so let's remove other superseded blob in
1209 // one transaction.
1210 tx.execute(
1211 "DELETE FROM persistent.blobentry
1212 WHERE NOT subcomponent_type = ?
1213 AND (
1214 id NOT IN (
1215 SELECT MAX(id) FROM persistent.blobentry
1216 WHERE NOT subcomponent_type = ?
1217 GROUP BY keyentryid, subcomponent_type
1218 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1219 );",
1220 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1221 )
1222 .context("Trying to purge superseded blobs.")?;
1223
Janis Danisevskis3395f862021-05-06 10:54:17 -07001224 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001225 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001226 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001227 }
1228
1229 /// This maintenance function should be called only once before the database is used for the
1230 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1231 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1232 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1233 /// Keystore crashed at some point during key generation. Callers may want to log such
1234 /// occurrences.
1235 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1236 /// it to `KeyLifeCycle::Live` may have grants.
1237 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001238 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1239
Janis Danisevskis66784c42021-01-27 08:40:25 -08001240 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1241 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001242 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1243 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1244 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001245 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001246 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001247 })
1248 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001249 }
1250
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001251 /// Checks if a key exists with given key type and key descriptor properties.
1252 pub fn key_exists(
1253 &mut self,
1254 domain: Domain,
1255 nspace: i64,
1256 alias: &str,
1257 key_type: KeyType,
1258 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001259 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1260
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001261 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1262 let key_descriptor =
1263 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1264 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1265 match result {
1266 Ok(_) => Ok(true),
1267 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1268 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1269 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1270 },
1271 }
1272 .no_gc()
1273 })
1274 .context("In key_exists.")
1275 }
1276
Hasini Gunasingheda895552021-01-27 19:34:37 +00001277 /// Stores a super key in the database.
1278 pub fn store_super_key(
1279 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001280 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001281 key_type: &SuperKeyType,
1282 blob: &[u8],
1283 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001284 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001285 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001286 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1287
Hasini Gunasingheda895552021-01-27 19:34:37 +00001288 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1289 let key_id = Self::insert_with_retry(|id| {
1290 tx.execute(
1291 "INSERT into persistent.keyentry
1292 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001293 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001294 params![
1295 id,
1296 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001297 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001298 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001299 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001300 KeyLifeCycle::Live,
1301 &KEYSTORE_UUID,
1302 ],
1303 )
1304 })
1305 .context("Failed to insert into keyentry table.")?;
1306
Paul Crowley8d5b2532021-03-19 10:53:07 -07001307 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1308
Hasini Gunasingheda895552021-01-27 19:34:37 +00001309 Self::set_blob_internal(
1310 &tx,
1311 key_id,
1312 SubComponentType::KEY_BLOB,
1313 Some(blob),
1314 Some(blob_metadata),
1315 )
1316 .context("Failed to store key blob.")?;
1317
1318 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1319 .context("Trying to load key components.")
1320 .no_gc()
1321 })
1322 .context("In store_super_key.")
1323 }
1324
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001325 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001326 pub fn load_super_key(
1327 &mut self,
1328 key_type: &SuperKeyType,
1329 user_id: u32,
1330 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001331 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1332
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001333 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1334 let key_descriptor = KeyDescriptor {
1335 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001336 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001337 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001338 blob: None,
1339 };
1340 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1341 match id {
1342 Ok(id) => {
1343 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1344 .context("In load_super_key. Failed to load key entry.")?;
1345 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1346 }
1347 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1348 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1349 _ => Err(error).context("In load_super_key."),
1350 },
1351 }
1352 .no_gc()
1353 })
1354 .context("In load_super_key.")
1355 }
1356
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001357 /// Atomically loads a key entry and associated metadata or creates it using the
1358 /// callback create_new_key callback. The callback is called during a database
1359 /// transaction. This means that implementers should be mindful about using
1360 /// blocking operations such as IPC or grabbing mutexes.
1361 pub fn get_or_create_key_with<F>(
1362 &mut self,
1363 domain: Domain,
1364 namespace: i64,
1365 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001366 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001367 create_new_key: F,
1368 ) -> Result<(KeyIdGuard, KeyEntry)>
1369 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001370 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001371 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001372 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1373
Janis Danisevskis66784c42021-01-27 08:40:25 -08001374 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1375 let id = {
1376 let mut stmt = tx
1377 .prepare(
1378 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001379 WHERE
1380 key_type = ?
1381 AND domain = ?
1382 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001383 AND alias = ?
1384 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001385 )
1386 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1387 let mut rows = stmt
1388 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1389 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001390
Janis Danisevskis66784c42021-01-27 08:40:25 -08001391 db_utils::with_rows_extract_one(&mut rows, |row| {
1392 Ok(match row {
1393 Some(r) => r.get(0).context("Failed to unpack id.")?,
1394 None => None,
1395 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001396 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001397 .context("In get_or_create_key_with.")?
1398 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001399
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 let (id, entry) = match id {
1401 Some(id) => (
1402 id,
1403 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1404 .context("In get_or_create_key_with.")?,
1405 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001406
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 None => {
1408 let id = Self::insert_with_retry(|id| {
1409 tx.execute(
1410 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001411 (id, key_type, domain, namespace, alias, state, km_uuid)
1412 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 params![
1414 id,
1415 KeyType::Super,
1416 domain.0,
1417 namespace,
1418 alias,
1419 KeyLifeCycle::Live,
1420 km_uuid,
1421 ],
1422 )
1423 })
1424 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001425
Janis Danisevskis66784c42021-01-27 08:40:25 -08001426 let (blob, metadata) =
1427 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001428 Self::set_blob_internal(
1429 &tx,
1430 id,
1431 SubComponentType::KEY_BLOB,
1432 Some(&blob),
1433 Some(&metadata),
1434 )
Paul Crowley7a658392021-03-18 17:08:20 -07001435 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001436 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001437 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001438 KeyEntry {
1439 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001440 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001441 pure_cert: false,
1442 ..Default::default()
1443 },
1444 )
1445 }
1446 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001447 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001448 })
1449 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001450 }
1451
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001452 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001453 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1454 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001455 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1456 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001457 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001458 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001459 loop {
1460 match self
1461 .conn
1462 .transaction_with_behavior(behavior)
1463 .context("In with_transaction.")
1464 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1465 .and_then(|(result, tx)| {
1466 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1467 Ok(result)
1468 }) {
1469 Ok(result) => break Ok(result),
1470 Err(e) => {
1471 if Self::is_locked_error(&e) {
1472 std::thread::sleep(std::time::Duration::from_micros(500));
1473 continue;
1474 } else {
1475 return Err(e).context("In with_transaction.");
1476 }
1477 }
1478 }
1479 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001480 .map(|(need_gc, result)| {
1481 if need_gc {
1482 if let Some(ref gc) = self.gc {
1483 gc.notify_gc();
1484 }
1485 }
1486 result
1487 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001488 }
1489
1490 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001491 matches!(
1492 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1493 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1494 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1495 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001496 }
1497
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001498 /// Creates a new key entry and allocates a new randomized id for the new key.
1499 /// The key id gets associated with a domain and namespace but not with an alias.
1500 /// To complete key generation `rebind_alias` should be called after all of the
1501 /// key artifacts, i.e., blobs and parameters have been associated with the new
1502 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1503 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001504 pub fn create_key_entry(
1505 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001506 domain: &Domain,
1507 namespace: &i64,
Janis Danisevskis10b79f52021-05-25 11:07:10 -07001508 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001509 km_uuid: &Uuid,
1510 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001511 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1512
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001513 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis10b79f52021-05-25 11:07:10 -07001514 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001515 })
1516 .context("In create_key_entry.")
1517 }
1518
1519 fn create_key_entry_internal(
1520 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001521 domain: &Domain,
1522 namespace: &i64,
Janis Danisevskis10b79f52021-05-25 11:07:10 -07001523 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001524 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001526 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001527 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001528 _ => {
1529 return Err(KsError::sys())
1530 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1531 }
1532 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001533 Ok(KEY_ID_LOCK.get(
1534 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001535 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001536 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001537 (id, key_type, domain, namespace, alias, state, km_uuid)
1538 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001539 params![
1540 id,
Janis Danisevskis10b79f52021-05-25 11:07:10 -07001541 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001542 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001543 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001544 KeyLifeCycle::Existing,
1545 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001546 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001547 )
1548 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001549 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001550 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001551 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001552
Max Bires2b2e6562020-09-22 11:22:36 -07001553 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1554 /// The key id gets associated with a domain and namespace later but not with an alias. The
1555 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1556 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1557 /// a key.
1558 pub fn create_attestation_key_entry(
1559 &mut self,
1560 maced_public_key: &[u8],
1561 raw_public_key: &[u8],
1562 private_key: &[u8],
1563 km_uuid: &Uuid,
1564 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001565 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1566
Max Bires2b2e6562020-09-22 11:22:36 -07001567 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1568 let key_id = KEY_ID_LOCK.get(
1569 Self::insert_with_retry(|id| {
1570 tx.execute(
1571 "INSERT into persistent.keyentry
1572 (id, key_type, domain, namespace, alias, state, km_uuid)
1573 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1574 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1575 )
1576 })
1577 .context("In create_key_entry")?,
1578 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001579 Self::set_blob_internal(
1580 &tx,
1581 key_id.0,
1582 SubComponentType::KEY_BLOB,
1583 Some(private_key),
1584 None,
1585 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001586 let mut metadata = KeyMetaData::new();
1587 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1588 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1589 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001590 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001591 })
1592 .context("In create_attestation_key_entry")
1593 }
1594
Janis Danisevskis377d1002021-01-27 19:07:48 -08001595 /// Set a new blob and associates it with the given key id. Each blob
1596 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001597 /// Each key can have one of each sub component type associated. If more
1598 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001599 /// will get garbage collected.
1600 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1601 /// removed by setting blob to None.
1602 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001603 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001604 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001605 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001606 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001607 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001608 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001609 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1610
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001611 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001612 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001613 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001614 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001615 }
1616
Janis Danisevskiseed69842021-02-18 20:04:10 -08001617 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1618 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1619 /// We use this to insert key blobs into the database which can then be garbage collected
1620 /// lazily by the key garbage collector.
1621 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001622 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1623
Janis Danisevskiseed69842021-02-18 20:04:10 -08001624 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1625 Self::set_blob_internal(
1626 &tx,
1627 Self::UNASSIGNED_KEY_ID,
1628 SubComponentType::KEY_BLOB,
1629 Some(blob),
1630 Some(blob_metadata),
1631 )
1632 .need_gc()
1633 })
1634 .context("In set_deleted_blob.")
1635 }
1636
Janis Danisevskis377d1002021-01-27 19:07:48 -08001637 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001638 tx: &Transaction,
1639 key_id: i64,
1640 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001641 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001642 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001643 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001644 match (blob, sc_type) {
1645 (Some(blob), _) => {
1646 tx.execute(
1647 "INSERT INTO persistent.blobentry
1648 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1649 params![sc_type, key_id, blob],
1650 )
1651 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001652 if let Some(blob_metadata) = blob_metadata {
1653 let blob_id = tx
1654 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1655 row.get(0)
1656 })
1657 .context("In set_blob_internal: Failed to get new blob id.")?;
1658 blob_metadata
1659 .store_in_db(blob_id, tx)
1660 .context("In set_blob_internal: Trying to store blob metadata.")?;
1661 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001662 }
1663 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1664 tx.execute(
1665 "DELETE FROM persistent.blobentry
1666 WHERE subcomponent_type = ? AND keyentryid = ?;",
1667 params![sc_type, key_id],
1668 )
1669 .context("In set_blob_internal: Failed to delete blob.")?;
1670 }
1671 (None, _) => {
1672 return Err(KsError::sys())
1673 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1674 }
1675 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001676 Ok(())
1677 }
1678
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001679 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1680 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001681 #[cfg(test)]
1682 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001683 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001684 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001685 })
1686 .context("In insert_keyparameter.")
1687 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001688
Janis Danisevskis66784c42021-01-27 08:40:25 -08001689 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001690 tx: &Transaction,
1691 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001692 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001693 ) -> Result<()> {
1694 let mut stmt = tx
1695 .prepare(
1696 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1697 VALUES (?, ?, ?, ?);",
1698 )
1699 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1700
Janis Danisevskis66784c42021-01-27 08:40:25 -08001701 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001702 stmt.insert(params![
1703 key_id.0,
1704 p.get_tag().0,
1705 p.key_parameter_value(),
1706 p.security_level().0
1707 ])
1708 .with_context(|| {
1709 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1710 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001711 }
1712 Ok(())
1713 }
1714
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001715 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001716 #[cfg(test)]
1717 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001718 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001719 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001720 })
1721 .context("In insert_key_metadata.")
1722 }
1723
Max Bires2b2e6562020-09-22 11:22:36 -07001724 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1725 /// on the public key.
1726 pub fn store_signed_attestation_certificate_chain(
1727 &mut self,
1728 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001729 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001730 cert_chain: &[u8],
1731 expiration_date: i64,
1732 km_uuid: &Uuid,
1733 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001734 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1735
Max Bires2b2e6562020-09-22 11:22:36 -07001736 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1737 let mut stmt = tx
1738 .prepare(
1739 "SELECT keyentryid
1740 FROM persistent.keymetadata
1741 WHERE tag = ? AND data = ? AND keyentryid IN
1742 (SELECT id
1743 FROM persistent.keyentry
1744 WHERE
1745 alias IS NULL AND
1746 domain IS NULL AND
1747 namespace IS NULL AND
1748 key_type = ? AND
1749 km_uuid = ?);",
1750 )
1751 .context("Failed to store attestation certificate chain.")?;
1752 let mut rows = stmt
1753 .query(params![
1754 KeyMetaData::AttestationRawPubKey,
1755 raw_public_key,
1756 KeyType::Attestation,
1757 km_uuid
1758 ])
1759 .context("Failed to fetch keyid")?;
1760 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1761 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1762 .get(0)
1763 .context("Failed to unpack id.")
1764 })
1765 .context("Failed to get key_id.")?;
1766 let num_updated = tx
1767 .execute(
1768 "UPDATE persistent.keyentry
1769 SET alias = ?
1770 WHERE id = ?;",
1771 params!["signed", key_id],
1772 )
1773 .context("Failed to update alias.")?;
1774 if num_updated != 1 {
1775 return Err(KsError::sys()).context("Alias not updated for the key.");
1776 }
1777 let mut metadata = KeyMetaData::new();
1778 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1779 expiration_date,
1780 )));
1781 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001782 Self::set_blob_internal(
1783 &tx,
1784 key_id,
1785 SubComponentType::CERT_CHAIN,
1786 Some(cert_chain),
1787 None,
1788 )
1789 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001790 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1791 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001792 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001793 })
1794 .context("In store_signed_attestation_certificate_chain: ")
1795 }
1796
1797 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1798 /// currently have a key assigned to it.
1799 pub fn assign_attestation_key(
1800 &mut self,
1801 domain: Domain,
1802 namespace: i64,
1803 km_uuid: &Uuid,
1804 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001805 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1806
Max Bires2b2e6562020-09-22 11:22:36 -07001807 match domain {
1808 Domain::APP | Domain::SELINUX => {}
1809 _ => {
1810 return Err(KsError::sys()).context(format!(
1811 concat!(
1812 "In assign_attestation_key: Domain {:?} ",
1813 "must be either App or SELinux.",
1814 ),
1815 domain
1816 ));
1817 }
1818 }
1819 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1820 let result = tx
1821 .execute(
1822 "UPDATE persistent.keyentry
1823 SET domain=?1, namespace=?2
1824 WHERE
1825 id =
1826 (SELECT MIN(id)
1827 FROM persistent.keyentry
1828 WHERE ALIAS IS NOT NULL
1829 AND domain IS NULL
1830 AND key_type IS ?3
1831 AND state IS ?4
1832 AND km_uuid IS ?5)
1833 AND
1834 (SELECT COUNT(*)
1835 FROM persistent.keyentry
1836 WHERE domain=?1
1837 AND namespace=?2
1838 AND key_type IS ?3
1839 AND state IS ?4
1840 AND km_uuid IS ?5) = 0;",
1841 params![
1842 domain.0 as u32,
1843 namespace,
1844 KeyType::Attestation,
1845 KeyLifeCycle::Live,
1846 km_uuid,
1847 ],
1848 )
1849 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001850 if result == 0 {
1851 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1852 } else if result > 1 {
1853 return Err(KsError::sys())
1854 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001855 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001856 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001857 })
1858 .context("In assign_attestation_key: ")
1859 }
1860
1861 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1862 /// provisioning server, or the maximum number available if there are not num_keys number of
1863 /// entries in the table.
1864 pub fn fetch_unsigned_attestation_keys(
1865 &mut self,
1866 num_keys: i32,
1867 km_uuid: &Uuid,
1868 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001869 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1870
Max Bires2b2e6562020-09-22 11:22:36 -07001871 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1872 let mut stmt = tx
1873 .prepare(
1874 "SELECT data
1875 FROM persistent.keymetadata
1876 WHERE tag = ? AND keyentryid IN
1877 (SELECT id
1878 FROM persistent.keyentry
1879 WHERE
1880 alias IS NULL AND
1881 domain IS NULL AND
1882 namespace IS NULL AND
1883 key_type = ? AND
1884 km_uuid = ?
1885 LIMIT ?);",
1886 )
1887 .context("Failed to prepare statement")?;
1888 let rows = stmt
1889 .query_map(
1890 params![
1891 KeyMetaData::AttestationMacedPublicKey,
1892 KeyType::Attestation,
1893 km_uuid,
1894 num_keys
1895 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001896 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001897 )?
1898 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1899 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001900 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001901 })
1902 .context("In fetch_unsigned_attestation_keys")
1903 }
1904
1905 /// Removes any keys that have expired as of the current time. Returns the number of keys
1906 /// marked unreferenced that are bound to be garbage collected.
1907 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001908 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1909
Max Bires2b2e6562020-09-22 11:22:36 -07001910 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1911 let mut stmt = tx
1912 .prepare(
1913 "SELECT keyentryid, data
1914 FROM persistent.keymetadata
1915 WHERE tag = ? AND keyentryid IN
1916 (SELECT id
1917 FROM persistent.keyentry
1918 WHERE key_type = ?);",
1919 )
1920 .context("Failed to prepare query")?;
1921 let key_ids_to_check = stmt
1922 .query_map(
1923 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1924 |row| Ok((row.get(0)?, row.get(1)?)),
1925 )?
1926 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1927 .context("Failed to get date metadata")?;
1928 let curr_time = DateTime::from_millis_epoch(
1929 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1930 );
1931 let mut num_deleted = 0;
1932 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1933 if Self::mark_unreferenced(&tx, id)? {
1934 num_deleted += 1;
1935 }
1936 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001937 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001938 })
1939 .context("In delete_expired_attestation_keys: ")
1940 }
1941
Max Bires60d7ed12021-03-05 15:59:22 -08001942 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1943 /// they are in. This is useful primarily as a testing mechanism.
1944 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001945 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1946
Max Bires60d7ed12021-03-05 15:59:22 -08001947 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1948 let mut stmt = tx
1949 .prepare(
1950 "SELECT id FROM persistent.keyentry
1951 WHERE key_type IS ?;",
1952 )
1953 .context("Failed to prepare statement")?;
1954 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001955 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001956 .collect::<rusqlite::Result<Vec<i64>>>()
1957 .context("Failed to execute statement")?;
1958 let num_deleted = keys_to_delete
1959 .iter()
1960 .map(|id| Self::mark_unreferenced(&tx, *id))
1961 .collect::<Result<Vec<bool>>>()
1962 .context("Failed to execute mark_unreferenced on a keyid")?
1963 .into_iter()
1964 .filter(|result| *result)
1965 .count() as i64;
1966 Ok(num_deleted).do_gc(num_deleted != 0)
1967 })
1968 .context("In delete_all_attestation_keys: ")
1969 }
1970
Max Bires2b2e6562020-09-22 11:22:36 -07001971 /// Counts the number of keys that will expire by the provided epoch date and the number of
1972 /// keys not currently assigned to a domain.
1973 pub fn get_attestation_pool_status(
1974 &mut self,
1975 date: i64,
1976 km_uuid: &Uuid,
1977 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001978 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1979
Max Bires2b2e6562020-09-22 11:22:36 -07001980 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1981 let mut stmt = tx.prepare(
1982 "SELECT data
1983 FROM persistent.keymetadata
1984 WHERE tag = ? AND keyentryid IN
1985 (SELECT id
1986 FROM persistent.keyentry
1987 WHERE alias IS NOT NULL
1988 AND key_type = ?
1989 AND km_uuid = ?
1990 AND state = ?);",
1991 )?;
1992 let times = stmt
1993 .query_map(
1994 params![
1995 KeyMetaData::AttestationExpirationDate,
1996 KeyType::Attestation,
1997 km_uuid,
1998 KeyLifeCycle::Live
1999 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002000 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002001 )?
2002 .collect::<rusqlite::Result<Vec<DateTime>>>()
2003 .context("Failed to execute metadata statement")?;
2004 let expiring =
2005 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2006 as i32;
2007 stmt = tx.prepare(
2008 "SELECT alias, domain
2009 FROM persistent.keyentry
2010 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2011 )?;
2012 let rows = stmt
2013 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2014 Ok((row.get(0)?, row.get(1)?))
2015 })?
2016 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2017 .context("Failed to execute keyentry statement")?;
2018 let mut unassigned = 0i32;
2019 let mut attested = 0i32;
2020 let total = rows.len() as i32;
2021 for (alias, domain) in rows {
2022 match (alias, domain) {
2023 (Some(_alias), None) => {
2024 attested += 1;
2025 unassigned += 1;
2026 }
2027 (Some(_alias), Some(_domain)) => {
2028 attested += 1;
2029 }
2030 _ => {}
2031 }
2032 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002033 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002034 })
2035 .context("In get_attestation_pool_status: ")
2036 }
2037
2038 /// Fetches the private key and corresponding certificate chain assigned to a
2039 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2040 /// not assigned, or one CertificateChain.
2041 pub fn retrieve_attestation_key_and_cert_chain(
2042 &mut self,
2043 domain: Domain,
2044 namespace: i64,
2045 km_uuid: &Uuid,
2046 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002047 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2048
Max Bires2b2e6562020-09-22 11:22:36 -07002049 match domain {
2050 Domain::APP | Domain::SELINUX => {}
2051 _ => {
2052 return Err(KsError::sys())
2053 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2054 }
2055 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002056 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2057 let mut stmt = tx.prepare(
2058 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002059 FROM persistent.blobentry
2060 WHERE keyentryid IN
2061 (SELECT id
2062 FROM persistent.keyentry
2063 WHERE key_type = ?
2064 AND domain = ?
2065 AND namespace = ?
2066 AND state = ?
2067 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002068 )?;
2069 let rows = stmt
2070 .query_map(
2071 params![
2072 KeyType::Attestation,
2073 domain.0 as u32,
2074 namespace,
2075 KeyLifeCycle::Live,
2076 km_uuid
2077 ],
2078 |row| Ok((row.get(0)?, row.get(1)?)),
2079 )?
2080 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002081 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 if rows.is_empty() {
2083 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002084 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002085 return Err(KsError::sys()).context(format!(
2086 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002087 "Expected to get a single attestation",
2088 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2089 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002090 rows.len()
2091 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002092 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002093 let mut km_blob: Vec<u8> = Vec::new();
2094 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002095 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002096 for row in rows {
2097 let sub_type: SubComponentType = row.0;
2098 match sub_type {
2099 SubComponentType::KEY_BLOB => {
2100 km_blob = row.1;
2101 }
2102 SubComponentType::CERT_CHAIN => {
2103 cert_chain_blob = row.1;
2104 }
Max Biresb2e1d032021-02-08 21:35:05 -08002105 SubComponentType::CERT => {
2106 batch_cert_blob = row.1;
2107 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002108 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2109 }
2110 }
2111 Ok(Some(CertificateChain {
2112 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002113 batch_cert: batch_cert_blob,
2114 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002115 }))
2116 .no_gc()
2117 })
Max Biresb2e1d032021-02-08 21:35:05 -08002118 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002119 }
2120
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002121 /// Updates the alias column of the given key id `newid` with the given alias,
2122 /// and atomically, removes the alias, domain, and namespace from another row
2123 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002124 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2125 /// collector.
2126 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002128 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002129 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002130 domain: &Domain,
2131 namespace: &i64,
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002132 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002133 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002134 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002135 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002136 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002137 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002138 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002139 domain
2140 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002141 }
2142 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002143 let updated = tx
2144 .execute(
2145 "UPDATE persistent.keyentry
2146 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002147 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2148 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002149 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002150 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002151 let result = tx
2152 .execute(
2153 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002154 SET alias = ?, state = ?
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002155 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002156 params![
2157 alias,
2158 KeyLifeCycle::Live,
2159 newid.0,
2160 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002161 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002162 KeyLifeCycle::Existing,
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002163 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002164 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002165 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002166 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002167 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002168 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002169 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002170 result
2171 ));
2172 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002173 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002174 }
2175
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002176 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2177 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2178 pub fn migrate_key_namespace(
2179 &mut self,
2180 key_id_guard: KeyIdGuard,
2181 destination: &KeyDescriptor,
2182 caller_uid: u32,
2183 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2184 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002185 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2186
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002187 let destination = match destination.domain {
2188 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2189 Domain::SELINUX => (*destination).clone(),
2190 domain => {
2191 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2192 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2193 }
2194 };
2195
2196 // Security critical: Must return immediately on failure. Do not remove the '?';
2197 check_permission(&destination)
2198 .context("In migrate_key_namespace: Trying to check permission.")?;
2199
2200 let alias = destination
2201 .alias
2202 .as_ref()
2203 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2204 .context("In migrate_key_namespace: Alias must be specified.")?;
2205
2206 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2207 // Query the destination location. If there is a key, the migration request fails.
2208 if tx
2209 .query_row(
2210 "SELECT id FROM persistent.keyentry
2211 WHERE alias = ? AND domain = ? AND namespace = ?;",
2212 params![alias, destination.domain.0, destination.nspace],
2213 |_| Ok(()),
2214 )
2215 .optional()
2216 .context("Failed to query destination.")?
2217 .is_some()
2218 {
2219 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2220 .context("Target already exists.");
2221 }
2222
2223 let updated = tx
2224 .execute(
2225 "UPDATE persistent.keyentry
2226 SET alias = ?, domain = ?, namespace = ?
2227 WHERE id = ?;",
2228 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2229 )
2230 .context("Failed to update key entry.")?;
2231
2232 if updated != 1 {
2233 return Err(KsError::sys())
2234 .context(format!("Update succeeded, but {} rows were updated.", updated));
2235 }
2236 Ok(()).no_gc()
2237 })
2238 .context("In migrate_key_namespace:")
2239 }
2240
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002241 /// Store a new key in a single transaction.
2242 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2243 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002244 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2245 /// is now unreferenced and needs to be collected.
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002246 #[allow(clippy::clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002247 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002248 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002249 key: &KeyDescriptor,
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002250 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002251 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002252 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002253 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002254 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002255 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002256 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002257 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2258
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002259 let (alias, domain, namespace) = match key {
2260 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2261 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2262 (alias, key.domain, nspace)
2263 }
2264 _ => {
2265 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2266 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2267 }
2268 };
2269 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002270 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002272 let (blob, blob_metadata) = *blob_info;
2273 Self::set_blob_internal(
2274 tx,
2275 key_id.id(),
2276 SubComponentType::KEY_BLOB,
2277 Some(blob),
2278 Some(&blob_metadata),
2279 )
2280 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002281 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002282 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002283 .context("Trying to insert the certificate.")?;
2284 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002285 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002286 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002287 tx,
2288 key_id.id(),
2289 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002290 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002291 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002292 )
2293 .context("Trying to insert the certificate chain.")?;
2294 }
2295 Self::insert_keyparameter_internal(tx, &key_id, params)
2296 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002297 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002298 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace, key_type)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002299 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002300 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002301 })
2302 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002303 }
2304
Janis Danisevskis377d1002021-01-27 19:07:48 -08002305 /// Store a new certificate
2306 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2307 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002308 pub fn store_new_certificate(
2309 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002310 key: &KeyDescriptor,
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002311 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002312 cert: &[u8],
2313 km_uuid: &Uuid,
2314 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002315 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2316
Janis Danisevskis377d1002021-01-27 19:07:48 -08002317 let (alias, domain, namespace) = match key {
2318 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2319 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2320 (alias, key.domain, nspace)
2321 }
2322 _ => {
2323 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2324 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2325 )
2326 }
2327 };
2328 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002329 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002330 .context("Trying to create new key entry.")?;
2331
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002332 Self::set_blob_internal(
2333 tx,
2334 key_id.id(),
2335 SubComponentType::CERT_CHAIN,
2336 Some(cert),
2337 None,
2338 )
2339 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002340
2341 let mut metadata = KeyMetaData::new();
2342 metadata.add(KeyMetaEntry::CreationDate(
2343 DateTime::now().context("Trying to make creation time.")?,
2344 ));
2345
2346 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2347
Janis Danisevskis10b79f52021-05-25 11:07:10 -07002348 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002349 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002350 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002351 })
2352 .context("In store_new_certificate.")
2353 }
2354
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002355 // Helper function loading the key_id given the key descriptor
2356 // tuple comprising domain, namespace, and alias.
2357 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002358 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002359 let alias = key
2360 .alias
2361 .as_ref()
2362 .map_or_else(|| Err(KsError::sys()), Ok)
2363 .context("In load_key_entry_id: Alias must be specified.")?;
2364 let mut stmt = tx
2365 .prepare(
2366 "SELECT id FROM persistent.keyentry
2367 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002368 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002369 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002370 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002371 AND alias = ?
2372 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002373 )
2374 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2375 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002376 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002377 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002378 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002379 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002380 .get(0)
2381 .context("Failed to unpack id.")
2382 })
2383 .context("In load_key_entry_id.")
2384 }
2385
2386 /// This helper function completes the access tuple of a key, which is required
2387 /// to perform access control. The strategy depends on the `domain` field in the
2388 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002389 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002390 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002391 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002392 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002393 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002394 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002395 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002396 /// `namespace`.
2397 /// In each case the information returned is sufficient to perform the access
2398 /// check and the key id can be used to load further key artifacts.
2399 fn load_access_tuple(
2400 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002401 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002402 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002403 caller_uid: u32,
2404 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2405 match key.domain {
2406 // Domain App or SELinux. In this case we load the key_id from
2407 // the keyentry database for further loading of key components.
2408 // We already have the full access tuple to perform access control.
2409 // The only distinction is that we use the caller_uid instead
2410 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002411 // Domain::APP.
2412 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002413 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002414 if access_key.domain == Domain::APP {
2415 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002416 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002417 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002418 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419
2420 Ok((key_id, access_key, None))
2421 }
2422
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002423 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002424 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002425 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002426 let mut stmt = tx
2427 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002428 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002429 WHERE grantee = ? AND id = ? AND
2430 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002431 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002432 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002433 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002434 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002435 .context("Domain:Grant: query failed.")?;
2436 let (key_id, access_vector): (i64, i32) =
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((
2441 r.get(0).context("Failed to unpack key_id.")?,
2442 r.get(1).context("Failed to unpack access_vector.")?,
2443 ))
2444 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002445 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002446 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002447 }
2448
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002449 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002450 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002451 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002452 let (domain, namespace): (Domain, i64) = {
2453 let mut stmt = tx
2454 .prepare(
2455 "SELECT domain, namespace FROM persistent.keyentry
2456 WHERE
2457 id = ?
2458 AND state = ?;",
2459 )
2460 .context("Domain::KEY_ID: prepare statement failed")?;
2461 let mut rows = stmt
2462 .query(params![key.nspace, KeyLifeCycle::Live])
2463 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002464 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002465 let r =
2466 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002467 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002468 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002469 r.get(1).context("Failed to unpack namespace.")?,
2470 ))
2471 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002472 .context("Domain::KEY_ID.")?
2473 };
2474
2475 // We may use a key by id after loading it by grant.
2476 // In this case we have to check if the caller has a grant for this particular
2477 // key. We can skip this if we already know that the caller is the owner.
2478 // But we cannot know this if domain is anything but App. E.g. in the case
2479 // of Domain::SELINUX we have to speculatively check for grants because we have to
2480 // consult the SEPolicy before we know if the caller is the owner.
2481 let access_vector: Option<KeyPermSet> =
2482 if domain != Domain::APP || namespace != caller_uid as i64 {
2483 let access_vector: Option<i32> = tx
2484 .query_row(
2485 "SELECT access_vector FROM persistent.grant
2486 WHERE grantee = ? AND keyentryid = ?;",
2487 params![caller_uid as i64, key.nspace],
2488 |row| row.get(0),
2489 )
2490 .optional()
2491 .context("Domain::KEY_ID: query grant failed.")?;
2492 access_vector.map(|p| p.into())
2493 } else {
2494 None
2495 };
2496
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002497 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002498 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002499 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002500 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002501
Janis Danisevskis45760022021-01-19 16:34:10 -08002502 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002503 }
2504 _ => Err(anyhow!(KsError::sys())),
2505 }
2506 }
2507
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002508 fn load_blob_components(
2509 key_id: i64,
2510 load_bits: KeyEntryLoadBits,
2511 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002512 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002513 let mut stmt = tx
2514 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002515 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002516 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2517 )
2518 .context("In load_blob_components: prepare statement failed.")?;
2519
2520 let mut rows =
2521 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2522
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002523 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002524 let mut cert_blob: Option<Vec<u8>> = None;
2525 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002526 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002527 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002528 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002529 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002530 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002531 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2532 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002533 key_blob = Some((
2534 row.get(0).context("Failed to extract key blob id.")?,
2535 row.get(2).context("Failed to extract key blob.")?,
2536 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002537 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002538 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002539 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002540 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002541 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002542 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002543 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002544 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002545 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002546 (SubComponentType::CERT, _, _)
2547 | (SubComponentType::CERT_CHAIN, _, _)
2548 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002549 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2550 }
2551 Ok(())
2552 })
2553 .context("In load_blob_components.")?;
2554
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002555 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2556 Ok(Some((
2557 blob,
2558 BlobMetaData::load_from_db(blob_id, tx)
2559 .context("In load_blob_components: Trying to load blob_metadata.")?,
2560 )))
2561 })?;
2562
2563 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002564 }
2565
2566 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2567 let mut stmt = tx
2568 .prepare(
2569 "SELECT tag, data, security_level from persistent.keyparameter
2570 WHERE keyentryid = ?;",
2571 )
2572 .context("In load_key_parameters: prepare statement failed.")?;
2573
2574 let mut parameters: Vec<KeyParameter> = Vec::new();
2575
2576 let mut rows =
2577 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002578 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002579 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2580 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002581 parameters.push(
2582 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2583 .context("Failed to read KeyParameter.")?,
2584 );
2585 Ok(())
2586 })
2587 .context("In load_key_parameters.")?;
2588
2589 Ok(parameters)
2590 }
2591
Qi Wub9433b52020-12-01 14:52:46 +08002592 /// Decrements the usage count of a limited use key. This function first checks whether the
2593 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2594 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2595 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002596 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002597 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2598
Qi Wub9433b52020-12-01 14:52:46 +08002599 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2600 let limit: Option<i32> = tx
2601 .query_row(
2602 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2603 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2604 |row| row.get(0),
2605 )
2606 .optional()
2607 .context("Trying to load usage count")?;
2608
2609 let limit = limit
2610 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2611 .context("The Key no longer exists. Key is exhausted.")?;
2612
2613 tx.execute(
2614 "UPDATE persistent.keyparameter
2615 SET data = data - 1
2616 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2617 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2618 )
2619 .context("Failed to update key usage count.")?;
2620
2621 match limit {
2622 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002623 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002624 .context("Trying to mark limited use key for deletion."),
2625 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002626 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002627 }
2628 })
2629 .context("In check_and_update_key_usage_count.")
2630 }
2631
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002632 /// Load a key entry by the given key descriptor.
2633 /// It uses the `check_permission` callback to verify if the access is allowed
2634 /// given the key access tuple read from the database using `load_access_tuple`.
2635 /// With `load_bits` the caller may specify which blobs shall be loaded from
2636 /// the blob database.
2637 pub fn load_key_entry(
2638 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002639 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002640 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002641 load_bits: KeyEntryLoadBits,
2642 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002643 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2644 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002645 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2646
Janis Danisevskis66784c42021-01-27 08:40:25 -08002647 loop {
2648 match self.load_key_entry_internal(
2649 key,
2650 key_type,
2651 load_bits,
2652 caller_uid,
2653 &check_permission,
2654 ) {
2655 Ok(result) => break Ok(result),
2656 Err(e) => {
2657 if Self::is_locked_error(&e) {
2658 std::thread::sleep(std::time::Duration::from_micros(500));
2659 continue;
2660 } else {
2661 return Err(e).context("In load_key_entry.");
2662 }
2663 }
2664 }
2665 }
2666 }
2667
2668 fn load_key_entry_internal(
2669 &mut self,
2670 key: &KeyDescriptor,
2671 key_type: KeyType,
2672 load_bits: KeyEntryLoadBits,
2673 caller_uid: u32,
2674 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002675 ) -> Result<(KeyIdGuard, KeyEntry)> {
2676 // KEY ID LOCK 1/2
2677 // If we got a key descriptor with a key id we can get the lock right away.
2678 // Otherwise we have to defer it until we know the key id.
2679 let key_id_guard = match key.domain {
2680 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2681 _ => None,
2682 };
2683
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002684 let tx = self
2685 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002686 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002687 .context("In load_key_entry: Failed to initialize transaction.")?;
2688
2689 // Load the key_id and complete the access control tuple.
2690 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002691 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2692 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002693
2694 // Perform access control. It is vital that we return here if the permission is denied.
2695 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002696 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002697
Janis Danisevskisaec14592020-11-12 09:41:49 -08002698 // KEY ID LOCK 2/2
2699 // If we did not get a key id lock by now, it was because we got a key descriptor
2700 // without a key id. At this point we got the key id, so we can try and get a lock.
2701 // However, we cannot block here, because we are in the middle of the transaction.
2702 // So first we try to get the lock non blocking. If that fails, we roll back the
2703 // transaction and block until we get the lock. After we successfully got the lock,
2704 // we start a new transaction and load the access tuple again.
2705 //
2706 // We don't need to perform access control again, because we already established
2707 // that the caller had access to the given key. But we need to make sure that the
2708 // key id still exists. So we have to load the key entry by key id this time.
2709 let (key_id_guard, tx) = match key_id_guard {
2710 None => match KEY_ID_LOCK.try_get(key_id) {
2711 None => {
2712 // Roll back the transaction.
2713 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002714
Janis Danisevskisaec14592020-11-12 09:41:49 -08002715 // Block until we have a key id lock.
2716 let key_id_guard = KEY_ID_LOCK.get(key_id);
2717
2718 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002719 let tx = self
2720 .conn
2721 .unchecked_transaction()
2722 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002723
2724 Self::load_access_tuple(
2725 &tx,
2726 // This time we have to load the key by the retrieved key id, because the
2727 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002728 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002729 domain: Domain::KEY_ID,
2730 nspace: key_id,
2731 ..Default::default()
2732 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002733 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002734 caller_uid,
2735 )
2736 .context("In load_key_entry. (deferred key lock)")?;
2737 (key_id_guard, tx)
2738 }
2739 Some(l) => (l, tx),
2740 },
2741 Some(key_id_guard) => (key_id_guard, tx),
2742 };
2743
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002744 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2745 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002746
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002747 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2748
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002749 Ok((key_id_guard, key_entry))
2750 }
2751
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002752 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002753 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002754 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2755 .context("Trying to delete keyentry.")?;
2756 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2757 .context("Trying to delete keymetadata.")?;
2758 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2759 .context("Trying to delete keyparameters.")?;
2760 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2761 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002762 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002763 }
2764
2765 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002766 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002767 pub fn unbind_key(
2768 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002769 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002770 key_type: KeyType,
2771 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002772 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002773 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002774 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2775
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002776 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2777 let (key_id, access_key_descriptor, access_vector) =
2778 Self::load_access_tuple(tx, key, key_type, caller_uid)
2779 .context("Trying to get access tuple.")?;
2780
2781 // Perform access control. It is vital that we return here if the permission is denied.
2782 // So do not touch that '?' at the end.
2783 check_permission(&access_key_descriptor, access_vector)
2784 .context("While checking permission.")?;
2785
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002786 Self::mark_unreferenced(tx, key_id)
2787 .map(|need_gc| (need_gc, ()))
2788 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002789 })
2790 .context("In unbind_key.")
2791 }
2792
Max Bires8e93d2b2021-01-14 13:17:59 -08002793 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2794 tx.query_row(
2795 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2796 params![key_id],
2797 |row| row.get(0),
2798 )
2799 .context("In get_key_km_uuid.")
2800 }
2801
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002802 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2803 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2804 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002805 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2806
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002807 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2808 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2809 .context("In unbind_keys_for_namespace.");
2810 }
2811 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2812 tx.execute(
2813 "DELETE FROM persistent.keymetadata
2814 WHERE keyentryid IN (
2815 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002816 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002817 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002818 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002819 )
2820 .context("Trying to delete keymetadata.")?;
2821 tx.execute(
2822 "DELETE FROM persistent.keyparameter
2823 WHERE keyentryid IN (
2824 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002825 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002826 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002827 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002828 )
2829 .context("Trying to delete keyparameters.")?;
2830 tx.execute(
2831 "DELETE FROM persistent.grant
2832 WHERE keyentryid IN (
2833 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002834 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002835 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002836 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002837 )
2838 .context("Trying to delete grants.")?;
2839 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002840 "DELETE FROM persistent.keyentry
2841 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2842 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002843 )
2844 .context("Trying to delete keyentry.")?;
2845 Ok(()).need_gc()
2846 })
2847 .context("In unbind_keys_for_namespace")
2848 }
2849
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002850 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2851 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2852 {
2853 tx.execute(
2854 "DELETE FROM persistent.keymetadata
2855 WHERE keyentryid IN (
2856 SELECT id FROM persistent.keyentry
2857 WHERE state = ?
2858 );",
2859 params![KeyLifeCycle::Unreferenced],
2860 )
2861 .context("Trying to delete keymetadata.")?;
2862 tx.execute(
2863 "DELETE FROM persistent.keyparameter
2864 WHERE keyentryid IN (
2865 SELECT id FROM persistent.keyentry
2866 WHERE state = ?
2867 );",
2868 params![KeyLifeCycle::Unreferenced],
2869 )
2870 .context("Trying to delete keyparameters.")?;
2871 tx.execute(
2872 "DELETE FROM persistent.grant
2873 WHERE keyentryid IN (
2874 SELECT id FROM persistent.keyentry
2875 WHERE state = ?
2876 );",
2877 params![KeyLifeCycle::Unreferenced],
2878 )
2879 .context("Trying to delete grants.")?;
2880 tx.execute(
2881 "DELETE FROM persistent.keyentry
2882 WHERE state = ?;",
2883 params![KeyLifeCycle::Unreferenced],
2884 )
2885 .context("Trying to delete keyentry.")?;
2886 Result::<()>::Ok(())
2887 }
2888 .context("In cleanup_unreferenced")
2889 }
2890
Hasini Gunasingheda895552021-01-27 19:34:37 +00002891 /// Delete the keys created on behalf of the user, denoted by the user id.
2892 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2893 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2894 /// The caller of this function should notify the gc if the returned value is true.
2895 pub fn unbind_keys_for_user(
2896 &mut self,
2897 user_id: u32,
2898 keep_non_super_encrypted_keys: bool,
2899 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002900 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2901
Hasini Gunasingheda895552021-01-27 19:34:37 +00002902 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2903 let mut stmt = tx
2904 .prepare(&format!(
2905 "SELECT id from persistent.keyentry
2906 WHERE (
2907 key_type = ?
2908 AND domain = ?
2909 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2910 AND state = ?
2911 ) OR (
2912 key_type = ?
2913 AND namespace = ?
2914 AND alias = ?
2915 AND state = ?
2916 );",
2917 aid_user_offset = AID_USER_OFFSET
2918 ))
2919 .context(concat!(
2920 "In unbind_keys_for_user. ",
2921 "Failed to prepare the query to find the keys created by apps."
2922 ))?;
2923
2924 let mut rows = stmt
2925 .query(params![
2926 // WHERE client key:
2927 KeyType::Client,
2928 Domain::APP.0 as u32,
2929 user_id,
2930 KeyLifeCycle::Live,
2931 // OR super key:
2932 KeyType::Super,
2933 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002934 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002935 KeyLifeCycle::Live
2936 ])
2937 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2938
2939 let mut key_ids: Vec<i64> = Vec::new();
2940 db_utils::with_rows_extract_all(&mut rows, |row| {
2941 key_ids
2942 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2943 Ok(())
2944 })
2945 .context("In unbind_keys_for_user.")?;
2946
2947 let mut notify_gc = false;
2948 for key_id in key_ids {
2949 if keep_non_super_encrypted_keys {
2950 // Load metadata and filter out non-super-encrypted keys.
2951 if let (_, Some((_, blob_metadata)), _, _) =
2952 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2953 .context("In unbind_keys_for_user: Trying to load blob info.")?
2954 {
2955 if blob_metadata.encrypted_by().is_none() {
2956 continue;
2957 }
2958 }
2959 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002960 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002961 .context("In unbind_keys_for_user.")?
2962 || notify_gc;
2963 }
2964 Ok(()).do_gc(notify_gc)
2965 })
2966 .context("In unbind_keys_for_user.")
2967 }
2968
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002969 fn load_key_components(
2970 tx: &Transaction,
2971 load_bits: KeyEntryLoadBits,
2972 key_id: i64,
2973 ) -> Result<KeyEntry> {
2974 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2975
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002976 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002977 Self::load_blob_components(key_id, load_bits, &tx)
2978 .context("In load_key_components.")?;
2979
Max Bires8e93d2b2021-01-14 13:17:59 -08002980 let parameters = Self::load_key_parameters(key_id, &tx)
2981 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002982
Max Bires8e93d2b2021-01-14 13:17:59 -08002983 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2984 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002985
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002986 Ok(KeyEntry {
2987 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002988 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002989 cert: cert_blob,
2990 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002991 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002992 parameters,
2993 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002994 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002995 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002996 }
2997
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002998 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2999 /// The key descriptors will have the domain, nspace, and alias field set.
3000 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskisc2c856e2021-05-17 13:30:32 -07003001 pub fn list(
3002 &mut self,
3003 domain: Domain,
3004 namespace: i64,
3005 key_type: KeyType,
3006 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003007 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3008
Janis Danisevskis66784c42021-01-27 08:40:25 -08003009 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3010 let mut stmt = tx
3011 .prepare(
3012 "SELECT alias FROM persistent.keyentry
Janis Danisevskisc2c856e2021-05-17 13:30:32 -07003013 WHERE domain = ?
3014 AND namespace = ?
3015 AND alias IS NOT NULL
3016 AND state = ?
3017 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003018 )
3019 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003020
Janis Danisevskis66784c42021-01-27 08:40:25 -08003021 let mut rows = stmt
Janis Danisevskisc2c856e2021-05-17 13:30:32 -07003022 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08003023 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003024
Janis Danisevskis66784c42021-01-27 08:40:25 -08003025 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3026 db_utils::with_rows_extract_all(&mut rows, |row| {
3027 descriptors.push(KeyDescriptor {
3028 domain,
3029 nspace: namespace,
3030 alias: Some(row.get(0).context("Trying to extract alias.")?),
3031 blob: None,
3032 });
3033 Ok(())
3034 })
3035 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003036 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003037 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003038 }
3039
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003040 /// Adds a grant to the grant table.
3041 /// Like `load_key_entry` this function loads the access tuple before
3042 /// it uses the callback for a permission check. Upon success,
3043 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3044 /// grant table. The new row will have a randomized id, which is used as
3045 /// grant id in the namespace field of the resulting KeyDescriptor.
3046 pub fn grant(
3047 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003048 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003049 caller_uid: u32,
3050 grantee_uid: u32,
3051 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003052 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003053 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003054 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3055
Janis Danisevskis66784c42021-01-27 08:40:25 -08003056 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3057 // Load the key_id and complete the access control tuple.
3058 // We ignore the access vector here because grants cannot be granted.
3059 // The access vector returned here expresses the permissions the
3060 // grantee has if key.domain == Domain::GRANT. But this vector
3061 // cannot include the grant permission by design, so there is no way the
3062 // subsequent permission check can pass.
3063 // We could check key.domain == Domain::GRANT and fail early.
3064 // But even if we load the access tuple by grant here, the permission
3065 // check denies the attempt to create a grant by grant descriptor.
3066 let (key_id, access_key_descriptor, _) =
3067 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3068 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003069
Janis Danisevskis66784c42021-01-27 08:40:25 -08003070 // Perform access control. It is vital that we return here if the permission
3071 // was denied. So do not touch that '?' at the end of the line.
3072 // This permission check checks if the caller has the grant permission
3073 // for the given key and in addition to all of the permissions
3074 // expressed in `access_vector`.
3075 check_permission(&access_key_descriptor, &access_vector)
3076 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003077
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 let grant_id = if let Some(grant_id) = tx
3079 .query_row(
3080 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003081 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003082 params![key_id, grantee_uid],
3083 |row| row.get(0),
3084 )
3085 .optional()
3086 .context("In grant: Failed get optional existing grant id.")?
3087 {
3088 tx.execute(
3089 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003090 SET access_vector = ?
3091 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003092 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003093 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003094 .context("In grant: Failed to update existing grant.")?;
3095 grant_id
3096 } else {
3097 Self::insert_with_retry(|id| {
3098 tx.execute(
3099 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3100 VALUES (?, ?, ?, ?);",
3101 params![id, grantee_uid, key_id, i32::from(access_vector)],
3102 )
3103 })
3104 .context("In grant")?
3105 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003106
Janis Danisevskis66784c42021-01-27 08:40:25 -08003107 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003108 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003109 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003110 }
3111
3112 /// This function checks permissions like `grant` and `load_key_entry`
3113 /// before removing a grant from the grant table.
3114 pub fn ungrant(
3115 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003116 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003117 caller_uid: u32,
3118 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003119 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003120 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003121 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3122
Janis Danisevskis66784c42021-01-27 08:40:25 -08003123 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3124 // Load the key_id and complete the access control tuple.
3125 // We ignore the access vector here because grants cannot be granted.
3126 let (key_id, access_key_descriptor, _) =
3127 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3128 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003129
Janis Danisevskis66784c42021-01-27 08:40:25 -08003130 // Perform access control. We must return here if the permission
3131 // was denied. So do not touch the '?' at the end of this line.
3132 check_permission(&access_key_descriptor)
3133 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003134
Janis Danisevskis66784c42021-01-27 08:40:25 -08003135 tx.execute(
3136 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003137 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003138 params![key_id, grantee_uid],
3139 )
3140 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003141
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003142 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003143 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003144 }
3145
Joel Galenson845f74b2020-09-09 14:11:55 -07003146 // Generates a random id and passes it to the given function, which will
3147 // try to insert it into a database. If that insertion fails, retry;
3148 // otherwise return the id.
3149 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3150 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003151 let newid: i64 = match random() {
3152 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3153 i => i,
3154 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003155 match inserter(newid) {
3156 // If the id already existed, try again.
3157 Err(rusqlite::Error::SqliteFailure(
3158 libsqlite3_sys::Error {
3159 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3160 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3161 },
3162 _,
3163 )) => (),
3164 Err(e) => {
3165 return Err(e).context("In insert_with_retry: failed to insert into database.")
3166 }
3167 _ => return Ok(newid),
3168 }
3169 }
3170 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003171
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003172 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3173 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3174 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3175 auth_token.clone(),
3176 MonotonicRawTime::now(),
3177 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003178 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003179
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003180 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003181 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003182 where
3183 F: Fn(&AuthTokenEntry) -> bool,
3184 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003185 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003186 }
3187
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003188 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003189 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3190 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003191 }
3192
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003193 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003194 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3195 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003196 }
3197
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003198 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003199 fn get_last_off_body(&self) -> MonotonicRawTime {
3200 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003201 }
Pavel Grafov1ff6cd32021-05-12 22:35:45 +01003202
3203 /// Load descriptor of a key by key id
3204 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3205 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3206
3207 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3208 tx.query_row(
3209 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3210 params![key_id],
3211 |row| {
3212 Ok(KeyDescriptor {
3213 domain: Domain(row.get(0)?),
3214 nspace: row.get(1)?,
3215 alias: row.get(2)?,
3216 blob: None,
3217 })
3218 },
3219 )
3220 .optional()
3221 .context("Trying to load key descriptor")
3222 .no_gc()
3223 })
3224 .context("In load_key_descriptor.")
3225 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003226}
3227
3228#[cfg(test)]
3229mod tests {
3230
3231 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003232 use crate::key_parameter::{
3233 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3234 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3235 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003236 use crate::key_perm_set;
3237 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003238 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003239 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003240 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3241 HardwareAuthToken::HardwareAuthToken,
3242 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003243 };
3244 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003245 Timestamp::Timestamp,
3246 };
Seth Moore472fcbb2021-05-12 10:07:51 -07003247 use rusqlite::DatabaseName::Attached;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003248 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003249 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003250 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003251 use std::collections::BTreeMap;
3252 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003253 use std::sync::atomic::{AtomicU8, Ordering};
3254 use std::sync::Arc;
3255 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003256 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003257 #[cfg(disabled)]
3258 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003259
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003260 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003261 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003262
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003263 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003264 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003265 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003266 })?;
3267 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003268 }
3269
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003270 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3271 where
3272 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3273 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003274 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003275
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003276 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003277 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003278
Janis Danisevskis3395f862021-05-06 10:54:17 -07003279 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003280 }
3281
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003282 fn rebind_alias(
3283 db: &mut KeystoreDB,
3284 newid: &KeyIdGuard,
3285 alias: &str,
3286 domain: Domain,
3287 namespace: i64,
3288 ) -> Result<bool> {
3289 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003290 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003291 })
3292 .context("In rebind_alias.")
3293 }
3294
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003295 #[test]
3296 fn datetime() -> Result<()> {
3297 let conn = Connection::open_in_memory()?;
3298 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3299 let now = SystemTime::now();
3300 let duration = Duration::from_secs(1000);
3301 let then = now.checked_sub(duration).unwrap();
3302 let soon = now.checked_add(duration).unwrap();
3303 conn.execute(
3304 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3305 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3306 )?;
3307 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3308 let mut rows = stmt.query(NO_PARAMS)?;
3309 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3310 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3311 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3312 assert!(rows.next()?.is_none());
3313 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3314 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3315 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3316 Ok(())
3317 }
3318
Joel Galenson0891bc12020-07-20 10:37:03 -07003319 // Ensure that we're using the "injected" random function, not the real one.
3320 #[test]
3321 fn test_mocked_random() {
3322 let rand1 = random();
3323 let rand2 = random();
3324 let rand3 = random();
3325 if rand1 == rand2 {
3326 assert_eq!(rand2 + 1, rand3);
3327 } else {
3328 assert_eq!(rand1 + 1, rand2);
3329 assert_eq!(rand2, rand3);
3330 }
3331 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003332
Joel Galenson26f4d012020-07-17 14:57:21 -07003333 // Test that we have the correct tables.
3334 #[test]
3335 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003336 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003337 let tables = db
3338 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003339 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003340 .query_map(params![], |row| row.get(0))?
3341 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003342 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003343 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003344 assert_eq!(tables[1], "blobmetadata");
3345 assert_eq!(tables[2], "grant");
3346 assert_eq!(tables[3], "keyentry");
3347 assert_eq!(tables[4], "keymetadata");
3348 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003349 Ok(())
3350 }
3351
3352 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003353 fn test_auth_token_table_invariant() -> Result<()> {
3354 let mut db = new_test_db()?;
3355 let auth_token1 = HardwareAuthToken {
3356 challenge: i64::MAX,
3357 userId: 200,
3358 authenticatorId: 200,
3359 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3360 timestamp: Timestamp { milliSeconds: 500 },
3361 mac: String::from("mac").into_bytes(),
3362 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003363 db.insert_auth_token(&auth_token1);
3364 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003365 assert_eq!(auth_tokens_returned.len(), 1);
3366
3367 // insert another auth token with the same values for the columns in the UNIQUE constraint
3368 // of the auth token table and different value for timestamp
3369 let auth_token2 = HardwareAuthToken {
3370 challenge: i64::MAX,
3371 userId: 200,
3372 authenticatorId: 200,
3373 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3374 timestamp: Timestamp { milliSeconds: 600 },
3375 mac: String::from("mac").into_bytes(),
3376 };
3377
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003378 db.insert_auth_token(&auth_token2);
3379 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003380 assert_eq!(auth_tokens_returned.len(), 1);
3381
3382 if let Some(auth_token) = auth_tokens_returned.pop() {
3383 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3384 }
3385
3386 // insert another auth token with the different values for the columns in the UNIQUE
3387 // constraint of the auth token table
3388 let auth_token3 = HardwareAuthToken {
3389 challenge: i64::MAX,
3390 userId: 201,
3391 authenticatorId: 200,
3392 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3393 timestamp: Timestamp { milliSeconds: 600 },
3394 mac: String::from("mac").into_bytes(),
3395 };
3396
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003397 db.insert_auth_token(&auth_token3);
3398 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003399 assert_eq!(auth_tokens_returned.len(), 2);
3400
3401 Ok(())
3402 }
3403
3404 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003405 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3406 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003407 }
3408
3409 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003410 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003411 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003412 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003413
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003414 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003415 let entries = get_keyentry(&db)?;
3416 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003417
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003418 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003419
3420 let entries_new = get_keyentry(&db)?;
3421 assert_eq!(entries, entries_new);
3422 Ok(())
3423 }
3424
3425 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003426 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003427 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3428 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003429 }
3430
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003431 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003432
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003433 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3434 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003435
3436 let entries = get_keyentry(&db)?;
3437 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003438 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3439 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003440
3441 // Test that we must pass in a valid Domain.
3442 check_result_is_error_containing_string(
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003443 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003444 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003445 );
3446 check_result_is_error_containing_string(
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003447 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003448 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003449 );
3450 check_result_is_error_containing_string(
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003451 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003452 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003453 );
3454
3455 Ok(())
3456 }
3457
Joel Galenson33c04ad2020-08-03 11:04:38 -07003458 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003459 fn test_add_unsigned_key() -> Result<()> {
3460 let mut db = new_test_db()?;
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 db.create_attestation_key_entry(
3465 &public_key,
3466 &raw_public_key,
3467 &private_key,
3468 &KEYSTORE_UUID,
3469 )?;
3470 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3471 assert_eq!(keys.len(), 1);
3472 assert_eq!(keys[0], public_key);
3473 Ok(())
3474 }
3475
3476 #[test]
3477 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3478 let mut db = new_test_db()?;
3479 let expiration_date: i64 = 20;
3480 let namespace: i64 = 30;
3481 let base_byte: u8 = 1;
3482 let loaded_values =
3483 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3484 let chain =
3485 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3486 assert_eq!(true, chain.is_some());
3487 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003488 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003489 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3490 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003491 Ok(())
3492 }
3493
3494 #[test]
3495 fn test_get_attestation_pool_status() -> Result<()> {
3496 let mut db = new_test_db()?;
3497 let namespace: i64 = 30;
3498 load_attestation_key_pool(
3499 &mut db, 10, /* expiration */
3500 namespace, 0x01, /* base_byte */
3501 )?;
3502 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3503 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3504 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3505 assert_eq!(status.expiring, 0);
3506 assert_eq!(status.attested, 3);
3507 assert_eq!(status.unassigned, 0);
3508 assert_eq!(status.total, 3);
3509 assert_eq!(
3510 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3511 1
3512 );
3513 assert_eq!(
3514 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3515 2
3516 );
3517 assert_eq!(
3518 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3519 3
3520 );
3521 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3522 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3523 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3524 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003525 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003526 db.create_attestation_key_entry(
3527 &public_key,
3528 &raw_public_key,
3529 &private_key,
3530 &KEYSTORE_UUID,
3531 )?;
3532 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3533 assert_eq!(status.attested, 3);
3534 assert_eq!(status.unassigned, 0);
3535 assert_eq!(status.total, 4);
3536 db.store_signed_attestation_certificate_chain(
3537 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003538 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003539 &cert_chain,
3540 20,
3541 &KEYSTORE_UUID,
3542 )?;
3543 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3544 assert_eq!(status.attested, 4);
3545 assert_eq!(status.unassigned, 1);
3546 assert_eq!(status.total, 4);
3547 Ok(())
3548 }
3549
3550 #[test]
3551 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003552 let temp_dir =
3553 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3554 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003555 let expiration_date: i64 =
3556 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3557 let namespace: i64 = 30;
3558 let namespace_del1: i64 = 45;
3559 let namespace_del2: i64 = 60;
3560 let entry_values = load_attestation_key_pool(
3561 &mut db,
3562 expiration_date,
3563 namespace,
3564 0x01, /* base_byte */
3565 )?;
3566 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3567 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003568
3569 let blob_entry_row_count: u32 = db
3570 .conn
3571 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3572 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003573 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3574 // one key, one certificate chain, and one certificate.
3575 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003576
Max Bires2b2e6562020-09-22 11:22:36 -07003577 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3578
3579 let mut cert_chain =
3580 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003581 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003582 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003583 assert_eq!(entry_values.batch_cert, value.batch_cert);
3584 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003585 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003586
3587 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3588 Domain::APP,
3589 namespace_del1,
3590 &KEYSTORE_UUID,
3591 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003592 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003593 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3594 Domain::APP,
3595 namespace_del2,
3596 &KEYSTORE_UUID,
3597 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003598 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003599
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003600 // Give the garbage collector half a second to catch up.
3601 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003602
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003603 let blob_entry_row_count: u32 = db
3604 .conn
3605 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3606 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003607 // There shound be 3 blob entries left, because we deleted two of the attestation
3608 // key entries with three blobs each.
3609 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003610
Max Bires2b2e6562020-09-22 11:22:36 -07003611 Ok(())
3612 }
3613
3614 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003615 fn test_delete_all_attestation_keys() -> Result<()> {
3616 let mut db = new_test_db()?;
3617 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3618 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003619 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003620 let result = db.delete_all_attestation_keys()?;
3621
3622 // Give the garbage collector half a second to catch up.
3623 std::thread::sleep(Duration::from_millis(500));
3624
3625 // Attestation keys should be deleted, and the regular key should remain.
3626 assert_eq!(result, 2);
3627
3628 Ok(())
3629 }
3630
3631 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003632 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003633 fn extractor(
3634 ke: &KeyEntryRow,
3635 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3636 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003637 }
3638
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003639 let mut db = new_test_db()?;
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003640 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3641 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003642 let entries = get_keyentry(&db)?;
3643 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003644 assert_eq!(
3645 extractor(&entries[0]),
3646 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3647 );
3648 assert_eq!(
3649 extractor(&entries[1]),
3650 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3651 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003652
3653 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003654 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003655 let entries = get_keyentry(&db)?;
3656 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003657 assert_eq!(
3658 extractor(&entries[0]),
3659 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3660 );
3661 assert_eq!(
3662 extractor(&entries[1]),
3663 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3664 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003665
3666 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003667 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003668 let entries = get_keyentry(&db)?;
3669 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003670 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3671 assert_eq!(
3672 extractor(&entries[1]),
3673 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3674 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003675
3676 // Test that we must pass in a valid Domain.
3677 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003678 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003679 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003680 );
3681 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003682 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003683 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003684 );
3685 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003686 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003687 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003688 );
3689
3690 // Test that we correctly handle setting an alias for something that does not exist.
3691 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003692 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003693 "Expected to update a single entry but instead updated 0",
3694 );
3695 // Test that we correctly abort the transaction in this case.
3696 let entries = get_keyentry(&db)?;
3697 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003698 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3699 assert_eq!(
3700 extractor(&entries[1]),
3701 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3702 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003703
3704 Ok(())
3705 }
3706
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003707 #[test]
3708 fn test_grant_ungrant() -> Result<()> {
3709 const CALLER_UID: u32 = 15;
3710 const GRANTEE_UID: u32 = 12;
3711 const SELINUX_NAMESPACE: i64 = 7;
3712
3713 let mut db = new_test_db()?;
3714 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003715 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3716 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3717 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003718 )?;
3719 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003720 domain: super::Domain::APP,
3721 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003722 alias: Some("key".to_string()),
3723 blob: None,
3724 };
3725 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3726 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3727
3728 // Reset totally predictable random number generator in case we
3729 // are not the first test running on this thread.
3730 reset_random();
3731 let next_random = 0i64;
3732
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003733 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003734 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003735 assert_eq!(*a, PVEC1);
3736 assert_eq!(
3737 *k,
3738 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003739 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003740 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003741 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003742 alias: Some("key".to_string()),
3743 blob: None,
3744 }
3745 );
3746 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003747 })
3748 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003749
3750 assert_eq!(
3751 app_granted_key,
3752 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003753 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003755 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003756 alias: None,
3757 blob: None,
3758 }
3759 );
3760
3761 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003762 domain: super::Domain::SELINUX,
3763 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003764 alias: Some("yek".to_string()),
3765 blob: None,
3766 };
3767
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003768 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003769 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003770 assert_eq!(*a, PVEC1);
3771 assert_eq!(
3772 *k,
3773 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003774 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775 // namespace must be the supplied SELinux
3776 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003777 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003778 alias: Some("yek".to_string()),
3779 blob: None,
3780 }
3781 );
3782 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003783 })
3784 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003785
3786 assert_eq!(
3787 selinux_granted_key,
3788 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003789 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003790 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003791 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003792 alias: None,
3793 blob: None,
3794 }
3795 );
3796
3797 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003798 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003799 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003800 assert_eq!(*a, PVEC2);
3801 assert_eq!(
3802 *k,
3803 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003804 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003805 // namespace must be the supplied SELinux
3806 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003807 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003808 alias: Some("yek".to_string()),
3809 blob: None,
3810 }
3811 );
3812 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003813 })
3814 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003815
3816 assert_eq!(
3817 selinux_granted_key,
3818 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003819 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003820 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003821 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003822 alias: None,
3823 blob: None,
3824 }
3825 );
3826
3827 {
3828 // Limiting scope of stmt, because it borrows db.
3829 let mut stmt = db
3830 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003831 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003832 let mut rows =
3833 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3834 Ok((
3835 row.get(0)?,
3836 row.get(1)?,
3837 row.get(2)?,
3838 KeyPermSet::from(row.get::<_, i32>(3)?),
3839 ))
3840 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003841
3842 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003843 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003844 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003845 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003846 assert!(rows.next().is_none());
3847 }
3848
3849 debug_dump_keyentry_table(&mut db)?;
3850 println!("app_key {:?}", app_key);
3851 println!("selinux_key {:?}", selinux_key);
3852
Janis Danisevskis66784c42021-01-27 08:40:25 -08003853 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3854 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003855
3856 Ok(())
3857 }
3858
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003859 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003860 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3861 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3862
3863 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003864 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003865 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003866 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003867 let mut blob_metadata = BlobMetaData::new();
3868 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3869 db.set_blob(
3870 &key_id,
3871 SubComponentType::KEY_BLOB,
3872 Some(TEST_KEY_BLOB),
3873 Some(&blob_metadata),
3874 )?;
3875 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3876 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003877 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003878
3879 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003880 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003881 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003882 )?;
3883 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003884 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3885 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003886 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003887 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003888 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003889 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003890 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003891 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003892 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003893
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003894 drop(rows);
3895 drop(stmt);
3896
3897 assert_eq!(
3898 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3899 BlobMetaData::load_from_db(id, tx).no_gc()
3900 })
3901 .expect("Should find blob metadata."),
3902 blob_metadata
3903 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003904 Ok(())
3905 }
3906
3907 static TEST_ALIAS: &str = "my super duper key";
3908
3909 #[test]
3910 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3911 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003912 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003913 .context("test_insert_and_load_full_keyentry_domain_app")?
3914 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003915 let (_key_guard, key_entry) = db
3916 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003917 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003918 domain: Domain::APP,
3919 nspace: 0,
3920 alias: Some(TEST_ALIAS.to_string()),
3921 blob: None,
3922 },
3923 KeyType::Client,
3924 KeyEntryLoadBits::BOTH,
3925 1,
3926 |_k, _av| Ok(()),
3927 )
3928 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003929 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003930
3931 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003932 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003933 domain: Domain::APP,
3934 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003935 alias: Some(TEST_ALIAS.to_string()),
3936 blob: None,
3937 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003938 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003939 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003940 |_, _| Ok(()),
3941 )
3942 .unwrap();
3943
3944 assert_eq!(
3945 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3946 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003947 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003948 domain: Domain::APP,
3949 nspace: 0,
3950 alias: Some(TEST_ALIAS.to_string()),
3951 blob: None,
3952 },
3953 KeyType::Client,
3954 KeyEntryLoadBits::NONE,
3955 1,
3956 |_k, _av| Ok(()),
3957 )
3958 .unwrap_err()
3959 .root_cause()
3960 .downcast_ref::<KsError>()
3961 );
3962
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003963 Ok(())
3964 }
3965
3966 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003967 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3968 let mut db = new_test_db()?;
3969
3970 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003971 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003972 domain: Domain::APP,
3973 nspace: 1,
3974 alias: Some(TEST_ALIAS.to_string()),
3975 blob: None,
3976 },
Janis Danisevskis10b79f52021-05-25 11:07:10 -07003977 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003978 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003979 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003980 )
3981 .expect("Trying to insert cert.");
3982
3983 let (_key_guard, mut key_entry) = db
3984 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003985 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003986 domain: Domain::APP,
3987 nspace: 1,
3988 alias: Some(TEST_ALIAS.to_string()),
3989 blob: None,
3990 },
3991 KeyType::Client,
3992 KeyEntryLoadBits::PUBLIC,
3993 1,
3994 |_k, _av| Ok(()),
3995 )
3996 .expect("Trying to read certificate entry.");
3997
3998 assert!(key_entry.pure_cert());
3999 assert!(key_entry.cert().is_none());
4000 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4001
4002 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004003 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004004 domain: Domain::APP,
4005 nspace: 1,
4006 alias: Some(TEST_ALIAS.to_string()),
4007 blob: None,
4008 },
4009 KeyType::Client,
4010 1,
4011 |_, _| Ok(()),
4012 )
4013 .unwrap();
4014
4015 assert_eq!(
4016 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4017 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004018 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004019 domain: Domain::APP,
4020 nspace: 1,
4021 alias: Some(TEST_ALIAS.to_string()),
4022 blob: None,
4023 },
4024 KeyType::Client,
4025 KeyEntryLoadBits::NONE,
4026 1,
4027 |_k, _av| Ok(()),
4028 )
4029 .unwrap_err()
4030 .root_cause()
4031 .downcast_ref::<KsError>()
4032 );
4033
4034 Ok(())
4035 }
4036
4037 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004038 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4039 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004040 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004041 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4042 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004043 let (_key_guard, key_entry) = db
4044 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004045 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004046 domain: Domain::SELINUX,
4047 nspace: 1,
4048 alias: Some(TEST_ALIAS.to_string()),
4049 blob: None,
4050 },
4051 KeyType::Client,
4052 KeyEntryLoadBits::BOTH,
4053 1,
4054 |_k, _av| Ok(()),
4055 )
4056 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004057 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004058
4059 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004060 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004061 domain: Domain::SELINUX,
4062 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004063 alias: Some(TEST_ALIAS.to_string()),
4064 blob: None,
4065 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004066 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004067 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004068 |_, _| Ok(()),
4069 )
4070 .unwrap();
4071
4072 assert_eq!(
4073 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4074 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004075 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004076 domain: Domain::SELINUX,
4077 nspace: 1,
4078 alias: Some(TEST_ALIAS.to_string()),
4079 blob: None,
4080 },
4081 KeyType::Client,
4082 KeyEntryLoadBits::NONE,
4083 1,
4084 |_k, _av| Ok(()),
4085 )
4086 .unwrap_err()
4087 .root_cause()
4088 .downcast_ref::<KsError>()
4089 );
4090
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004091 Ok(())
4092 }
4093
4094 #[test]
4095 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4096 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004097 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004098 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4099 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004100 let (_, key_entry) = db
4101 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004102 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004103 KeyType::Client,
4104 KeyEntryLoadBits::BOTH,
4105 1,
4106 |_k, _av| Ok(()),
4107 )
4108 .unwrap();
4109
Qi Wub9433b52020-12-01 14:52:46 +08004110 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004111
4112 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004113 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004114 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004115 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004116 |_, _| Ok(()),
4117 )
4118 .unwrap();
4119
4120 assert_eq!(
4121 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4122 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004123 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004124 KeyType::Client,
4125 KeyEntryLoadBits::NONE,
4126 1,
4127 |_k, _av| Ok(()),
4128 )
4129 .unwrap_err()
4130 .root_cause()
4131 .downcast_ref::<KsError>()
4132 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004133
4134 Ok(())
4135 }
4136
4137 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004138 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4139 let mut db = new_test_db()?;
4140 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4141 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4142 .0;
4143 // Update the usage count of the limited use key.
4144 db.check_and_update_key_usage_count(key_id)?;
4145
4146 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004147 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004148 KeyType::Client,
4149 KeyEntryLoadBits::BOTH,
4150 1,
4151 |_k, _av| Ok(()),
4152 )?;
4153
4154 // The usage count is decremented now.
4155 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4156
4157 Ok(())
4158 }
4159
4160 #[test]
4161 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4162 let mut db = new_test_db()?;
4163 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4164 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4165 .0;
4166 // Update the usage count of the limited use key.
4167 db.check_and_update_key_usage_count(key_id).expect(concat!(
4168 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4169 "This should succeed."
4170 ));
4171
4172 // Try to update the exhausted limited use key.
4173 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4174 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4175 "This should fail."
4176 ));
4177 assert_eq!(
4178 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4179 e.root_cause().downcast_ref::<KsError>().unwrap()
4180 );
4181
4182 Ok(())
4183 }
4184
4185 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004186 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4187 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004188 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004189 .context("test_insert_and_load_full_keyentry_from_grant")?
4190 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004191
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004192 let granted_key = db
4193 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004194 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004195 domain: Domain::APP,
4196 nspace: 0,
4197 alias: Some(TEST_ALIAS.to_string()),
4198 blob: None,
4199 },
4200 1,
4201 2,
4202 key_perm_set![KeyPerm::use_()],
4203 |_k, _av| Ok(()),
4204 )
4205 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004206
4207 debug_dump_grant_table(&mut db)?;
4208
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004209 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004210 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4211 assert_eq!(Domain::GRANT, k.domain);
4212 assert!(av.unwrap().includes(KeyPerm::use_()));
4213 Ok(())
4214 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004215 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004216
Qi Wub9433b52020-12-01 14:52:46 +08004217 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004218
Janis Danisevskis66784c42021-01-27 08:40:25 -08004219 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004220
4221 assert_eq!(
4222 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4223 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004224 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004225 KeyType::Client,
4226 KeyEntryLoadBits::NONE,
4227 2,
4228 |_k, _av| Ok(()),
4229 )
4230 .unwrap_err()
4231 .root_cause()
4232 .downcast_ref::<KsError>()
4233 );
4234
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004235 Ok(())
4236 }
4237
Janis Danisevskis45760022021-01-19 16:34:10 -08004238 // This test attempts to load a key by key id while the caller is not the owner
4239 // but a grant exists for the given key and the caller.
4240 #[test]
4241 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4242 let mut db = new_test_db()?;
4243 const OWNER_UID: u32 = 1u32;
4244 const GRANTEE_UID: u32 = 2u32;
4245 const SOMEONE_ELSE_UID: u32 = 3u32;
4246 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4247 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4248 .0;
4249
4250 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004251 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004252 domain: Domain::APP,
4253 nspace: 0,
4254 alias: Some(TEST_ALIAS.to_string()),
4255 blob: None,
4256 },
4257 OWNER_UID,
4258 GRANTEE_UID,
4259 key_perm_set![KeyPerm::use_()],
4260 |_k, _av| Ok(()),
4261 )
4262 .unwrap();
4263
4264 debug_dump_grant_table(&mut db)?;
4265
4266 let id_descriptor =
4267 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4268
4269 let (_, key_entry) = db
4270 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004271 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004272 KeyType::Client,
4273 KeyEntryLoadBits::BOTH,
4274 GRANTEE_UID,
4275 |k, av| {
4276 assert_eq!(Domain::APP, k.domain);
4277 assert_eq!(OWNER_UID as i64, k.nspace);
4278 assert!(av.unwrap().includes(KeyPerm::use_()));
4279 Ok(())
4280 },
4281 )
4282 .unwrap();
4283
4284 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4285
4286 let (_, key_entry) = db
4287 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004288 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004289 KeyType::Client,
4290 KeyEntryLoadBits::BOTH,
4291 SOMEONE_ELSE_UID,
4292 |k, av| {
4293 assert_eq!(Domain::APP, k.domain);
4294 assert_eq!(OWNER_UID as i64, k.nspace);
4295 assert!(av.is_none());
4296 Ok(())
4297 },
4298 )
4299 .unwrap();
4300
4301 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4302
Janis Danisevskis66784c42021-01-27 08:40:25 -08004303 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004304
4305 assert_eq!(
4306 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4307 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004308 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004309 KeyType::Client,
4310 KeyEntryLoadBits::NONE,
4311 GRANTEE_UID,
4312 |_k, _av| Ok(()),
4313 )
4314 .unwrap_err()
4315 .root_cause()
4316 .downcast_ref::<KsError>()
4317 );
4318
4319 Ok(())
4320 }
4321
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004322 // Creates a key migrates it to a different location and then tries to access it by the old
4323 // and new location.
4324 #[test]
4325 fn test_migrate_key_app_to_app() -> Result<()> {
4326 let mut db = new_test_db()?;
4327 const SOURCE_UID: u32 = 1u32;
4328 const DESTINATION_UID: u32 = 2u32;
4329 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4330 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4331 let key_id_guard =
4332 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4333 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4334
4335 let source_descriptor: KeyDescriptor = KeyDescriptor {
4336 domain: Domain::APP,
4337 nspace: -1,
4338 alias: Some(SOURCE_ALIAS.to_string()),
4339 blob: None,
4340 };
4341
4342 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4343 domain: Domain::APP,
4344 nspace: -1,
4345 alias: Some(DESTINATION_ALIAS.to_string()),
4346 blob: None,
4347 };
4348
4349 let key_id = key_id_guard.id();
4350
4351 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4352 Ok(())
4353 })
4354 .unwrap();
4355
4356 let (_, key_entry) = db
4357 .load_key_entry(
4358 &destination_descriptor,
4359 KeyType::Client,
4360 KeyEntryLoadBits::BOTH,
4361 DESTINATION_UID,
4362 |k, av| {
4363 assert_eq!(Domain::APP, k.domain);
4364 assert_eq!(DESTINATION_UID as i64, k.nspace);
4365 assert!(av.is_none());
4366 Ok(())
4367 },
4368 )
4369 .unwrap();
4370
4371 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4372
4373 assert_eq!(
4374 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4375 db.load_key_entry(
4376 &source_descriptor,
4377 KeyType::Client,
4378 KeyEntryLoadBits::NONE,
4379 SOURCE_UID,
4380 |_k, _av| Ok(()),
4381 )
4382 .unwrap_err()
4383 .root_cause()
4384 .downcast_ref::<KsError>()
4385 );
4386
4387 Ok(())
4388 }
4389
4390 // Creates a key migrates it to a different location and then tries to access it by the old
4391 // and new location.
4392 #[test]
4393 fn test_migrate_key_app_to_selinux() -> Result<()> {
4394 let mut db = new_test_db()?;
4395 const SOURCE_UID: u32 = 1u32;
4396 const DESTINATION_UID: u32 = 2u32;
4397 const DESTINATION_NAMESPACE: i64 = 1000i64;
4398 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4399 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4400 let key_id_guard =
4401 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4402 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4403
4404 let source_descriptor: KeyDescriptor = KeyDescriptor {
4405 domain: Domain::APP,
4406 nspace: -1,
4407 alias: Some(SOURCE_ALIAS.to_string()),
4408 blob: None,
4409 };
4410
4411 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4412 domain: Domain::SELINUX,
4413 nspace: DESTINATION_NAMESPACE,
4414 alias: Some(DESTINATION_ALIAS.to_string()),
4415 blob: None,
4416 };
4417
4418 let key_id = key_id_guard.id();
4419
4420 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4421 Ok(())
4422 })
4423 .unwrap();
4424
4425 let (_, key_entry) = db
4426 .load_key_entry(
4427 &destination_descriptor,
4428 KeyType::Client,
4429 KeyEntryLoadBits::BOTH,
4430 DESTINATION_UID,
4431 |k, av| {
4432 assert_eq!(Domain::SELINUX, k.domain);
4433 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4434 assert!(av.is_none());
4435 Ok(())
4436 },
4437 )
4438 .unwrap();
4439
4440 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4441
4442 assert_eq!(
4443 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4444 db.load_key_entry(
4445 &source_descriptor,
4446 KeyType::Client,
4447 KeyEntryLoadBits::NONE,
4448 SOURCE_UID,
4449 |_k, _av| Ok(()),
4450 )
4451 .unwrap_err()
4452 .root_cause()
4453 .downcast_ref::<KsError>()
4454 );
4455
4456 Ok(())
4457 }
4458
4459 // Creates two keys and tries to migrate the first to the location of the second which
4460 // is expected to fail.
4461 #[test]
4462 fn test_migrate_key_destination_occupied() -> Result<()> {
4463 let mut db = new_test_db()?;
4464 const SOURCE_UID: u32 = 1u32;
4465 const DESTINATION_UID: u32 = 2u32;
4466 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4467 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4468 let key_id_guard =
4469 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4470 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4471 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4472 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4473
4474 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4475 domain: Domain::APP,
4476 nspace: -1,
4477 alias: Some(DESTINATION_ALIAS.to_string()),
4478 blob: None,
4479 };
4480
4481 assert_eq!(
4482 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4483 db.migrate_key_namespace(
4484 key_id_guard,
4485 &destination_descriptor,
4486 DESTINATION_UID,
4487 |_k| Ok(())
4488 )
4489 .unwrap_err()
4490 .root_cause()
4491 .downcast_ref::<KsError>()
4492 );
4493
4494 Ok(())
4495 }
4496
Janis Danisevskis97c83872021-05-26 16:31:02 -07004497 #[test]
4498 fn test_upgrade_0_to_1() {
4499 const ALIAS1: &str = &"test_upgrade_0_to_1_1";
4500 const ALIAS2: &str = &"test_upgrade_0_to_1_2";
4501 const ALIAS3: &str = &"test_upgrade_0_to_1_3";
4502 const UID: u32 = 33;
4503 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4504 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4505 let key_id_untouched1 =
4506 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4507 let key_id_untouched2 =
4508 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4509 let key_id_deleted =
4510 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4511
4512 let (_, key_entry) = db
4513 .load_key_entry(
4514 &KeyDescriptor {
4515 domain: Domain::APP,
4516 nspace: -1,
4517 alias: Some(ALIAS1.to_string()),
4518 blob: None,
4519 },
4520 KeyType::Client,
4521 KeyEntryLoadBits::BOTH,
4522 UID,
4523 |k, av| {
4524 assert_eq!(Domain::APP, k.domain);
4525 assert_eq!(UID as i64, k.nspace);
4526 assert!(av.is_none());
4527 Ok(())
4528 },
4529 )
4530 .unwrap();
4531 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4532 let (_, key_entry) = db
4533 .load_key_entry(
4534 &KeyDescriptor {
4535 domain: Domain::APP,
4536 nspace: -1,
4537 alias: Some(ALIAS2.to_string()),
4538 blob: None,
4539 },
4540 KeyType::Client,
4541 KeyEntryLoadBits::BOTH,
4542 UID,
4543 |k, av| {
4544 assert_eq!(Domain::APP, k.domain);
4545 assert_eq!(UID as i64, k.nspace);
4546 assert!(av.is_none());
4547 Ok(())
4548 },
4549 )
4550 .unwrap();
4551 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4552 let (_, key_entry) = db
4553 .load_key_entry(
4554 &KeyDescriptor {
4555 domain: Domain::APP,
4556 nspace: -1,
4557 alias: Some(ALIAS3.to_string()),
4558 blob: None,
4559 },
4560 KeyType::Client,
4561 KeyEntryLoadBits::BOTH,
4562 UID,
4563 |k, av| {
4564 assert_eq!(Domain::APP, k.domain);
4565 assert_eq!(UID as i64, k.nspace);
4566 assert!(av.is_none());
4567 Ok(())
4568 },
4569 )
4570 .unwrap();
4571 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4572
4573 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4574 KeystoreDB::from_0_to_1(tx).no_gc()
4575 })
4576 .unwrap();
4577
4578 let (_, key_entry) = db
4579 .load_key_entry(
4580 &KeyDescriptor {
4581 domain: Domain::APP,
4582 nspace: -1,
4583 alias: Some(ALIAS1.to_string()),
4584 blob: None,
4585 },
4586 KeyType::Client,
4587 KeyEntryLoadBits::BOTH,
4588 UID,
4589 |k, av| {
4590 assert_eq!(Domain::APP, k.domain);
4591 assert_eq!(UID as i64, k.nspace);
4592 assert!(av.is_none());
4593 Ok(())
4594 },
4595 )
4596 .unwrap();
4597 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4598 let (_, key_entry) = db
4599 .load_key_entry(
4600 &KeyDescriptor {
4601 domain: Domain::APP,
4602 nspace: -1,
4603 alias: Some(ALIAS2.to_string()),
4604 blob: None,
4605 },
4606 KeyType::Client,
4607 KeyEntryLoadBits::BOTH,
4608 UID,
4609 |k, av| {
4610 assert_eq!(Domain::APP, k.domain);
4611 assert_eq!(UID as i64, k.nspace);
4612 assert!(av.is_none());
4613 Ok(())
4614 },
4615 )
4616 .unwrap();
4617 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4618 assert_eq!(
4619 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4620 db.load_key_entry(
4621 &KeyDescriptor {
4622 domain: Domain::APP,
4623 nspace: -1,
4624 alias: Some(ALIAS3.to_string()),
4625 blob: None,
4626 },
4627 KeyType::Client,
4628 KeyEntryLoadBits::BOTH,
4629 UID,
4630 |k, av| {
4631 assert_eq!(Domain::APP, k.domain);
4632 assert_eq!(UID as i64, k.nspace);
4633 assert!(av.is_none());
4634 Ok(())
4635 },
4636 )
4637 .unwrap_err()
4638 .root_cause()
4639 .downcast_ref::<KsError>()
4640 );
4641 }
4642
Janis Danisevskisaec14592020-11-12 09:41:49 -08004643 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4644
Janis Danisevskisaec14592020-11-12 09:41:49 -08004645 #[test]
4646 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4647 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004648 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4649 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004650 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004651 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004652 .context("test_insert_and_load_full_keyentry_domain_app")?
4653 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004654 let (_key_guard, key_entry) = db
4655 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004656 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004657 domain: Domain::APP,
4658 nspace: 0,
4659 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4660 blob: None,
4661 },
4662 KeyType::Client,
4663 KeyEntryLoadBits::BOTH,
4664 33,
4665 |_k, _av| Ok(()),
4666 )
4667 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004668 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004669 let state = Arc::new(AtomicU8::new(1));
4670 let state2 = state.clone();
4671
4672 // Spawning a second thread that attempts to acquire the key id lock
4673 // for the same key as the primary thread. The primary thread then
4674 // waits, thereby forcing the secondary thread into the second stage
4675 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4676 // The test succeeds if the secondary thread observes the transition
4677 // of `state` from 1 to 2, despite having a whole second to overtake
4678 // the primary thread.
4679 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004680 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004681 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004682 assert!(db
4683 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004684 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004685 domain: Domain::APP,
4686 nspace: 0,
4687 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4688 blob: None,
4689 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004690 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004691 KeyEntryLoadBits::BOTH,
4692 33,
4693 |_k, _av| Ok(()),
4694 )
4695 .is_ok());
4696 // We should only see a 2 here because we can only return
4697 // from load_key_entry when the `_key_guard` expires,
4698 // which happens at the end of the scope.
4699 assert_eq!(2, state2.load(Ordering::Relaxed));
4700 });
4701
4702 thread::sleep(std::time::Duration::from_millis(1000));
4703
4704 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4705
4706 // Return the handle from this scope so we can join with the
4707 // secondary thread after the key id lock has expired.
4708 handle
4709 // This is where the `_key_guard` goes out of scope,
4710 // which is the reason for concurrent load_key_entry on the same key
4711 // to unblock.
4712 };
4713 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4714 // main test thread. We will not see failing asserts in secondary threads otherwise.
4715 handle.join().unwrap();
4716 Ok(())
4717 }
4718
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004719 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004720 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004721 let temp_dir =
4722 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4723
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004724 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4725 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004726
4727 let _tx1 = db1
4728 .conn
4729 .transaction_with_behavior(TransactionBehavior::Immediate)
4730 .expect("Failed to create first transaction.");
4731
4732 let error = db2
4733 .conn
4734 .transaction_with_behavior(TransactionBehavior::Immediate)
4735 .context("Transaction begin failed.")
4736 .expect_err("This should fail.");
4737 let root_cause = error.root_cause();
4738 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4739 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4740 {
4741 return;
4742 }
4743 panic!(
4744 "Unexpected error {:?} \n{:?} \n{:?}",
4745 error,
4746 root_cause,
4747 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4748 )
4749 }
4750
4751 #[cfg(disabled)]
4752 #[test]
4753 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4754 let temp_dir = Arc::new(
4755 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4756 .expect("Failed to create temp dir."),
4757 );
4758
4759 let test_begin = Instant::now();
4760
4761 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4762 const KEY_COUNT: u32 = 500u32;
4763 const OPEN_DB_COUNT: u32 = 50u32;
4764
4765 let mut actual_key_count = KEY_COUNT;
4766 // First insert KEY_COUNT keys.
4767 for count in 0..KEY_COUNT {
4768 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4769 actual_key_count = count;
4770 break;
4771 }
4772 let alias = format!("test_alias_{}", count);
4773 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4774 .expect("Failed to make key entry.");
4775 }
4776
4777 // Insert more keys from a different thread and into a different namespace.
4778 let temp_dir1 = temp_dir.clone();
4779 let handle1 = thread::spawn(move || {
4780 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4781
4782 for count in 0..actual_key_count {
4783 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4784 return;
4785 }
4786 let alias = format!("test_alias_{}", count);
4787 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4788 .expect("Failed to make key entry.");
4789 }
4790
4791 // then unbind them again.
4792 for count in 0..actual_key_count {
4793 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4794 return;
4795 }
4796 let key = KeyDescriptor {
4797 domain: Domain::APP,
4798 nspace: -1,
4799 alias: Some(format!("test_alias_{}", count)),
4800 blob: None,
4801 };
4802 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4803 }
4804 });
4805
4806 // And start unbinding the first set of keys.
4807 let temp_dir2 = temp_dir.clone();
4808 let handle2 = thread::spawn(move || {
4809 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4810
4811 for count in 0..actual_key_count {
4812 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4813 return;
4814 }
4815 let key = KeyDescriptor {
4816 domain: Domain::APP,
4817 nspace: -1,
4818 alias: Some(format!("test_alias_{}", count)),
4819 blob: None,
4820 };
4821 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4822 }
4823 });
4824
4825 let stop_deleting = Arc::new(AtomicU8::new(0));
4826 let stop_deleting2 = stop_deleting.clone();
4827
4828 // And delete anything that is unreferenced keys.
4829 let temp_dir3 = temp_dir.clone();
4830 let handle3 = thread::spawn(move || {
4831 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4832
4833 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4834 while let Some((key_guard, _key)) =
4835 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4836 {
4837 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4838 return;
4839 }
4840 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4841 }
4842 std::thread::sleep(std::time::Duration::from_millis(100));
4843 }
4844 });
4845
4846 // While a lot of inserting and deleting is going on we have to open database connections
4847 // successfully and use them.
4848 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4849 // out of scope.
4850 #[allow(clippy::redundant_clone)]
4851 let temp_dir4 = temp_dir.clone();
4852 let handle4 = thread::spawn(move || {
4853 for count in 0..OPEN_DB_COUNT {
4854 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4855 return;
4856 }
4857 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4858
4859 let alias = format!("test_alias_{}", count);
4860 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4861 .expect("Failed to make key entry.");
4862 let key = KeyDescriptor {
4863 domain: Domain::APP,
4864 nspace: -1,
4865 alias: Some(alias),
4866 blob: None,
4867 };
4868 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4869 }
4870 });
4871
4872 handle1.join().expect("Thread 1 panicked.");
4873 handle2.join().expect("Thread 2 panicked.");
4874 handle4.join().expect("Thread 4 panicked.");
4875
4876 stop_deleting.store(1, Ordering::Relaxed);
4877 handle3.join().expect("Thread 3 panicked.");
4878
4879 Ok(())
4880 }
4881
4882 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004883 fn list() -> Result<()> {
4884 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004885 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004886 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4887 (Domain::APP, 1, "test1"),
4888 (Domain::APP, 1, "test2"),
4889 (Domain::APP, 1, "test3"),
4890 (Domain::APP, 1, "test4"),
4891 (Domain::APP, 1, "test5"),
4892 (Domain::APP, 1, "test6"),
4893 (Domain::APP, 1, "test7"),
4894 (Domain::APP, 2, "test1"),
4895 (Domain::APP, 2, "test2"),
4896 (Domain::APP, 2, "test3"),
4897 (Domain::APP, 2, "test4"),
4898 (Domain::APP, 2, "test5"),
4899 (Domain::APP, 2, "test6"),
4900 (Domain::APP, 2, "test8"),
4901 (Domain::SELINUX, 100, "test1"),
4902 (Domain::SELINUX, 100, "test2"),
4903 (Domain::SELINUX, 100, "test3"),
4904 (Domain::SELINUX, 100, "test4"),
4905 (Domain::SELINUX, 100, "test5"),
4906 (Domain::SELINUX, 100, "test6"),
4907 (Domain::SELINUX, 100, "test9"),
4908 ];
4909
4910 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4911 .iter()
4912 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004913 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4914 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004915 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4916 });
4917 (entry.id(), *ns)
4918 })
4919 .collect();
4920
4921 for (domain, namespace) in
4922 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4923 {
4924 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4925 .iter()
4926 .filter_map(|(domain, ns, alias)| match ns {
4927 ns if *ns == *namespace => Some(KeyDescriptor {
4928 domain: *domain,
4929 nspace: *ns,
4930 alias: Some(alias.to_string()),
4931 blob: None,
4932 }),
4933 _ => None,
4934 })
4935 .collect();
4936 list_o_descriptors.sort();
Janis Danisevskisc2c856e2021-05-17 13:30:32 -07004937 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004938 list_result.sort();
4939 assert_eq!(list_o_descriptors, list_result);
4940
4941 let mut list_o_ids: Vec<i64> = list_o_descriptors
4942 .into_iter()
4943 .map(|d| {
4944 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004945 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004946 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004947 KeyType::Client,
4948 KeyEntryLoadBits::NONE,
4949 *namespace as u32,
4950 |_, _| Ok(()),
4951 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004952 .unwrap();
4953 entry.id()
4954 })
4955 .collect();
4956 list_o_ids.sort_unstable();
4957 let mut loaded_entries: Vec<i64> = list_o_keys
4958 .iter()
4959 .filter_map(|(id, ns)| match ns {
4960 ns if *ns == *namespace => Some(*id),
4961 _ => None,
4962 })
4963 .collect();
4964 loaded_entries.sort_unstable();
4965 assert_eq!(list_o_ids, loaded_entries);
4966 }
Janis Danisevskisc2c856e2021-05-17 13:30:32 -07004967 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004968
4969 Ok(())
4970 }
4971
Joel Galenson0891bc12020-07-20 10:37:03 -07004972 // Helpers
4973
4974 // Checks that the given result is an error containing the given string.
4975 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4976 let error_str = format!(
4977 "{:#?}",
4978 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4979 );
4980 assert!(
4981 error_str.contains(target),
4982 "The string \"{}\" should contain \"{}\"",
4983 error_str,
4984 target
4985 );
4986 }
4987
Joel Galenson2aab4432020-07-22 15:27:57 -07004988 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004989 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004990 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004991 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004992 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004993 namespace: Option<i64>,
4994 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004995 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004996 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004997 }
4998
4999 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
5000 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07005001 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07005002 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07005003 Ok(KeyEntryRow {
5004 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005005 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005006 domain: match row.get(2)? {
5007 Some(i) => Some(Domain(i)),
5008 None => None,
5009 },
Joel Galenson0891bc12020-07-20 10:37:03 -07005010 namespace: row.get(3)?,
5011 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005012 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08005013 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07005014 })
5015 })?
5016 .map(|r| r.context("Could not read keyentry row."))
5017 .collect::<Result<Vec<_>>>()
5018 }
5019
Max Biresb2e1d032021-02-08 21:35:05 -08005020 struct RemoteProvValues {
5021 cert_chain: Vec<u8>,
5022 priv_key: Vec<u8>,
5023 batch_cert: Vec<u8>,
5024 }
5025
Max Bires2b2e6562020-09-22 11:22:36 -07005026 fn load_attestation_key_pool(
5027 db: &mut KeystoreDB,
5028 expiration_date: i64,
5029 namespace: i64,
5030 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08005031 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07005032 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
5033 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
5034 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5035 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005036 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005037 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5038 db.store_signed_attestation_certificate_chain(
5039 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005040 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005041 &cert_chain,
5042 expiration_date,
5043 &KEYSTORE_UUID,
5044 )?;
5045 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005046 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005047 }
5048
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005049 // Note: The parameters and SecurityLevel associations are nonsensical. This
5050 // collection is only used to check if the parameters are preserved as expected by the
5051 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005052 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5053 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005054 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5055 KeyParameter::new(
5056 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5057 SecurityLevel::TRUSTED_ENVIRONMENT,
5058 ),
5059 KeyParameter::new(
5060 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5061 SecurityLevel::TRUSTED_ENVIRONMENT,
5062 ),
5063 KeyParameter::new(
5064 KeyParameterValue::Algorithm(Algorithm::RSA),
5065 SecurityLevel::TRUSTED_ENVIRONMENT,
5066 ),
5067 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5068 KeyParameter::new(
5069 KeyParameterValue::BlockMode(BlockMode::ECB),
5070 SecurityLevel::TRUSTED_ENVIRONMENT,
5071 ),
5072 KeyParameter::new(
5073 KeyParameterValue::BlockMode(BlockMode::GCM),
5074 SecurityLevel::TRUSTED_ENVIRONMENT,
5075 ),
5076 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5077 KeyParameter::new(
5078 KeyParameterValue::Digest(Digest::MD5),
5079 SecurityLevel::TRUSTED_ENVIRONMENT,
5080 ),
5081 KeyParameter::new(
5082 KeyParameterValue::Digest(Digest::SHA_2_224),
5083 SecurityLevel::TRUSTED_ENVIRONMENT,
5084 ),
5085 KeyParameter::new(
5086 KeyParameterValue::Digest(Digest::SHA_2_256),
5087 SecurityLevel::STRONGBOX,
5088 ),
5089 KeyParameter::new(
5090 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5091 SecurityLevel::TRUSTED_ENVIRONMENT,
5092 ),
5093 KeyParameter::new(
5094 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5095 SecurityLevel::TRUSTED_ENVIRONMENT,
5096 ),
5097 KeyParameter::new(
5098 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5099 SecurityLevel::STRONGBOX,
5100 ),
5101 KeyParameter::new(
5102 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5103 SecurityLevel::TRUSTED_ENVIRONMENT,
5104 ),
5105 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5106 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5107 KeyParameter::new(
5108 KeyParameterValue::EcCurve(EcCurve::P_224),
5109 SecurityLevel::TRUSTED_ENVIRONMENT,
5110 ),
5111 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5112 KeyParameter::new(
5113 KeyParameterValue::EcCurve(EcCurve::P_384),
5114 SecurityLevel::TRUSTED_ENVIRONMENT,
5115 ),
5116 KeyParameter::new(
5117 KeyParameterValue::EcCurve(EcCurve::P_521),
5118 SecurityLevel::TRUSTED_ENVIRONMENT,
5119 ),
5120 KeyParameter::new(
5121 KeyParameterValue::RSAPublicExponent(3),
5122 SecurityLevel::TRUSTED_ENVIRONMENT,
5123 ),
5124 KeyParameter::new(
5125 KeyParameterValue::IncludeUniqueID,
5126 SecurityLevel::TRUSTED_ENVIRONMENT,
5127 ),
5128 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5129 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5130 KeyParameter::new(
5131 KeyParameterValue::ActiveDateTime(1234567890),
5132 SecurityLevel::STRONGBOX,
5133 ),
5134 KeyParameter::new(
5135 KeyParameterValue::OriginationExpireDateTime(1234567890),
5136 SecurityLevel::TRUSTED_ENVIRONMENT,
5137 ),
5138 KeyParameter::new(
5139 KeyParameterValue::UsageExpireDateTime(1234567890),
5140 SecurityLevel::TRUSTED_ENVIRONMENT,
5141 ),
5142 KeyParameter::new(
5143 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5144 SecurityLevel::TRUSTED_ENVIRONMENT,
5145 ),
5146 KeyParameter::new(
5147 KeyParameterValue::MaxUsesPerBoot(1234567890),
5148 SecurityLevel::TRUSTED_ENVIRONMENT,
5149 ),
5150 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5151 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5152 KeyParameter::new(
5153 KeyParameterValue::NoAuthRequired,
5154 SecurityLevel::TRUSTED_ENVIRONMENT,
5155 ),
5156 KeyParameter::new(
5157 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5158 SecurityLevel::TRUSTED_ENVIRONMENT,
5159 ),
5160 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5161 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5162 KeyParameter::new(
5163 KeyParameterValue::TrustedUserPresenceRequired,
5164 SecurityLevel::TRUSTED_ENVIRONMENT,
5165 ),
5166 KeyParameter::new(
5167 KeyParameterValue::TrustedConfirmationRequired,
5168 SecurityLevel::TRUSTED_ENVIRONMENT,
5169 ),
5170 KeyParameter::new(
5171 KeyParameterValue::UnlockedDeviceRequired,
5172 SecurityLevel::TRUSTED_ENVIRONMENT,
5173 ),
5174 KeyParameter::new(
5175 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5176 SecurityLevel::SOFTWARE,
5177 ),
5178 KeyParameter::new(
5179 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5180 SecurityLevel::SOFTWARE,
5181 ),
5182 KeyParameter::new(
5183 KeyParameterValue::CreationDateTime(12345677890),
5184 SecurityLevel::SOFTWARE,
5185 ),
5186 KeyParameter::new(
5187 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5188 SecurityLevel::TRUSTED_ENVIRONMENT,
5189 ),
5190 KeyParameter::new(
5191 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5192 SecurityLevel::TRUSTED_ENVIRONMENT,
5193 ),
5194 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5195 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5196 KeyParameter::new(
5197 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5198 SecurityLevel::SOFTWARE,
5199 ),
5200 KeyParameter::new(
5201 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5202 SecurityLevel::TRUSTED_ENVIRONMENT,
5203 ),
5204 KeyParameter::new(
5205 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5206 SecurityLevel::TRUSTED_ENVIRONMENT,
5207 ),
5208 KeyParameter::new(
5209 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5210 SecurityLevel::TRUSTED_ENVIRONMENT,
5211 ),
5212 KeyParameter::new(
5213 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5214 SecurityLevel::TRUSTED_ENVIRONMENT,
5215 ),
5216 KeyParameter::new(
5217 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5218 SecurityLevel::TRUSTED_ENVIRONMENT,
5219 ),
5220 KeyParameter::new(
5221 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5222 SecurityLevel::TRUSTED_ENVIRONMENT,
5223 ),
5224 KeyParameter::new(
5225 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5226 SecurityLevel::TRUSTED_ENVIRONMENT,
5227 ),
5228 KeyParameter::new(
5229 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5230 SecurityLevel::TRUSTED_ENVIRONMENT,
5231 ),
5232 KeyParameter::new(
5233 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5234 SecurityLevel::TRUSTED_ENVIRONMENT,
5235 ),
5236 KeyParameter::new(
5237 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5238 SecurityLevel::TRUSTED_ENVIRONMENT,
5239 ),
5240 KeyParameter::new(
5241 KeyParameterValue::VendorPatchLevel(3),
5242 SecurityLevel::TRUSTED_ENVIRONMENT,
5243 ),
5244 KeyParameter::new(
5245 KeyParameterValue::BootPatchLevel(4),
5246 SecurityLevel::TRUSTED_ENVIRONMENT,
5247 ),
5248 KeyParameter::new(
5249 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5250 SecurityLevel::TRUSTED_ENVIRONMENT,
5251 ),
5252 KeyParameter::new(
5253 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5254 SecurityLevel::TRUSTED_ENVIRONMENT,
5255 ),
5256 KeyParameter::new(
5257 KeyParameterValue::MacLength(256),
5258 SecurityLevel::TRUSTED_ENVIRONMENT,
5259 ),
5260 KeyParameter::new(
5261 KeyParameterValue::ResetSinceIdRotation,
5262 SecurityLevel::TRUSTED_ENVIRONMENT,
5263 ),
5264 KeyParameter::new(
5265 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5266 SecurityLevel::TRUSTED_ENVIRONMENT,
5267 ),
Qi Wub9433b52020-12-01 14:52:46 +08005268 ];
5269 if let Some(value) = max_usage_count {
5270 params.push(KeyParameter::new(
5271 KeyParameterValue::UsageCountLimit(value),
5272 SecurityLevel::SOFTWARE,
5273 ));
5274 }
5275 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005276 }
5277
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005278 fn make_test_key_entry(
5279 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005280 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005281 namespace: i64,
5282 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005283 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005284 ) -> Result<KeyIdGuard> {
Janis Danisevskis10b79f52021-05-25 11:07:10 -07005285 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005286 let mut blob_metadata = BlobMetaData::new();
5287 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5288 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5289 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5290 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5291 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5292
5293 db.set_blob(
5294 &key_id,
5295 SubComponentType::KEY_BLOB,
5296 Some(TEST_KEY_BLOB),
5297 Some(&blob_metadata),
5298 )?;
5299 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5300 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005301
5302 let params = make_test_params(max_usage_count);
5303 db.insert_keyparameter(&key_id, &params)?;
5304
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005305 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005306 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005307 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005308 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005309 Ok(key_id)
5310 }
5311
Qi Wub9433b52020-12-01 14:52:46 +08005312 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5313 let params = make_test_params(max_usage_count);
5314
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005315 let mut blob_metadata = BlobMetaData::new();
5316 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5317 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5318 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5319 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5320 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5321
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005322 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005323 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005324
5325 KeyEntry {
5326 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005327 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005328 cert: Some(TEST_CERT_BLOB.to_vec()),
5329 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005330 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005331 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005332 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005333 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005334 }
5335 }
5336
Janis Danisevskis97c83872021-05-26 16:31:02 -07005337 fn make_bootlevel_key_entry(
5338 db: &mut KeystoreDB,
5339 domain: Domain,
5340 namespace: i64,
5341 alias: &str,
5342 logical_only: bool,
5343 ) -> Result<KeyIdGuard> {
5344 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5345 let mut blob_metadata = BlobMetaData::new();
5346 if !logical_only {
5347 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5348 }
5349 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5350
5351 db.set_blob(
5352 &key_id,
5353 SubComponentType::KEY_BLOB,
5354 Some(TEST_KEY_BLOB),
5355 Some(&blob_metadata),
5356 )?;
5357 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5358 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5359
5360 let mut params = make_test_params(None);
5361 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5362
5363 db.insert_keyparameter(&key_id, &params)?;
5364
5365 let mut metadata = KeyMetaData::new();
5366 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5367 db.insert_key_metadata(&key_id, &metadata)?;
5368 rebind_alias(db, &key_id, alias, domain, namespace)?;
5369 Ok(key_id)
5370 }
5371
5372 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5373 let mut params = make_test_params(None);
5374 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5375
5376 let mut blob_metadata = BlobMetaData::new();
5377 if !logical_only {
5378 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5379 }
5380 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5381
5382 let mut metadata = KeyMetaData::new();
5383 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5384
5385 KeyEntry {
5386 id: key_id,
5387 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5388 cert: Some(TEST_CERT_BLOB.to_vec()),
5389 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5390 km_uuid: KEYSTORE_UUID,
5391 parameters: params,
5392 metadata,
5393 pure_cert: false,
5394 }
5395 }
5396
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005397 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005398 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005399 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005400 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005401 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005402 NO_PARAMS,
5403 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005404 Ok((
5405 row.get(0)?,
5406 row.get(1)?,
5407 row.get(2)?,
5408 row.get(3)?,
5409 row.get(4)?,
5410 row.get(5)?,
5411 row.get(6)?,
5412 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005413 },
5414 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005415
5416 println!("Key entry table rows:");
5417 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005418 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005419 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005420 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5421 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005422 );
5423 }
5424 Ok(())
5425 }
5426
5427 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005428 let mut stmt = db
5429 .conn
5430 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005431 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5432 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5433 })?;
5434
5435 println!("Grant table rows:");
5436 for r in rows {
5437 let (id, gt, ki, av) = r.unwrap();
5438 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5439 }
5440 Ok(())
5441 }
5442
Joel Galenson0891bc12020-07-20 10:37:03 -07005443 // Use a custom random number generator that repeats each number once.
5444 // This allows us to test repeated elements.
5445
5446 thread_local! {
5447 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5448 }
5449
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005450 fn reset_random() {
5451 RANDOM_COUNTER.with(|counter| {
5452 *counter.borrow_mut() = 0;
5453 })
5454 }
5455
Joel Galenson0891bc12020-07-20 10:37:03 -07005456 pub fn random() -> i64 {
5457 RANDOM_COUNTER.with(|counter| {
5458 let result = *counter.borrow() / 2;
5459 *counter.borrow_mut() += 1;
5460 result
5461 })
5462 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005463
5464 #[test]
5465 fn test_last_off_body() -> Result<()> {
5466 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005467 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005468 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005469 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005470 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005471 let one_second = Duration::from_secs(1);
5472 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005473 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005474 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005475 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005476 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005477 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005478 Ok(())
5479 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005480
5481 #[test]
5482 fn test_unbind_keys_for_user() -> Result<()> {
5483 let mut db = new_test_db()?;
5484 db.unbind_keys_for_user(1, false)?;
5485
5486 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5487 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5488 db.unbind_keys_for_user(2, false)?;
5489
Janis Danisevskisc2c856e2021-05-17 13:30:32 -07005490 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5491 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005492
5493 db.unbind_keys_for_user(1, true)?;
Janis Danisevskisc2c856e2021-05-17 13:30:32 -07005494 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005495
5496 Ok(())
5497 }
5498
5499 #[test]
5500 fn test_store_super_key() -> Result<()> {
5501 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005502 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005503 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005504 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005505 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005506 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005507
5508 let (encrypted_super_key, metadata) =
5509 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005510 db.store_super_key(
5511 1,
5512 &USER_SUPER_KEY,
5513 &encrypted_super_key,
5514 &metadata,
5515 &KeyMetaData::new(),
5516 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005517
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005518 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005519 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005520
Paul Crowley7a658392021-03-18 17:08:20 -07005521 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005522 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5523 USER_SUPER_KEY.algorithm,
5524 key_entry,
5525 &pw,
5526 None,
5527 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005528
Paul Crowley7a658392021-03-18 17:08:20 -07005529 let decrypted_secret_bytes =
5530 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5531 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005532 Ok(())
5533 }
Seth Moore78c091f2021-04-09 21:38:30 +00005534
5535 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5536 vec![
5537 StatsdStorageType::KeyEntry,
5538 StatsdStorageType::KeyEntryIdIndex,
5539 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5540 StatsdStorageType::BlobEntry,
5541 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5542 StatsdStorageType::KeyParameter,
5543 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5544 StatsdStorageType::KeyMetadata,
5545 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5546 StatsdStorageType::Grant,
5547 StatsdStorageType::AuthToken,
5548 StatsdStorageType::BlobMetadata,
5549 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5550 ]
5551 }
5552
5553 /// Perform a simple check to ensure that we can query all the storage types
5554 /// that are supported by the DB. Check for reasonable values.
5555 #[test]
5556 fn test_query_all_valid_table_sizes() -> Result<()> {
5557 const PAGE_SIZE: i64 = 4096;
5558
5559 let mut db = new_test_db()?;
5560
5561 for t in get_valid_statsd_storage_types() {
5562 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005563 // AuthToken can be less than a page since it's in a btree, not sqlite
5564 // TODO(b/187474736) stop using if-let here
5565 if let StatsdStorageType::AuthToken = t {
5566 } else {
5567 assert!(stat.size >= PAGE_SIZE);
5568 }
Seth Moore78c091f2021-04-09 21:38:30 +00005569 assert!(stat.size >= stat.unused_size);
5570 }
5571
5572 Ok(())
5573 }
5574
5575 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5576 get_valid_statsd_storage_types()
5577 .into_iter()
5578 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5579 .collect()
5580 }
5581
5582 fn assert_storage_increased(
5583 db: &mut KeystoreDB,
5584 increased_storage_types: Vec<StatsdStorageType>,
5585 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5586 ) {
5587 for storage in increased_storage_types {
5588 // Verify the expected storage increased.
5589 let new = db.get_storage_stat(storage).unwrap();
5590 let storage = storage as i32;
5591 let old = &baseline[&storage];
5592 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5593 assert!(
5594 new.unused_size <= old.unused_size,
5595 "{}: {} <= {}",
5596 storage,
5597 new.unused_size,
5598 old.unused_size
5599 );
5600
5601 // Update the baseline with the new value so that it succeeds in the
5602 // later comparison.
5603 baseline.insert(storage, new);
5604 }
5605
5606 // Get an updated map of the storage and verify there were no unexpected changes.
5607 let updated_stats = get_storage_stats_map(db);
5608 assert_eq!(updated_stats.len(), baseline.len());
5609
5610 for &k in baseline.keys() {
5611 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5612 let mut s = String::new();
5613 for &k in map.keys() {
5614 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5615 .expect("string concat failed");
5616 }
5617 s
5618 };
5619
5620 assert!(
5621 updated_stats[&k].size == baseline[&k].size
5622 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5623 "updated_stats:\n{}\nbaseline:\n{}",
5624 stringify(&updated_stats),
5625 stringify(&baseline)
5626 );
5627 }
5628 }
5629
5630 #[test]
5631 fn test_verify_key_table_size_reporting() -> Result<()> {
5632 let mut db = new_test_db()?;
5633 let mut working_stats = get_storage_stats_map(&mut db);
5634
Janis Danisevskis10b79f52021-05-25 11:07:10 -07005635 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005636 assert_storage_increased(
5637 &mut db,
5638 vec![
5639 StatsdStorageType::KeyEntry,
5640 StatsdStorageType::KeyEntryIdIndex,
5641 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5642 ],
5643 &mut working_stats,
5644 );
5645
5646 let mut blob_metadata = BlobMetaData::new();
5647 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5648 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5649 assert_storage_increased(
5650 &mut db,
5651 vec![
5652 StatsdStorageType::BlobEntry,
5653 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5654 StatsdStorageType::BlobMetadata,
5655 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5656 ],
5657 &mut working_stats,
5658 );
5659
5660 let params = make_test_params(None);
5661 db.insert_keyparameter(&key_id, &params)?;
5662 assert_storage_increased(
5663 &mut db,
5664 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5665 &mut working_stats,
5666 );
5667
5668 let mut metadata = KeyMetaData::new();
5669 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5670 db.insert_key_metadata(&key_id, &metadata)?;
5671 assert_storage_increased(
5672 &mut db,
5673 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5674 &mut working_stats,
5675 );
5676
5677 let mut sum = 0;
5678 for stat in working_stats.values() {
5679 sum += stat.size;
5680 }
5681 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5682 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5683
5684 Ok(())
5685 }
5686
5687 #[test]
5688 fn test_verify_auth_table_size_reporting() -> Result<()> {
5689 let mut db = new_test_db()?;
5690 let mut working_stats = get_storage_stats_map(&mut db);
5691 db.insert_auth_token(&HardwareAuthToken {
5692 challenge: 123,
5693 userId: 456,
5694 authenticatorId: 789,
5695 authenticatorType: kmhw_authenticator_type::ANY,
5696 timestamp: Timestamp { milliSeconds: 10 },
5697 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005698 });
Seth Moore78c091f2021-04-09 21:38:30 +00005699 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5700 Ok(())
5701 }
5702
5703 #[test]
5704 fn test_verify_grant_table_size_reporting() -> Result<()> {
5705 const OWNER: i64 = 1;
5706 let mut db = new_test_db()?;
5707 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5708
5709 let mut working_stats = get_storage_stats_map(&mut db);
5710 db.grant(
5711 &KeyDescriptor {
5712 domain: Domain::APP,
5713 nspace: 0,
5714 alias: Some(TEST_ALIAS.to_string()),
5715 blob: None,
5716 },
5717 OWNER as u32,
5718 123,
5719 key_perm_set![KeyPerm::use_()],
5720 |_, _| Ok(()),
5721 )?;
5722
5723 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5724
5725 Ok(())
5726 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005727
5728 #[test]
5729 fn find_auth_token_entry_returns_latest() -> Result<()> {
5730 let mut db = new_test_db()?;
5731 db.insert_auth_token(&HardwareAuthToken {
5732 challenge: 123,
5733 userId: 456,
5734 authenticatorId: 789,
5735 authenticatorType: kmhw_authenticator_type::ANY,
5736 timestamp: Timestamp { milliSeconds: 10 },
5737 mac: b"mac0".to_vec(),
5738 });
5739 std::thread::sleep(std::time::Duration::from_millis(1));
5740 db.insert_auth_token(&HardwareAuthToken {
5741 challenge: 123,
5742 userId: 457,
5743 authenticatorId: 789,
5744 authenticatorType: kmhw_authenticator_type::ANY,
5745 timestamp: Timestamp { milliSeconds: 12 },
5746 mac: b"mac1".to_vec(),
5747 });
5748 std::thread::sleep(std::time::Duration::from_millis(1));
5749 db.insert_auth_token(&HardwareAuthToken {
5750 challenge: 123,
5751 userId: 458,
5752 authenticatorId: 789,
5753 authenticatorType: kmhw_authenticator_type::ANY,
5754 timestamp: Timestamp { milliSeconds: 3 },
5755 mac: b"mac2".to_vec(),
5756 });
5757 // All three entries are in the database
5758 assert_eq!(db.perboot.auth_tokens_len(), 3);
5759 // It selected the most recent timestamp
5760 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5761 Ok(())
5762 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005763
5764 #[test]
5765 fn test_set_wal_mode() -> Result<()> {
5766 let temp_dir = TempDir::new("test_set_wal_mode")?;
5767 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5768 let mode: String =
5769 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5770 row.get(0)
5771 })?;
5772 assert_eq!(mode, "delete");
5773 db.conn.close().expect("Close didn't work");
5774
5775 KeystoreDB::set_wal_mode(temp_dir.path())?;
5776
5777 db = KeystoreDB::new(temp_dir.path(), None)?;
5778 let mode: String =
5779 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5780 row.get(0)
5781 })?;
5782 assert_eq!(mode, "wal");
5783 Ok(())
5784 }
Pavel Grafov1ff6cd32021-05-12 22:35:45 +01005785
5786 #[test]
5787 fn test_load_key_descriptor() -> Result<()> {
5788 let mut db = new_test_db()?;
5789 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5790
5791 let key = db.load_key_descriptor(key_id)?.unwrap();
5792
5793 assert_eq!(key.domain, Domain::APP);
5794 assert_eq!(key.nspace, 1);
5795 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5796
5797 // No such id
5798 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5799 Ok(())
5800 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005801}