blob: e1185f32015d6297ebf20f3bd1ef0141998b562f [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
Janis Danisevskisb42fc182020-12-15 08:41:27 -080044use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080045use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070046use crate::permission::KeyPermSet;
Janis Danisevskis850d4862021-05-05 08:41:14 -070047use crate::utils::{get_current_time_in_seconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080048use crate::{
49 db_utils::{self, SqlField},
50 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070051 super_key::USER_SUPER_KEY,
52};
53use crate::{
54 error::{Error as KsError, ErrorCode, ResponseCode},
55 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080056};
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 Danisevskis60400fe2020-08-26 15:24:42 -070059
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000060use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080061 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000062 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080063};
64use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000065 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000066};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070067use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070068 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070069};
Max Bires2b2e6562020-09-22 11:22:36 -070070use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
71 AttestationPoolStatus::AttestationPoolStatus,
72};
Seth Moore78c091f2021-04-09 21:38:30 +000073use statslog_rust::keystore2_storage_stats::{
74 Keystore2StorageStats, StorageType as StatsdStorageType,
75};
Max Bires2b2e6562020-09-22 11:22:36 -070076
77use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080078use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000079use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070080#[cfg(not(test))]
81use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070082use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080083 params,
84 types::FromSql,
85 types::FromSqlResult,
86 types::ToSqlOutput,
87 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080088 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070089};
Max Bires2b2e6562020-09-22 11:22:36 -070090
Janis Danisevskisaec14592020-11-12 09:41:49 -080091use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080093 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070094 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080095 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080096};
Max Bires2b2e6562020-09-22 11:22:36 -070097
Joel Galenson0891bc12020-07-20 10:37:03 -070098#[cfg(test)]
99use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -0700100
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800101impl_metadata!(
102 /// A set of metadata for key entries.
103 #[derive(Debug, Default, Eq, PartialEq)]
104 pub struct KeyMetaData;
105 /// A metadata entry for key entries.
106 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
107 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800108 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800109 CreationDate(DateTime) with accessor creation_date,
110 /// Expiration date for attestation keys.
111 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700112 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
113 /// provisioning
114 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
115 /// Vector representing the raw public key so results from the server can be matched
116 /// to the right entry
117 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700118 /// SEC1 public key for ECDH encryption
119 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800120 // --- ADD NEW META DATA FIELDS HERE ---
121 // For backwards compatibility add new entries only to
122 // end of this list and above this comment.
123 };
124);
125
126impl KeyMetaData {
127 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
128 let mut stmt = tx
129 .prepare(
130 "SELECT tag, data from persistent.keymetadata
131 WHERE keyentryid = ?;",
132 )
133 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
134
135 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
136
137 let mut rows =
138 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
139 db_utils::with_rows_extract_all(&mut rows, |row| {
140 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
141 metadata.insert(
142 db_tag,
143 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
144 .context("Failed to read KeyMetaEntry.")?,
145 );
146 Ok(())
147 })
148 .context("In KeyMetaData::load_from_db.")?;
149
150 Ok(Self { data: metadata })
151 }
152
153 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
154 let mut stmt = tx
155 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000156 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800157 VALUES (?, ?, ?);",
158 )
159 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
160
161 let iter = self.data.iter();
162 for (tag, entry) in iter {
163 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
164 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
165 })?;
166 }
167 Ok(())
168 }
169}
170
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800171impl_metadata!(
172 /// A set of metadata for key blobs.
173 #[derive(Debug, Default, Eq, PartialEq)]
174 pub struct BlobMetaData;
175 /// A metadata entry for key blobs.
176 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
177 pub enum BlobMetaEntry {
178 /// If present, indicates that the blob is encrypted with another key or a key derived
179 /// from a password.
180 EncryptedBy(EncryptedBy) with accessor encrypted_by,
181 /// If the blob is password encrypted this field is set to the
182 /// salt used for the key derivation.
183 Salt(Vec<u8>) with accessor salt,
184 /// If the blob is encrypted, this field is set to the initialization vector.
185 Iv(Vec<u8>) with accessor iv,
186 /// If the blob is encrypted, this field holds the AEAD TAG.
187 AeadTag(Vec<u8>) with accessor aead_tag,
188 /// The uuid of the owning KeyMint instance.
189 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700190 /// If the key is ECDH encrypted, this is the ephemeral public key
191 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000192 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
193 /// of that key
194 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800195 // --- ADD NEW META DATA FIELDS HERE ---
196 // For backwards compatibility add new entries only to
197 // end of this list and above this comment.
198 };
199);
200
201impl BlobMetaData {
202 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
203 let mut stmt = tx
204 .prepare(
205 "SELECT tag, data from persistent.blobmetadata
206 WHERE blobentryid = ?;",
207 )
208 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
209
210 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
211
212 let mut rows =
213 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
214 db_utils::with_rows_extract_all(&mut rows, |row| {
215 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
216 metadata.insert(
217 db_tag,
218 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
219 .context("Failed to read BlobMetaEntry.")?,
220 );
221 Ok(())
222 })
223 .context("In BlobMetaData::load_from_db.")?;
224
225 Ok(Self { data: metadata })
226 }
227
228 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
229 let mut stmt = tx
230 .prepare(
231 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
232 VALUES (?, ?, ?);",
233 )
234 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
235
236 let iter = self.data.iter();
237 for (tag, entry) in iter {
238 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
239 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
240 })?;
241 }
242 Ok(())
243 }
244}
245
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800246/// Indicates the type of the keyentry.
247#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
248pub enum KeyType {
249 /// This is a client key type. These keys are created or imported through the Keystore 2.0
250 /// AIDL interface android.system.keystore2.
251 Client,
252 /// This is a super key type. These keys are created by keystore itself and used to encrypt
253 /// other key blobs to provide LSKF binding.
254 Super,
255 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
256 Attestation,
257}
258
259impl ToSql for KeyType {
260 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
261 Ok(ToSqlOutput::Owned(Value::Integer(match self {
262 KeyType::Client => 0,
263 KeyType::Super => 1,
264 KeyType::Attestation => 2,
265 })))
266 }
267}
268
269impl FromSql for KeyType {
270 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
271 match i64::column_result(value)? {
272 0 => Ok(KeyType::Client),
273 1 => Ok(KeyType::Super),
274 2 => Ok(KeyType::Attestation),
275 v => Err(FromSqlError::OutOfRange(v)),
276 }
277 }
278}
279
Max Bires8e93d2b2021-01-14 13:17:59 -0800280/// Uuid representation that can be stored in the database.
281/// Right now it can only be initialized from SecurityLevel.
282/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
284pub struct Uuid([u8; 16]);
285
286impl Deref for Uuid {
287 type Target = [u8; 16];
288
289 fn deref(&self) -> &Self::Target {
290 &self.0
291 }
292}
293
294impl From<SecurityLevel> for Uuid {
295 fn from(sec_level: SecurityLevel) -> Self {
296 Self((sec_level.0 as u128).to_be_bytes())
297 }
298}
299
300impl ToSql for Uuid {
301 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
302 self.0.to_sql()
303 }
304}
305
306impl FromSql for Uuid {
307 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
308 let blob = Vec::<u8>::column_result(value)?;
309 if blob.len() != 16 {
310 return Err(FromSqlError::OutOfRange(blob.len() as i64));
311 }
312 let mut arr = [0u8; 16];
313 arr.copy_from_slice(&blob);
314 Ok(Self(arr))
315 }
316}
317
318/// Key entries that are not associated with any KeyMint instance, such as pure certificate
319/// entries are associated with this UUID.
320pub static KEYSTORE_UUID: Uuid = Uuid([
321 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
322]);
323
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800324/// Indicates how the sensitive part of this key blob is encrypted.
325#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
326pub enum EncryptedBy {
327 /// The keyblob is encrypted by a user password.
328 /// In the database this variant is represented as NULL.
329 Password,
330 /// The keyblob is encrypted by another key with wrapped key id.
331 /// In the database this variant is represented as non NULL value
332 /// that is convertible to i64, typically NUMERIC.
333 KeyId(i64),
334}
335
336impl ToSql for EncryptedBy {
337 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
338 match self {
339 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
340 Self::KeyId(id) => id.to_sql(),
341 }
342 }
343}
344
345impl FromSql for EncryptedBy {
346 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
347 match value {
348 ValueRef::Null => Ok(Self::Password),
349 _ => Ok(Self::KeyId(i64::column_result(value)?)),
350 }
351 }
352}
353
354/// A database representation of wall clock time. DateTime stores unix epoch time as
355/// i64 in milliseconds.
356#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
357pub struct DateTime(i64);
358
359/// Error type returned when creating DateTime or converting it from and to
360/// SystemTime.
361#[derive(thiserror::Error, Debug)]
362pub enum DateTimeError {
363 /// This is returned when SystemTime and Duration computations fail.
364 #[error(transparent)]
365 SystemTimeError(#[from] SystemTimeError),
366
367 /// This is returned when type conversions fail.
368 #[error(transparent)]
369 TypeConversion(#[from] std::num::TryFromIntError),
370
371 /// This is returned when checked time arithmetic failed.
372 #[error("Time arithmetic failed.")]
373 TimeArithmetic,
374}
375
376impl DateTime {
377 /// Constructs a new DateTime object denoting the current time. This may fail during
378 /// conversion to unix epoch time and during conversion to the internal i64 representation.
379 pub fn now() -> Result<Self, DateTimeError> {
380 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
381 }
382
383 /// Constructs a new DateTime object from milliseconds.
384 pub fn from_millis_epoch(millis: i64) -> Self {
385 Self(millis)
386 }
387
388 /// Returns unix epoch time in milliseconds.
389 pub fn to_millis_epoch(&self) -> i64 {
390 self.0
391 }
392
393 /// Returns unix epoch time in seconds.
394 pub fn to_secs_epoch(&self) -> i64 {
395 self.0 / 1000
396 }
397}
398
399impl ToSql for DateTime {
400 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
401 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
402 }
403}
404
405impl FromSql for DateTime {
406 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
407 Ok(Self(i64::column_result(value)?))
408 }
409}
410
411impl TryInto<SystemTime> for DateTime {
412 type Error = DateTimeError;
413
414 fn try_into(self) -> Result<SystemTime, Self::Error> {
415 // We want to construct a SystemTime representation equivalent to self, denoting
416 // a point in time THEN, but we cannot set the time directly. We can only construct
417 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
418 // and between EPOCH and THEN. With this common reference we can construct the
419 // duration between NOW and THEN which we can add to our SystemTime representation
420 // of NOW to get a SystemTime representation of THEN.
421 // Durations can only be positive, thus the if statement below.
422 let now = SystemTime::now();
423 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
424 let then_epoch = Duration::from_millis(self.0.try_into()?);
425 Ok(if now_epoch > then_epoch {
426 // then = now - (now_epoch - then_epoch)
427 now_epoch
428 .checked_sub(then_epoch)
429 .and_then(|d| now.checked_sub(d))
430 .ok_or(DateTimeError::TimeArithmetic)?
431 } else {
432 // then = now + (then_epoch - now_epoch)
433 then_epoch
434 .checked_sub(now_epoch)
435 .and_then(|d| now.checked_add(d))
436 .ok_or(DateTimeError::TimeArithmetic)?
437 })
438 }
439}
440
441impl TryFrom<SystemTime> for DateTime {
442 type Error = DateTimeError;
443
444 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
445 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
446 }
447}
448
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800449#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
450enum KeyLifeCycle {
451 /// Existing keys have a key ID but are not fully populated yet.
452 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
453 /// them to Unreferenced for garbage collection.
454 Existing,
455 /// A live key is fully populated and usable by clients.
456 Live,
457 /// An unreferenced key is scheduled for garbage collection.
458 Unreferenced,
459}
460
461impl ToSql for KeyLifeCycle {
462 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
463 match self {
464 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
465 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
466 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
467 }
468 }
469}
470
471impl FromSql for KeyLifeCycle {
472 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
473 match i64::column_result(value)? {
474 0 => Ok(KeyLifeCycle::Existing),
475 1 => Ok(KeyLifeCycle::Live),
476 2 => Ok(KeyLifeCycle::Unreferenced),
477 v => Err(FromSqlError::OutOfRange(v)),
478 }
479 }
480}
481
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700482/// Keys have a KeyMint blob component and optional public certificate and
483/// certificate chain components.
484/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
485/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800486#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700487pub struct KeyEntryLoadBits(u32);
488
489impl KeyEntryLoadBits {
490 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
491 pub const NONE: KeyEntryLoadBits = Self(0);
492 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
493 pub const KM: KeyEntryLoadBits = Self(1);
494 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
495 pub const PUBLIC: KeyEntryLoadBits = Self(2);
496 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
497 pub const BOTH: KeyEntryLoadBits = Self(3);
498
499 /// Returns true if this object indicates that the public components shall be loaded.
500 pub const fn load_public(&self) -> bool {
501 self.0 & Self::PUBLIC.0 != 0
502 }
503
504 /// Returns true if the object indicates that the KeyMint component shall be loaded.
505 pub const fn load_km(&self) -> bool {
506 self.0 & Self::KM.0 != 0
507 }
508}
509
Janis Danisevskisaec14592020-11-12 09:41:49 -0800510lazy_static! {
511 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
512}
513
514struct KeyIdLockDb {
515 locked_keys: Mutex<HashSet<i64>>,
516 cond_var: Condvar,
517}
518
519/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
520/// from the database a second time. Most functions manipulating the key blob database
521/// require a KeyIdGuard.
522#[derive(Debug)]
523pub struct KeyIdGuard(i64);
524
525impl KeyIdLockDb {
526 fn new() -> Self {
527 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
528 }
529
530 /// This function blocks until an exclusive lock for the given key entry id can
531 /// be acquired. It returns a guard object, that represents the lifecycle of the
532 /// acquired lock.
533 pub fn get(&self, key_id: i64) -> KeyIdGuard {
534 let mut locked_keys = self.locked_keys.lock().unwrap();
535 while locked_keys.contains(&key_id) {
536 locked_keys = self.cond_var.wait(locked_keys).unwrap();
537 }
538 locked_keys.insert(key_id);
539 KeyIdGuard(key_id)
540 }
541
542 /// This function attempts to acquire an exclusive lock on a given key id. If the
543 /// given key id is already taken the function returns None immediately. If a lock
544 /// can be acquired this function returns a guard object, that represents the
545 /// lifecycle of the acquired lock.
546 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
547 let mut locked_keys = self.locked_keys.lock().unwrap();
548 if locked_keys.insert(key_id) {
549 Some(KeyIdGuard(key_id))
550 } else {
551 None
552 }
553 }
554}
555
556impl KeyIdGuard {
557 /// Get the numeric key id of the locked key.
558 pub fn id(&self) -> i64 {
559 self.0
560 }
561}
562
563impl Drop for KeyIdGuard {
564 fn drop(&mut self) {
565 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
566 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800567 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800568 KEY_ID_LOCK.cond_var.notify_all();
569 }
570}
571
Max Bires8e93d2b2021-01-14 13:17:59 -0800572/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700573#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800574pub struct CertificateInfo {
575 cert: Option<Vec<u8>>,
576 cert_chain: Option<Vec<u8>>,
577}
578
579impl CertificateInfo {
580 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
581 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
582 Self { cert, cert_chain }
583 }
584
585 /// Take the cert
586 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
587 self.cert.take()
588 }
589
590 /// Take the cert chain
591 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
592 self.cert_chain.take()
593 }
594}
595
Max Bires2b2e6562020-09-22 11:22:36 -0700596/// This type represents a certificate chain with a private key corresponding to the leaf
597/// 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 -0700598pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800599 /// A KM key blob
600 pub private_key: ZVec,
601 /// A batch cert for private_key
602 pub batch_cert: Vec<u8>,
603 /// A full certificate chain from root signing authority to private_key, including batch_cert
604 /// for convenience.
605 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700606}
607
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700608/// This type represents a Keystore 2.0 key entry.
609/// An entry has a unique `id` by which it can be found in the database.
610/// It has a security level field, key parameters, and three optional fields
611/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800612#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700613pub struct KeyEntry {
614 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800615 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700616 cert: Option<Vec<u8>>,
617 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800618 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700619 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800620 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800621 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700622}
623
624impl KeyEntry {
625 /// Returns the unique id of the Key entry.
626 pub fn id(&self) -> i64 {
627 self.id
628 }
629 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800630 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
631 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700632 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800633 /// Extracts the Optional KeyMint blob including its metadata.
634 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
635 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700636 }
637 /// Exposes the optional public certificate.
638 pub fn cert(&self) -> &Option<Vec<u8>> {
639 &self.cert
640 }
641 /// Extracts the optional public certificate.
642 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
643 self.cert.take()
644 }
645 /// Exposes the optional public certificate chain.
646 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
647 &self.cert_chain
648 }
649 /// Extracts the optional public certificate_chain.
650 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
651 self.cert_chain.take()
652 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800653 /// Returns the uuid of the owning KeyMint instance.
654 pub fn km_uuid(&self) -> &Uuid {
655 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700656 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700657 /// Exposes the key parameters of this key entry.
658 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
659 &self.parameters
660 }
661 /// Consumes this key entry and extracts the keyparameters from it.
662 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
663 self.parameters
664 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800665 /// Exposes the key metadata of this key entry.
666 pub fn metadata(&self) -> &KeyMetaData {
667 &self.metadata
668 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800669 /// This returns true if the entry is a pure certificate entry with no
670 /// private key component.
671 pub fn pure_cert(&self) -> bool {
672 self.pure_cert
673 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000674 /// Consumes this key entry and extracts the keyparameters and metadata from it.
675 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
676 (self.parameters, self.metadata)
677 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700678}
679
680/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800681#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700682pub struct SubComponentType(u32);
683impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800684 /// Persistent identifier for a key blob.
685 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700686 /// Persistent identifier for a certificate blob.
687 pub const CERT: SubComponentType = Self(1);
688 /// Persistent identifier for a certificate chain blob.
689 pub const CERT_CHAIN: SubComponentType = Self(2);
690}
691
692impl ToSql for SubComponentType {
693 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
694 self.0.to_sql()
695 }
696}
697
698impl FromSql for SubComponentType {
699 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
700 Ok(Self(u32::column_result(value)?))
701 }
702}
703
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800704/// This trait is private to the database module. It is used to convey whether or not the garbage
705/// collector shall be invoked after a database access. All closures passed to
706/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
707/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
708/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
709/// `.need_gc()`.
710trait DoGc<T> {
711 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
712
713 fn no_gc(self) -> Result<(bool, T)>;
714
715 fn need_gc(self) -> Result<(bool, T)>;
716}
717
718impl<T> DoGc<T> for Result<T> {
719 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
720 self.map(|r| (need_gc, r))
721 }
722
723 fn no_gc(self) -> Result<(bool, T)> {
724 self.do_gc(false)
725 }
726
727 fn need_gc(self) -> Result<(bool, T)> {
728 self.do_gc(true)
729 }
730}
731
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700732/// KeystoreDB wraps a connection to an SQLite database and tracks its
733/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700734pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700735 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700736 gc: Option<Arc<Gc>>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700737}
738
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000739/// Database representation of the monotonic time retrieved from the system call clock_gettime with
740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
741#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
742pub struct MonotonicRawTime(i64);
743
744impl MonotonicRawTime {
745 /// Constructs a new MonotonicRawTime
746 pub fn now() -> Self {
747 Self(get_current_time_in_seconds())
748 }
749
David Drysdale0e45a612021-02-25 17:24:36 +0000750 /// Constructs a new MonotonicRawTime from a given number of seconds.
751 pub fn from_secs(val: i64) -> Self {
752 Self(val)
753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
757 self.0
758 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800759
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000760 /// Returns the value of MonotonicRawTime in milli seconds as i64
761 pub fn milli_seconds(&self) -> i64 {
762 self.0 * 1000
763 }
764
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800765 /// Like i64::checked_sub.
766 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
767 self.0.checked_sub(other.0).map(Self)
768 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000769}
770
771impl ToSql for MonotonicRawTime {
772 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
773 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
774 }
775}
776
777impl FromSql for MonotonicRawTime {
778 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
779 Ok(Self(i64::column_result(value)?))
780 }
781}
782
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000783/// This struct encapsulates the information to be stored in the database about the auth tokens
784/// received by keystore.
785pub struct AuthTokenEntry {
786 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000787 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000788}
789
790impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000791 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000792 AuthTokenEntry { auth_token, time_received }
793 }
794
795 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800796 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
799 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 })
801 }
802
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000803 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800804 pub fn auth_token(&self) -> &HardwareAuthToken {
805 &self.auth_token
806 }
807
808 /// Returns the auth token wrapped by the AuthTokenEntry
809 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000810 self.auth_token
811 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800812
813 /// Returns the time that this auth token was received.
814 pub fn time_received(&self) -> MonotonicRawTime {
815 self.time_received
816 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000817
818 /// Returns the challenge value of the auth token.
819 pub fn challenge(&self) -> i64 {
820 self.auth_token.challenge
821 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822}
823
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800824/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
825/// This object does not allow access to the database connection. But it keeps a database
826/// connection alive in order to keep the in memory per boot database alive.
827pub struct PerBootDbKeepAlive(Connection);
828
Joel Galenson26f4d012020-07-17 14:57:21 -0700829impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800830 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800831 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
832
Seth Moore78c091f2021-04-09 21:38:30 +0000833 /// Name of the file that holds the cross-boot persistent database.
834 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
835
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800836 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
837 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
838 let conn = Connection::open_in_memory()
839 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
840
841 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
842 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
843 Ok(PerBootDbKeepAlive(conn))
844 }
845
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700846 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800847 /// files persistent.sqlite and perboot.sqlite in the given directory.
848 /// It also attempts to initialize all of the tables.
849 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700850 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700851 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700852 let _wp = wd::watch_millis("KeystoreDB::new", 500);
853
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800855 let mut persistent_path = db_root.to_path_buf();
Seth Moore78c091f2021-04-09 21:38:30 +0000856 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700857
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800858 // Now convert them to strings prefixed with "file:"
859 let mut persistent_path_str = "file:".to_owned();
860 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800861
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800862 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800863
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
865 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
866
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800867 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800868 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800869 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 })?;
871 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700872 }
873
Janis Danisevskis66784c42021-01-27 08:40:25 -0800874 fn init_tables(tx: &Transaction) -> Result<()> {
875 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700876 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700877 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800878 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700879 domain INTEGER,
880 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800881 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800882 state INTEGER,
883 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700884 NO_PARAMS,
885 )
886 .context("Failed to initialize \"keyentry\" table.")?;
887
Janis Danisevskis66784c42021-01-27 08:40:25 -0800888 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800889 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
890 ON keyentry(id);",
891 NO_PARAMS,
892 )
893 .context("Failed to create index keyentry_id_index.")?;
894
895 tx.execute(
896 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
897 ON keyentry(domain, namespace, alias);",
898 NO_PARAMS,
899 )
900 .context("Failed to create index keyentry_domain_namespace_index.")?;
901
902 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700903 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
904 id INTEGER PRIMARY KEY,
905 subcomponent_type INTEGER,
906 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800907 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700908 NO_PARAMS,
909 )
910 .context("Failed to initialize \"blobentry\" table.")?;
911
Janis Danisevskis66784c42021-01-27 08:40:25 -0800912 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800913 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
914 ON blobentry(keyentryid);",
915 NO_PARAMS,
916 )
917 .context("Failed to create index blobentry_keyentryid_index.")?;
918
919 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800920 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
921 id INTEGER PRIMARY KEY,
922 blobentryid INTEGER,
923 tag INTEGER,
924 data ANY,
925 UNIQUE (blobentryid, tag));",
926 NO_PARAMS,
927 )
928 .context("Failed to initialize \"blobmetadata\" table.")?;
929
930 tx.execute(
931 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
932 ON blobmetadata(blobentryid);",
933 NO_PARAMS,
934 )
935 .context("Failed to create index blobmetadata_blobentryid_index.")?;
936
937 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700938 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000939 keyentryid INTEGER,
940 tag INTEGER,
941 data ANY,
942 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700943 NO_PARAMS,
944 )
945 .context("Failed to initialize \"keyparameter\" table.")?;
946
Janis Danisevskis66784c42021-01-27 08:40:25 -0800947 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800948 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
949 ON keyparameter(keyentryid);",
950 NO_PARAMS,
951 )
952 .context("Failed to create index keyparameter_keyentryid_index.")?;
953
954 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800955 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
956 keyentryid INTEGER,
957 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000958 data ANY,
959 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800960 NO_PARAMS,
961 )
962 .context("Failed to initialize \"keymetadata\" table.")?;
963
Janis Danisevskis66784c42021-01-27 08:40:25 -0800964 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800965 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
966 ON keymetadata(keyentryid);",
967 NO_PARAMS,
968 )
969 .context("Failed to create index keymetadata_keyentryid_index.")?;
970
971 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800972 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700973 id INTEGER UNIQUE,
974 grantee INTEGER,
975 keyentryid INTEGER,
976 access_vector INTEGER);",
977 NO_PARAMS,
978 )
979 .context("Failed to initialize \"grant\" table.")?;
980
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000981 //TODO: only drop the following two perboot tables if this is the first start up
982 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800983 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000984 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800985 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000986 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
987 id INTEGER PRIMARY KEY,
988 challenge INTEGER,
989 user_id INTEGER,
990 auth_id INTEGER,
991 authenticator_type INTEGER,
992 timestamp INTEGER,
993 mac BLOB,
994 time_received INTEGER,
995 UNIQUE(user_id, auth_id, authenticator_type));",
996 NO_PARAMS,
997 )
998 .context("Failed to initialize \"authtoken\" table.")?;
999
Janis Danisevskis66784c42021-01-27 08:40:25 -08001000 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001001 // .context("Failed to drop perboot.metadata table")?;
1002 // metadata table stores certain miscellaneous information required for keystore functioning
1003 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001004 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001005 "CREATE TABLE IF NOT EXISTS perboot.metadata (
1006 key TEXT,
1007 value BLOB,
1008 UNIQUE(key));",
1009 NO_PARAMS,
1010 )
1011 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -07001012 Ok(())
1013 }
1014
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001015 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
1016 let conn =
1017 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1018
Janis Danisevskis66784c42021-01-27 08:40:25 -08001019 loop {
1020 if let Err(e) = conn
1021 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1022 .context("Failed to attach database persistent.")
1023 {
1024 if Self::is_locked_error(&e) {
1025 std::thread::sleep(std::time::Duration::from_micros(500));
1026 continue;
1027 } else {
1028 return Err(e);
1029 }
1030 }
1031 break;
1032 }
1033 loop {
1034 if let Err(e) = conn
1035 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1036 .context("Failed to attach database perboot.")
1037 {
1038 if Self::is_locked_error(&e) {
1039 std::thread::sleep(std::time::Duration::from_micros(500));
1040 continue;
1041 } else {
1042 return Err(e);
1043 }
1044 }
1045 break;
1046 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047
1048 Ok(conn)
1049 }
1050
Seth Moore78c091f2021-04-09 21:38:30 +00001051 fn do_table_size_query(
1052 &mut self,
1053 storage_type: StatsdStorageType,
1054 query: &str,
1055 params: &[&str],
1056 ) -> Result<Keystore2StorageStats> {
1057 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1058 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1059 .with_context(|| {
1060 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1061 })
1062 .no_gc()
1063 })?;
1064 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1065 }
1066
1067 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1068 self.do_table_size_query(
1069 StatsdStorageType::Database,
1070 "SELECT page_count * page_size, freelist_count * page_size
1071 FROM pragma_page_count('persistent'),
1072 pragma_page_size('persistent'),
1073 persistent.pragma_freelist_count();",
1074 &[],
1075 )
1076 }
1077
1078 fn get_table_size(
1079 &mut self,
1080 storage_type: StatsdStorageType,
1081 schema: &str,
1082 table: &str,
1083 ) -> Result<Keystore2StorageStats> {
1084 self.do_table_size_query(
1085 storage_type,
1086 "SELECT pgsize,unused FROM dbstat(?1)
1087 WHERE name=?2 AND aggregate=TRUE;",
1088 &[schema, table],
1089 )
1090 }
1091
1092 /// Fetches a storage statisitics atom for a given storage type. For storage
1093 /// types that map to a table, information about the table's storage is
1094 /// returned. Requests for storage types that are not DB tables return None.
1095 pub fn get_storage_stat(
1096 &mut self,
1097 storage_type: StatsdStorageType,
1098 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001099 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1100
Seth Moore78c091f2021-04-09 21:38:30 +00001101 match storage_type {
1102 StatsdStorageType::Database => self.get_total_size(),
1103 StatsdStorageType::KeyEntry => {
1104 self.get_table_size(storage_type, "persistent", "keyentry")
1105 }
1106 StatsdStorageType::KeyEntryIdIndex => {
1107 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1108 }
1109 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1110 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1111 }
1112 StatsdStorageType::BlobEntry => {
1113 self.get_table_size(storage_type, "persistent", "blobentry")
1114 }
1115 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1116 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1117 }
1118 StatsdStorageType::KeyParameter => {
1119 self.get_table_size(storage_type, "persistent", "keyparameter")
1120 }
1121 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1122 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1123 }
1124 StatsdStorageType::KeyMetadata => {
1125 self.get_table_size(storage_type, "persistent", "keymetadata")
1126 }
1127 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1128 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1129 }
1130 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1131 StatsdStorageType::AuthToken => {
1132 self.get_table_size(storage_type, "perboot", "authtoken")
1133 }
1134 StatsdStorageType::BlobMetadata => {
1135 self.get_table_size(storage_type, "persistent", "blobmetadata")
1136 }
1137 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1138 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1139 }
1140 _ => Err(anyhow::Error::msg(format!(
1141 "Unsupported storage type: {}",
1142 storage_type as i32
1143 ))),
1144 }
1145 }
1146
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001147 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001148 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1149 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001150 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1151 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001152 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 blob_ids_to_delete: &[i64],
1155 max_blobs: usize,
1156 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001157 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001158 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001159 // Delete the given blobs.
1160 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161 tx.execute(
1162 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001163 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001164 )
1165 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001166 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1167 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001168 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001169
1170 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1171
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1173 let result: Vec<(i64, Vec<u8>)> = {
1174 let mut stmt = tx
1175 .prepare(
1176 "SELECT id, blob FROM persistent.blobentry
1177 WHERE subcomponent_type = ?
1178 AND (
1179 id NOT IN (
1180 SELECT MAX(id) FROM persistent.blobentry
1181 WHERE subcomponent_type = ?
1182 GROUP BY keyentryid, subcomponent_type
1183 )
1184 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1185 ) LIMIT ?;",
1186 )
1187 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001188
Janis Danisevskis3395f862021-05-06 10:54:17 -07001189 let rows = stmt
1190 .query_map(
1191 params![
1192 SubComponentType::KEY_BLOB,
1193 SubComponentType::KEY_BLOB,
1194 max_blobs as i64,
1195 ],
1196 |row| Ok((row.get(0)?, row.get(1)?)),
1197 )
1198 .context("Trying to query superseded blob.")?;
1199
1200 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1201 .context("Trying to extract superseded blobs.")?
1202 };
1203
1204 let result = result
1205 .into_iter()
1206 .map(|(blob_id, blob)| {
1207 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1208 })
1209 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1210 .context("Trying to load blob metadata.")?;
1211 if !result.is_empty() {
1212 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001213 }
1214
1215 // We did not find any superseded key blob, so let's remove other superseded blob in
1216 // one transaction.
1217 tx.execute(
1218 "DELETE FROM persistent.blobentry
1219 WHERE NOT subcomponent_type = ?
1220 AND (
1221 id NOT IN (
1222 SELECT MAX(id) FROM persistent.blobentry
1223 WHERE NOT subcomponent_type = ?
1224 GROUP BY keyentryid, subcomponent_type
1225 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1226 );",
1227 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1228 )
1229 .context("Trying to purge superseded blobs.")?;
1230
Janis Danisevskis3395f862021-05-06 10:54:17 -07001231 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001232 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001233 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001234 }
1235
1236 /// This maintenance function should be called only once before the database is used for the
1237 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1238 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1239 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1240 /// Keystore crashed at some point during key generation. Callers may want to log such
1241 /// occurrences.
1242 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1243 /// it to `KeyLifeCycle::Live` may have grants.
1244 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001245 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1246
Janis Danisevskis66784c42021-01-27 08:40:25 -08001247 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1248 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001249 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1250 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1251 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001252 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001253 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001254 })
1255 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001256 }
1257
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001258 /// Checks if a key exists with given key type and key descriptor properties.
1259 pub fn key_exists(
1260 &mut self,
1261 domain: Domain,
1262 nspace: i64,
1263 alias: &str,
1264 key_type: KeyType,
1265 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001266 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1267
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001268 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1269 let key_descriptor =
1270 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1271 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1272 match result {
1273 Ok(_) => Ok(true),
1274 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1275 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1276 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1277 },
1278 }
1279 .no_gc()
1280 })
1281 .context("In key_exists.")
1282 }
1283
Hasini Gunasingheda895552021-01-27 19:34:37 +00001284 /// Stores a super key in the database.
1285 pub fn store_super_key(
1286 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001287 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001288 key_type: &SuperKeyType,
1289 blob: &[u8],
1290 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001291 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001292 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001293 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1294
Hasini Gunasingheda895552021-01-27 19:34:37 +00001295 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1296 let key_id = Self::insert_with_retry(|id| {
1297 tx.execute(
1298 "INSERT into persistent.keyentry
1299 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001300 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001301 params![
1302 id,
1303 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001304 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001305 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001306 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001307 KeyLifeCycle::Live,
1308 &KEYSTORE_UUID,
1309 ],
1310 )
1311 })
1312 .context("Failed to insert into keyentry table.")?;
1313
Paul Crowley8d5b2532021-03-19 10:53:07 -07001314 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1315
Hasini Gunasingheda895552021-01-27 19:34:37 +00001316 Self::set_blob_internal(
1317 &tx,
1318 key_id,
1319 SubComponentType::KEY_BLOB,
1320 Some(blob),
1321 Some(blob_metadata),
1322 )
1323 .context("Failed to store key blob.")?;
1324
1325 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1326 .context("Trying to load key components.")
1327 .no_gc()
1328 })
1329 .context("In store_super_key.")
1330 }
1331
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001332 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001333 pub fn load_super_key(
1334 &mut self,
1335 key_type: &SuperKeyType,
1336 user_id: u32,
1337 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001338 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1339
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001340 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1341 let key_descriptor = KeyDescriptor {
1342 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001343 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001344 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001345 blob: None,
1346 };
1347 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1348 match id {
1349 Ok(id) => {
1350 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1351 .context("In load_super_key. Failed to load key entry.")?;
1352 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1353 }
1354 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1355 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1356 _ => Err(error).context("In load_super_key."),
1357 },
1358 }
1359 .no_gc()
1360 })
1361 .context("In load_super_key.")
1362 }
1363
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001364 /// Atomically loads a key entry and associated metadata or creates it using the
1365 /// callback create_new_key callback. The callback is called during a database
1366 /// transaction. This means that implementers should be mindful about using
1367 /// blocking operations such as IPC or grabbing mutexes.
1368 pub fn get_or_create_key_with<F>(
1369 &mut self,
1370 domain: Domain,
1371 namespace: i64,
1372 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001373 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001374 create_new_key: F,
1375 ) -> Result<(KeyIdGuard, KeyEntry)>
1376 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001377 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001378 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001379 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1380
Janis Danisevskis66784c42021-01-27 08:40:25 -08001381 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1382 let id = {
1383 let mut stmt = tx
1384 .prepare(
1385 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001386 WHERE
1387 key_type = ?
1388 AND domain = ?
1389 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001390 AND alias = ?
1391 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001392 )
1393 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1394 let mut rows = stmt
1395 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1396 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001397
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 db_utils::with_rows_extract_one(&mut rows, |row| {
1399 Ok(match row {
1400 Some(r) => r.get(0).context("Failed to unpack id.")?,
1401 None => None,
1402 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 .context("In get_or_create_key_with.")?
1405 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001406
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 let (id, entry) = match id {
1408 Some(id) => (
1409 id,
1410 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1411 .context("In get_or_create_key_with.")?,
1412 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001413
Janis Danisevskis66784c42021-01-27 08:40:25 -08001414 None => {
1415 let id = Self::insert_with_retry(|id| {
1416 tx.execute(
1417 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001418 (id, key_type, domain, namespace, alias, state, km_uuid)
1419 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001420 params![
1421 id,
1422 KeyType::Super,
1423 domain.0,
1424 namespace,
1425 alias,
1426 KeyLifeCycle::Live,
1427 km_uuid,
1428 ],
1429 )
1430 })
1431 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001432
Janis Danisevskis66784c42021-01-27 08:40:25 -08001433 let (blob, metadata) =
1434 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001435 Self::set_blob_internal(
1436 &tx,
1437 id,
1438 SubComponentType::KEY_BLOB,
1439 Some(&blob),
1440 Some(&metadata),
1441 )
Paul Crowley7a658392021-03-18 17:08:20 -07001442 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001443 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001444 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001445 KeyEntry {
1446 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001447 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001448 pure_cert: false,
1449 ..Default::default()
1450 },
1451 )
1452 }
1453 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001454 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001455 })
1456 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001457 }
1458
Janis Danisevskis66784c42021-01-27 08:40:25 -08001459 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1460 /// waiting for the database file to become available. This makes it
1461 /// impossible to successfully recover from a locked database when the
1462 /// transaction holding the device busy is in the same process on a
1463 /// different connection. As a result the busy handler has to time out and
1464 /// fail in order to make progress.
1465 ///
1466 /// Instead, we set the busy handler to None (return immediately). And catch
1467 /// Busy and Locked errors (the latter occur on in memory databases with
1468 /// shared cache, e.g., the per-boot database.) and restart the transaction
1469 /// after a grace period of half a millisecond.
1470 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001471 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001472 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1473 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001474 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1475 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001476 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001477 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001478 loop {
1479 match self
1480 .conn
1481 .transaction_with_behavior(behavior)
1482 .context("In with_transaction.")
1483 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1484 .and_then(|(result, tx)| {
1485 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1486 Ok(result)
1487 }) {
1488 Ok(result) => break Ok(result),
1489 Err(e) => {
1490 if Self::is_locked_error(&e) {
1491 std::thread::sleep(std::time::Duration::from_micros(500));
1492 continue;
1493 } else {
1494 return Err(e).context("In with_transaction.");
1495 }
1496 }
1497 }
1498 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001499 .map(|(need_gc, result)| {
1500 if need_gc {
1501 if let Some(ref gc) = self.gc {
1502 gc.notify_gc();
1503 }
1504 }
1505 result
1506 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001507 }
1508
1509 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001510 matches!(
1511 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1512 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1513 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1514 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001515 }
1516
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001517 /// Creates a new key entry and allocates a new randomized id for the new key.
1518 /// The key id gets associated with a domain and namespace but not with an alias.
1519 /// To complete key generation `rebind_alias` should be called after all of the
1520 /// key artifacts, i.e., blobs and parameters have been associated with the new
1521 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1522 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001523 pub fn create_key_entry(
1524 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001525 domain: &Domain,
1526 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001527 km_uuid: &Uuid,
1528 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001529 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1530
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001531 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001532 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001533 })
1534 .context("In create_key_entry.")
1535 }
1536
1537 fn create_key_entry_internal(
1538 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001539 domain: &Domain,
1540 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001541 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001542 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001543 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001544 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001545 _ => {
1546 return Err(KsError::sys())
1547 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1548 }
1549 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001550 Ok(KEY_ID_LOCK.get(
1551 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001552 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001553 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001554 (id, key_type, domain, namespace, alias, state, km_uuid)
1555 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001556 params![
1557 id,
1558 KeyType::Client,
1559 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001560 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001561 KeyLifeCycle::Existing,
1562 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001563 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001564 )
1565 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001566 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001567 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001568 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001569
Max Bires2b2e6562020-09-22 11:22:36 -07001570 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1571 /// The key id gets associated with a domain and namespace later but not with an alias. The
1572 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1573 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1574 /// a key.
1575 pub fn create_attestation_key_entry(
1576 &mut self,
1577 maced_public_key: &[u8],
1578 raw_public_key: &[u8],
1579 private_key: &[u8],
1580 km_uuid: &Uuid,
1581 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001582 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1583
Max Bires2b2e6562020-09-22 11:22:36 -07001584 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1585 let key_id = KEY_ID_LOCK.get(
1586 Self::insert_with_retry(|id| {
1587 tx.execute(
1588 "INSERT into persistent.keyentry
1589 (id, key_type, domain, namespace, alias, state, km_uuid)
1590 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1591 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1592 )
1593 })
1594 .context("In create_key_entry")?,
1595 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001596 Self::set_blob_internal(
1597 &tx,
1598 key_id.0,
1599 SubComponentType::KEY_BLOB,
1600 Some(private_key),
1601 None,
1602 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001603 let mut metadata = KeyMetaData::new();
1604 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1605 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1606 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001607 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001608 })
1609 .context("In create_attestation_key_entry")
1610 }
1611
Janis Danisevskis377d1002021-01-27 19:07:48 -08001612 /// Set a new blob and associates it with the given key id. Each blob
1613 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001614 /// Each key can have one of each sub component type associated. If more
1615 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001616 /// will get garbage collected.
1617 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1618 /// removed by setting blob to None.
1619 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001620 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001621 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001622 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001623 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001624 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001625 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001626 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1627
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001628 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001629 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001630 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001631 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001632 }
1633
Janis Danisevskiseed69842021-02-18 20:04:10 -08001634 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1635 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1636 /// We use this to insert key blobs into the database which can then be garbage collected
1637 /// lazily by the key garbage collector.
1638 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001639 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1640
Janis Danisevskiseed69842021-02-18 20:04:10 -08001641 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1642 Self::set_blob_internal(
1643 &tx,
1644 Self::UNASSIGNED_KEY_ID,
1645 SubComponentType::KEY_BLOB,
1646 Some(blob),
1647 Some(blob_metadata),
1648 )
1649 .need_gc()
1650 })
1651 .context("In set_deleted_blob.")
1652 }
1653
Janis Danisevskis377d1002021-01-27 19:07:48 -08001654 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001655 tx: &Transaction,
1656 key_id: i64,
1657 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001658 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001659 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001660 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001661 match (blob, sc_type) {
1662 (Some(blob), _) => {
1663 tx.execute(
1664 "INSERT INTO persistent.blobentry
1665 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1666 params![sc_type, key_id, blob],
1667 )
1668 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001669 if let Some(blob_metadata) = blob_metadata {
1670 let blob_id = tx
1671 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1672 row.get(0)
1673 })
1674 .context("In set_blob_internal: Failed to get new blob id.")?;
1675 blob_metadata
1676 .store_in_db(blob_id, tx)
1677 .context("In set_blob_internal: Trying to store blob metadata.")?;
1678 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001679 }
1680 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1681 tx.execute(
1682 "DELETE FROM persistent.blobentry
1683 WHERE subcomponent_type = ? AND keyentryid = ?;",
1684 params![sc_type, key_id],
1685 )
1686 .context("In set_blob_internal: Failed to delete blob.")?;
1687 }
1688 (None, _) => {
1689 return Err(KsError::sys())
1690 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1691 }
1692 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001693 Ok(())
1694 }
1695
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001696 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1697 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001698 #[cfg(test)]
1699 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001700 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001701 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001702 })
1703 .context("In insert_keyparameter.")
1704 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001705
Janis Danisevskis66784c42021-01-27 08:40:25 -08001706 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001707 tx: &Transaction,
1708 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001709 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001710 ) -> Result<()> {
1711 let mut stmt = tx
1712 .prepare(
1713 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1714 VALUES (?, ?, ?, ?);",
1715 )
1716 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1717
Janis Danisevskis66784c42021-01-27 08:40:25 -08001718 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001719 stmt.insert(params![
1720 key_id.0,
1721 p.get_tag().0,
1722 p.key_parameter_value(),
1723 p.security_level().0
1724 ])
1725 .with_context(|| {
1726 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1727 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001728 }
1729 Ok(())
1730 }
1731
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001732 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001733 #[cfg(test)]
1734 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001735 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001736 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001737 })
1738 .context("In insert_key_metadata.")
1739 }
1740
Max Bires2b2e6562020-09-22 11:22:36 -07001741 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1742 /// on the public key.
1743 pub fn store_signed_attestation_certificate_chain(
1744 &mut self,
1745 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001746 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001747 cert_chain: &[u8],
1748 expiration_date: i64,
1749 km_uuid: &Uuid,
1750 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001751 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1752
Max Bires2b2e6562020-09-22 11:22:36 -07001753 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1754 let mut stmt = tx
1755 .prepare(
1756 "SELECT keyentryid
1757 FROM persistent.keymetadata
1758 WHERE tag = ? AND data = ? AND keyentryid IN
1759 (SELECT id
1760 FROM persistent.keyentry
1761 WHERE
1762 alias IS NULL AND
1763 domain IS NULL AND
1764 namespace IS NULL AND
1765 key_type = ? AND
1766 km_uuid = ?);",
1767 )
1768 .context("Failed to store attestation certificate chain.")?;
1769 let mut rows = stmt
1770 .query(params![
1771 KeyMetaData::AttestationRawPubKey,
1772 raw_public_key,
1773 KeyType::Attestation,
1774 km_uuid
1775 ])
1776 .context("Failed to fetch keyid")?;
1777 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1778 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1779 .get(0)
1780 .context("Failed to unpack id.")
1781 })
1782 .context("Failed to get key_id.")?;
1783 let num_updated = tx
1784 .execute(
1785 "UPDATE persistent.keyentry
1786 SET alias = ?
1787 WHERE id = ?;",
1788 params!["signed", key_id],
1789 )
1790 .context("Failed to update alias.")?;
1791 if num_updated != 1 {
1792 return Err(KsError::sys()).context("Alias not updated for the key.");
1793 }
1794 let mut metadata = KeyMetaData::new();
1795 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1796 expiration_date,
1797 )));
1798 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001799 Self::set_blob_internal(
1800 &tx,
1801 key_id,
1802 SubComponentType::CERT_CHAIN,
1803 Some(cert_chain),
1804 None,
1805 )
1806 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001807 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1808 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001809 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001810 })
1811 .context("In store_signed_attestation_certificate_chain: ")
1812 }
1813
1814 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1815 /// currently have a key assigned to it.
1816 pub fn assign_attestation_key(
1817 &mut self,
1818 domain: Domain,
1819 namespace: i64,
1820 km_uuid: &Uuid,
1821 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001822 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1823
Max Bires2b2e6562020-09-22 11:22:36 -07001824 match domain {
1825 Domain::APP | Domain::SELINUX => {}
1826 _ => {
1827 return Err(KsError::sys()).context(format!(
1828 concat!(
1829 "In assign_attestation_key: Domain {:?} ",
1830 "must be either App or SELinux.",
1831 ),
1832 domain
1833 ));
1834 }
1835 }
1836 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1837 let result = tx
1838 .execute(
1839 "UPDATE persistent.keyentry
1840 SET domain=?1, namespace=?2
1841 WHERE
1842 id =
1843 (SELECT MIN(id)
1844 FROM persistent.keyentry
1845 WHERE ALIAS IS NOT NULL
1846 AND domain IS NULL
1847 AND key_type IS ?3
1848 AND state IS ?4
1849 AND km_uuid IS ?5)
1850 AND
1851 (SELECT COUNT(*)
1852 FROM persistent.keyentry
1853 WHERE domain=?1
1854 AND namespace=?2
1855 AND key_type IS ?3
1856 AND state IS ?4
1857 AND km_uuid IS ?5) = 0;",
1858 params![
1859 domain.0 as u32,
1860 namespace,
1861 KeyType::Attestation,
1862 KeyLifeCycle::Live,
1863 km_uuid,
1864 ],
1865 )
1866 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001867 if result == 0 {
1868 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1869 } else if result > 1 {
1870 return Err(KsError::sys())
1871 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001872 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001873 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001874 })
1875 .context("In assign_attestation_key: ")
1876 }
1877
1878 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1879 /// provisioning server, or the maximum number available if there are not num_keys number of
1880 /// entries in the table.
1881 pub fn fetch_unsigned_attestation_keys(
1882 &mut self,
1883 num_keys: i32,
1884 km_uuid: &Uuid,
1885 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001886 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1887
Max Bires2b2e6562020-09-22 11:22:36 -07001888 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1889 let mut stmt = tx
1890 .prepare(
1891 "SELECT data
1892 FROM persistent.keymetadata
1893 WHERE tag = ? AND keyentryid IN
1894 (SELECT id
1895 FROM persistent.keyentry
1896 WHERE
1897 alias IS NULL AND
1898 domain IS NULL AND
1899 namespace IS NULL AND
1900 key_type = ? AND
1901 km_uuid = ?
1902 LIMIT ?);",
1903 )
1904 .context("Failed to prepare statement")?;
1905 let rows = stmt
1906 .query_map(
1907 params![
1908 KeyMetaData::AttestationMacedPublicKey,
1909 KeyType::Attestation,
1910 km_uuid,
1911 num_keys
1912 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001913 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001914 )?
1915 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1916 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001917 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001918 })
1919 .context("In fetch_unsigned_attestation_keys")
1920 }
1921
1922 /// Removes any keys that have expired as of the current time. Returns the number of keys
1923 /// marked unreferenced that are bound to be garbage collected.
1924 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001925 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1926
Max Bires2b2e6562020-09-22 11:22:36 -07001927 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1928 let mut stmt = tx
1929 .prepare(
1930 "SELECT keyentryid, data
1931 FROM persistent.keymetadata
1932 WHERE tag = ? AND keyentryid IN
1933 (SELECT id
1934 FROM persistent.keyentry
1935 WHERE key_type = ?);",
1936 )
1937 .context("Failed to prepare query")?;
1938 let key_ids_to_check = stmt
1939 .query_map(
1940 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1941 |row| Ok((row.get(0)?, row.get(1)?)),
1942 )?
1943 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1944 .context("Failed to get date metadata")?;
1945 let curr_time = DateTime::from_millis_epoch(
1946 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1947 );
1948 let mut num_deleted = 0;
1949 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1950 if Self::mark_unreferenced(&tx, id)? {
1951 num_deleted += 1;
1952 }
1953 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001954 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001955 })
1956 .context("In delete_expired_attestation_keys: ")
1957 }
1958
Max Bires60d7ed12021-03-05 15:59:22 -08001959 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1960 /// they are in. This is useful primarily as a testing mechanism.
1961 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001962 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1963
Max Bires60d7ed12021-03-05 15:59:22 -08001964 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1965 let mut stmt = tx
1966 .prepare(
1967 "SELECT id FROM persistent.keyentry
1968 WHERE key_type IS ?;",
1969 )
1970 .context("Failed to prepare statement")?;
1971 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001972 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001973 .collect::<rusqlite::Result<Vec<i64>>>()
1974 .context("Failed to execute statement")?;
1975 let num_deleted = keys_to_delete
1976 .iter()
1977 .map(|id| Self::mark_unreferenced(&tx, *id))
1978 .collect::<Result<Vec<bool>>>()
1979 .context("Failed to execute mark_unreferenced on a keyid")?
1980 .into_iter()
1981 .filter(|result| *result)
1982 .count() as i64;
1983 Ok(num_deleted).do_gc(num_deleted != 0)
1984 })
1985 .context("In delete_all_attestation_keys: ")
1986 }
1987
Max Bires2b2e6562020-09-22 11:22:36 -07001988 /// Counts the number of keys that will expire by the provided epoch date and the number of
1989 /// keys not currently assigned to a domain.
1990 pub fn get_attestation_pool_status(
1991 &mut self,
1992 date: i64,
1993 km_uuid: &Uuid,
1994 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001995 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1996
Max Bires2b2e6562020-09-22 11:22:36 -07001997 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1998 let mut stmt = tx.prepare(
1999 "SELECT data
2000 FROM persistent.keymetadata
2001 WHERE tag = ? AND keyentryid IN
2002 (SELECT id
2003 FROM persistent.keyentry
2004 WHERE alias IS NOT NULL
2005 AND key_type = ?
2006 AND km_uuid = ?
2007 AND state = ?);",
2008 )?;
2009 let times = stmt
2010 .query_map(
2011 params![
2012 KeyMetaData::AttestationExpirationDate,
2013 KeyType::Attestation,
2014 km_uuid,
2015 KeyLifeCycle::Live
2016 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002017 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002018 )?
2019 .collect::<rusqlite::Result<Vec<DateTime>>>()
2020 .context("Failed to execute metadata statement")?;
2021 let expiring =
2022 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2023 as i32;
2024 stmt = tx.prepare(
2025 "SELECT alias, domain
2026 FROM persistent.keyentry
2027 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2028 )?;
2029 let rows = stmt
2030 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2031 Ok((row.get(0)?, row.get(1)?))
2032 })?
2033 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2034 .context("Failed to execute keyentry statement")?;
2035 let mut unassigned = 0i32;
2036 let mut attested = 0i32;
2037 let total = rows.len() as i32;
2038 for (alias, domain) in rows {
2039 match (alias, domain) {
2040 (Some(_alias), None) => {
2041 attested += 1;
2042 unassigned += 1;
2043 }
2044 (Some(_alias), Some(_domain)) => {
2045 attested += 1;
2046 }
2047 _ => {}
2048 }
2049 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002050 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002051 })
2052 .context("In get_attestation_pool_status: ")
2053 }
2054
2055 /// Fetches the private key and corresponding certificate chain assigned to a
2056 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2057 /// not assigned, or one CertificateChain.
2058 pub fn retrieve_attestation_key_and_cert_chain(
2059 &mut self,
2060 domain: Domain,
2061 namespace: i64,
2062 km_uuid: &Uuid,
2063 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002064 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2065
Max Bires2b2e6562020-09-22 11:22:36 -07002066 match domain {
2067 Domain::APP | Domain::SELINUX => {}
2068 _ => {
2069 return Err(KsError::sys())
2070 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2071 }
2072 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002073 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2074 let mut stmt = tx.prepare(
2075 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002076 FROM persistent.blobentry
2077 WHERE keyentryid IN
2078 (SELECT id
2079 FROM persistent.keyentry
2080 WHERE key_type = ?
2081 AND domain = ?
2082 AND namespace = ?
2083 AND state = ?
2084 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002085 )?;
2086 let rows = stmt
2087 .query_map(
2088 params![
2089 KeyType::Attestation,
2090 domain.0 as u32,
2091 namespace,
2092 KeyLifeCycle::Live,
2093 km_uuid
2094 ],
2095 |row| Ok((row.get(0)?, row.get(1)?)),
2096 )?
2097 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002098 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002099 if rows.is_empty() {
2100 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002101 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002102 return Err(KsError::sys()).context(format!(
2103 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002104 "Expected to get a single attestation",
2105 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2106 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002107 rows.len()
2108 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002109 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002110 let mut km_blob: Vec<u8> = Vec::new();
2111 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002112 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002113 for row in rows {
2114 let sub_type: SubComponentType = row.0;
2115 match sub_type {
2116 SubComponentType::KEY_BLOB => {
2117 km_blob = row.1;
2118 }
2119 SubComponentType::CERT_CHAIN => {
2120 cert_chain_blob = row.1;
2121 }
Max Biresb2e1d032021-02-08 21:35:05 -08002122 SubComponentType::CERT => {
2123 batch_cert_blob = row.1;
2124 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002125 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2126 }
2127 }
2128 Ok(Some(CertificateChain {
2129 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002130 batch_cert: batch_cert_blob,
2131 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002132 }))
2133 .no_gc()
2134 })
Max Biresb2e1d032021-02-08 21:35:05 -08002135 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002136 }
2137
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002138 /// Updates the alias column of the given key id `newid` with the given alias,
2139 /// and atomically, removes the alias, domain, and namespace from another row
2140 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002141 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2142 /// collector.
2143 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002144 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002145 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002146 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002147 domain: &Domain,
2148 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002149 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002150 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002151 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002152 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002153 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002154 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002155 domain
2156 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002157 }
2158 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002159 let updated = tx
2160 .execute(
2161 "UPDATE persistent.keyentry
2162 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002163 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002164 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2165 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002166 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002167 let result = tx
2168 .execute(
2169 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002170 SET alias = ?, state = ?
2171 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2172 params![
2173 alias,
2174 KeyLifeCycle::Live,
2175 newid.0,
2176 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002177 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002178 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002179 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002180 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002181 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002182 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002183 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002184 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002185 result
2186 ));
2187 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002188 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002189 }
2190
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002191 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2192 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2193 pub fn migrate_key_namespace(
2194 &mut self,
2195 key_id_guard: KeyIdGuard,
2196 destination: &KeyDescriptor,
2197 caller_uid: u32,
2198 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2199 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002200 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2201
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002202 let destination = match destination.domain {
2203 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2204 Domain::SELINUX => (*destination).clone(),
2205 domain => {
2206 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2207 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2208 }
2209 };
2210
2211 // Security critical: Must return immediately on failure. Do not remove the '?';
2212 check_permission(&destination)
2213 .context("In migrate_key_namespace: Trying to check permission.")?;
2214
2215 let alias = destination
2216 .alias
2217 .as_ref()
2218 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2219 .context("In migrate_key_namespace: Alias must be specified.")?;
2220
2221 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2222 // Query the destination location. If there is a key, the migration request fails.
2223 if tx
2224 .query_row(
2225 "SELECT id FROM persistent.keyentry
2226 WHERE alias = ? AND domain = ? AND namespace = ?;",
2227 params![alias, destination.domain.0, destination.nspace],
2228 |_| Ok(()),
2229 )
2230 .optional()
2231 .context("Failed to query destination.")?
2232 .is_some()
2233 {
2234 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2235 .context("Target already exists.");
2236 }
2237
2238 let updated = tx
2239 .execute(
2240 "UPDATE persistent.keyentry
2241 SET alias = ?, domain = ?, namespace = ?
2242 WHERE id = ?;",
2243 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2244 )
2245 .context("Failed to update key entry.")?;
2246
2247 if updated != 1 {
2248 return Err(KsError::sys())
2249 .context(format!("Update succeeded, but {} rows were updated.", updated));
2250 }
2251 Ok(()).no_gc()
2252 })
2253 .context("In migrate_key_namespace:")
2254 }
2255
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002256 /// Store a new key in a single transaction.
2257 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2258 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002259 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2260 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002261 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002262 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002263 key: &KeyDescriptor,
2264 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002265 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002266 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002267 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002268 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002269 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002270 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2271
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002272 let (alias, domain, namespace) = match key {
2273 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2274 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2275 (alias, key.domain, nspace)
2276 }
2277 _ => {
2278 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2279 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2280 }
2281 };
2282 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002283 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002284 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002285 let (blob, blob_metadata) = *blob_info;
2286 Self::set_blob_internal(
2287 tx,
2288 key_id.id(),
2289 SubComponentType::KEY_BLOB,
2290 Some(blob),
2291 Some(&blob_metadata),
2292 )
2293 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002294 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002295 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002296 .context("Trying to insert the certificate.")?;
2297 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002298 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002299 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002300 tx,
2301 key_id.id(),
2302 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002303 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002304 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002305 )
2306 .context("Trying to insert the certificate chain.")?;
2307 }
2308 Self::insert_keyparameter_internal(tx, &key_id, params)
2309 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002310 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002311 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002312 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002313 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002314 })
2315 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002316 }
2317
Janis Danisevskis377d1002021-01-27 19:07:48 -08002318 /// Store a new certificate
2319 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2320 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002321 pub fn store_new_certificate(
2322 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002323 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002324 cert: &[u8],
2325 km_uuid: &Uuid,
2326 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002327 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2328
Janis Danisevskis377d1002021-01-27 19:07:48 -08002329 let (alias, domain, namespace) = match key {
2330 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2331 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2332 (alias, key.domain, nspace)
2333 }
2334 _ => {
2335 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2336 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2337 )
2338 }
2339 };
2340 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002341 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002342 .context("Trying to create new key entry.")?;
2343
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002344 Self::set_blob_internal(
2345 tx,
2346 key_id.id(),
2347 SubComponentType::CERT_CHAIN,
2348 Some(cert),
2349 None,
2350 )
2351 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002352
2353 let mut metadata = KeyMetaData::new();
2354 metadata.add(KeyMetaEntry::CreationDate(
2355 DateTime::now().context("Trying to make creation time.")?,
2356 ));
2357
2358 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2359
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002360 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002361 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002362 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002363 })
2364 .context("In store_new_certificate.")
2365 }
2366
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002367 // Helper function loading the key_id given the key descriptor
2368 // tuple comprising domain, namespace, and alias.
2369 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002370 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002371 let alias = key
2372 .alias
2373 .as_ref()
2374 .map_or_else(|| Err(KsError::sys()), Ok)
2375 .context("In load_key_entry_id: Alias must be specified.")?;
2376 let mut stmt = tx
2377 .prepare(
2378 "SELECT id FROM persistent.keyentry
2379 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002380 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002381 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002382 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002383 AND alias = ?
2384 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002385 )
2386 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2387 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002388 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002389 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002390 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002391 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002392 .get(0)
2393 .context("Failed to unpack id.")
2394 })
2395 .context("In load_key_entry_id.")
2396 }
2397
2398 /// This helper function completes the access tuple of a key, which is required
2399 /// to perform access control. The strategy depends on the `domain` field in the
2400 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002401 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002402 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002403 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002404 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002405 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002406 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002407 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408 /// `namespace`.
2409 /// In each case the information returned is sufficient to perform the access
2410 /// check and the key id can be used to load further key artifacts.
2411 fn load_access_tuple(
2412 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002413 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002414 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002415 caller_uid: u32,
2416 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2417 match key.domain {
2418 // Domain App or SELinux. In this case we load the key_id from
2419 // the keyentry database for further loading of key components.
2420 // We already have the full access tuple to perform access control.
2421 // The only distinction is that we use the caller_uid instead
2422 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002423 // Domain::APP.
2424 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002425 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002426 if access_key.domain == Domain::APP {
2427 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002428 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002429 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002430 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002431
2432 Ok((key_id, access_key, None))
2433 }
2434
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002435 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002436 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002437 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 let mut stmt = tx
2439 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002440 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002441 WHERE grantee = ? AND id = ?;",
2442 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002443 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002444 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002445 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002446 .context("Domain:Grant: query failed.")?;
2447 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002448 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002449 let r =
2450 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002451 Ok((
2452 r.get(0).context("Failed to unpack key_id.")?,
2453 r.get(1).context("Failed to unpack access_vector.")?,
2454 ))
2455 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002456 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002457 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002458 }
2459
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002460 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002461 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002462 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002463 let (domain, namespace): (Domain, i64) = {
2464 let mut stmt = tx
2465 .prepare(
2466 "SELECT domain, namespace FROM persistent.keyentry
2467 WHERE
2468 id = ?
2469 AND state = ?;",
2470 )
2471 .context("Domain::KEY_ID: prepare statement failed")?;
2472 let mut rows = stmt
2473 .query(params![key.nspace, KeyLifeCycle::Live])
2474 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002475 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002476 let r =
2477 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002478 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002479 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002480 r.get(1).context("Failed to unpack namespace.")?,
2481 ))
2482 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002483 .context("Domain::KEY_ID.")?
2484 };
2485
2486 // We may use a key by id after loading it by grant.
2487 // In this case we have to check if the caller has a grant for this particular
2488 // key. We can skip this if we already know that the caller is the owner.
2489 // But we cannot know this if domain is anything but App. E.g. in the case
2490 // of Domain::SELINUX we have to speculatively check for grants because we have to
2491 // consult the SEPolicy before we know if the caller is the owner.
2492 let access_vector: Option<KeyPermSet> =
2493 if domain != Domain::APP || namespace != caller_uid as i64 {
2494 let access_vector: Option<i32> = tx
2495 .query_row(
2496 "SELECT access_vector FROM persistent.grant
2497 WHERE grantee = ? AND keyentryid = ?;",
2498 params![caller_uid as i64, key.nspace],
2499 |row| row.get(0),
2500 )
2501 .optional()
2502 .context("Domain::KEY_ID: query grant failed.")?;
2503 access_vector.map(|p| p.into())
2504 } else {
2505 None
2506 };
2507
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002508 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002509 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002510 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002511 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002512
Janis Danisevskis45760022021-01-19 16:34:10 -08002513 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002514 }
2515 _ => Err(anyhow!(KsError::sys())),
2516 }
2517 }
2518
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002519 fn load_blob_components(
2520 key_id: i64,
2521 load_bits: KeyEntryLoadBits,
2522 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002523 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002524 let mut stmt = tx
2525 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002526 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002527 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2528 )
2529 .context("In load_blob_components: prepare statement failed.")?;
2530
2531 let mut rows =
2532 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2533
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002534 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002535 let mut cert_blob: Option<Vec<u8>> = None;
2536 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002537 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002538 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002539 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002540 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002541 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002542 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2543 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002544 key_blob = Some((
2545 row.get(0).context("Failed to extract key blob id.")?,
2546 row.get(2).context("Failed to extract key blob.")?,
2547 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002548 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002549 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002550 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002551 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002552 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002553 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002554 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002555 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002556 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002557 (SubComponentType::CERT, _, _)
2558 | (SubComponentType::CERT_CHAIN, _, _)
2559 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002560 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2561 }
2562 Ok(())
2563 })
2564 .context("In load_blob_components.")?;
2565
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002566 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2567 Ok(Some((
2568 blob,
2569 BlobMetaData::load_from_db(blob_id, tx)
2570 .context("In load_blob_components: Trying to load blob_metadata.")?,
2571 )))
2572 })?;
2573
2574 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002575 }
2576
2577 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2578 let mut stmt = tx
2579 .prepare(
2580 "SELECT tag, data, security_level from persistent.keyparameter
2581 WHERE keyentryid = ?;",
2582 )
2583 .context("In load_key_parameters: prepare statement failed.")?;
2584
2585 let mut parameters: Vec<KeyParameter> = Vec::new();
2586
2587 let mut rows =
2588 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002589 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002590 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2591 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002592 parameters.push(
2593 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2594 .context("Failed to read KeyParameter.")?,
2595 );
2596 Ok(())
2597 })
2598 .context("In load_key_parameters.")?;
2599
2600 Ok(parameters)
2601 }
2602
Qi Wub9433b52020-12-01 14:52:46 +08002603 /// Decrements the usage count of a limited use key. This function first checks whether the
2604 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2605 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2606 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002607 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002608 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2609
Qi Wub9433b52020-12-01 14:52:46 +08002610 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2611 let limit: Option<i32> = tx
2612 .query_row(
2613 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2614 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2615 |row| row.get(0),
2616 )
2617 .optional()
2618 .context("Trying to load usage count")?;
2619
2620 let limit = limit
2621 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2622 .context("The Key no longer exists. Key is exhausted.")?;
2623
2624 tx.execute(
2625 "UPDATE persistent.keyparameter
2626 SET data = data - 1
2627 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2628 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2629 )
2630 .context("Failed to update key usage count.")?;
2631
2632 match limit {
2633 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002634 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002635 .context("Trying to mark limited use key for deletion."),
2636 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002637 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002638 }
2639 })
2640 .context("In check_and_update_key_usage_count.")
2641 }
2642
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002643 /// Load a key entry by the given key descriptor.
2644 /// It uses the `check_permission` callback to verify if the access is allowed
2645 /// given the key access tuple read from the database using `load_access_tuple`.
2646 /// With `load_bits` the caller may specify which blobs shall be loaded from
2647 /// the blob database.
2648 pub fn load_key_entry(
2649 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002650 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002651 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002652 load_bits: KeyEntryLoadBits,
2653 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002654 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2655 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002656 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2657
Janis Danisevskis66784c42021-01-27 08:40:25 -08002658 loop {
2659 match self.load_key_entry_internal(
2660 key,
2661 key_type,
2662 load_bits,
2663 caller_uid,
2664 &check_permission,
2665 ) {
2666 Ok(result) => break Ok(result),
2667 Err(e) => {
2668 if Self::is_locked_error(&e) {
2669 std::thread::sleep(std::time::Duration::from_micros(500));
2670 continue;
2671 } else {
2672 return Err(e).context("In load_key_entry.");
2673 }
2674 }
2675 }
2676 }
2677 }
2678
2679 fn load_key_entry_internal(
2680 &mut self,
2681 key: &KeyDescriptor,
2682 key_type: KeyType,
2683 load_bits: KeyEntryLoadBits,
2684 caller_uid: u32,
2685 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002686 ) -> Result<(KeyIdGuard, KeyEntry)> {
2687 // KEY ID LOCK 1/2
2688 // If we got a key descriptor with a key id we can get the lock right away.
2689 // Otherwise we have to defer it until we know the key id.
2690 let key_id_guard = match key.domain {
2691 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2692 _ => None,
2693 };
2694
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002695 let tx = self
2696 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002697 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002698 .context("In load_key_entry: Failed to initialize transaction.")?;
2699
2700 // Load the key_id and complete the access control tuple.
2701 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002702 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2703 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002704
2705 // Perform access control. It is vital that we return here if the permission is denied.
2706 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002707 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002708
Janis Danisevskisaec14592020-11-12 09:41:49 -08002709 // KEY ID LOCK 2/2
2710 // If we did not get a key id lock by now, it was because we got a key descriptor
2711 // without a key id. At this point we got the key id, so we can try and get a lock.
2712 // However, we cannot block here, because we are in the middle of the transaction.
2713 // So first we try to get the lock non blocking. If that fails, we roll back the
2714 // transaction and block until we get the lock. After we successfully got the lock,
2715 // we start a new transaction and load the access tuple again.
2716 //
2717 // We don't need to perform access control again, because we already established
2718 // that the caller had access to the given key. But we need to make sure that the
2719 // key id still exists. So we have to load the key entry by key id this time.
2720 let (key_id_guard, tx) = match key_id_guard {
2721 None => match KEY_ID_LOCK.try_get(key_id) {
2722 None => {
2723 // Roll back the transaction.
2724 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002725
Janis Danisevskisaec14592020-11-12 09:41:49 -08002726 // Block until we have a key id lock.
2727 let key_id_guard = KEY_ID_LOCK.get(key_id);
2728
2729 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002730 let tx = self
2731 .conn
2732 .unchecked_transaction()
2733 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002734
2735 Self::load_access_tuple(
2736 &tx,
2737 // This time we have to load the key by the retrieved key id, because the
2738 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002739 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002740 domain: Domain::KEY_ID,
2741 nspace: key_id,
2742 ..Default::default()
2743 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002744 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002745 caller_uid,
2746 )
2747 .context("In load_key_entry. (deferred key lock)")?;
2748 (key_id_guard, tx)
2749 }
2750 Some(l) => (l, tx),
2751 },
2752 Some(key_id_guard) => (key_id_guard, tx),
2753 };
2754
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002755 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2756 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002757
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002758 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2759
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002760 Ok((key_id_guard, key_entry))
2761 }
2762
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002763 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002764 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002765 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2766 .context("Trying to delete keyentry.")?;
2767 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2768 .context("Trying to delete keymetadata.")?;
2769 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2770 .context("Trying to delete keyparameters.")?;
2771 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2772 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002773 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002774 }
2775
2776 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002777 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002778 pub fn unbind_key(
2779 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002780 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002781 key_type: KeyType,
2782 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002783 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002784 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002785 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2786
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002787 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2788 let (key_id, access_key_descriptor, access_vector) =
2789 Self::load_access_tuple(tx, key, key_type, caller_uid)
2790 .context("Trying to get access tuple.")?;
2791
2792 // Perform access control. It is vital that we return here if the permission is denied.
2793 // So do not touch that '?' at the end.
2794 check_permission(&access_key_descriptor, access_vector)
2795 .context("While checking permission.")?;
2796
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002797 Self::mark_unreferenced(tx, key_id)
2798 .map(|need_gc| (need_gc, ()))
2799 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002800 })
2801 .context("In unbind_key.")
2802 }
2803
Max Bires8e93d2b2021-01-14 13:17:59 -08002804 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2805 tx.query_row(
2806 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2807 params![key_id],
2808 |row| row.get(0),
2809 )
2810 .context("In get_key_km_uuid.")
2811 }
2812
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002813 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2814 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2815 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002816 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2817
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002818 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2819 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2820 .context("In unbind_keys_for_namespace.");
2821 }
2822 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2823 tx.execute(
2824 "DELETE FROM persistent.keymetadata
2825 WHERE keyentryid IN (
2826 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002827 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002828 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002829 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002830 )
2831 .context("Trying to delete keymetadata.")?;
2832 tx.execute(
2833 "DELETE FROM persistent.keyparameter
2834 WHERE keyentryid IN (
2835 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002836 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002837 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002838 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002839 )
2840 .context("Trying to delete keyparameters.")?;
2841 tx.execute(
2842 "DELETE FROM persistent.grant
2843 WHERE keyentryid IN (
2844 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002845 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002846 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002847 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002848 )
2849 .context("Trying to delete grants.")?;
2850 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002851 "DELETE FROM persistent.keyentry
2852 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2853 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002854 )
2855 .context("Trying to delete keyentry.")?;
2856 Ok(()).need_gc()
2857 })
2858 .context("In unbind_keys_for_namespace")
2859 }
2860
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002861 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2862 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2863 {
2864 tx.execute(
2865 "DELETE FROM persistent.keymetadata
2866 WHERE keyentryid IN (
2867 SELECT id FROM persistent.keyentry
2868 WHERE state = ?
2869 );",
2870 params![KeyLifeCycle::Unreferenced],
2871 )
2872 .context("Trying to delete keymetadata.")?;
2873 tx.execute(
2874 "DELETE FROM persistent.keyparameter
2875 WHERE keyentryid IN (
2876 SELECT id FROM persistent.keyentry
2877 WHERE state = ?
2878 );",
2879 params![KeyLifeCycle::Unreferenced],
2880 )
2881 .context("Trying to delete keyparameters.")?;
2882 tx.execute(
2883 "DELETE FROM persistent.grant
2884 WHERE keyentryid IN (
2885 SELECT id FROM persistent.keyentry
2886 WHERE state = ?
2887 );",
2888 params![KeyLifeCycle::Unreferenced],
2889 )
2890 .context("Trying to delete grants.")?;
2891 tx.execute(
2892 "DELETE FROM persistent.keyentry
2893 WHERE state = ?;",
2894 params![KeyLifeCycle::Unreferenced],
2895 )
2896 .context("Trying to delete keyentry.")?;
2897 Result::<()>::Ok(())
2898 }
2899 .context("In cleanup_unreferenced")
2900 }
2901
Hasini Gunasingheda895552021-01-27 19:34:37 +00002902 /// Delete the keys created on behalf of the user, denoted by the user id.
2903 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2904 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2905 /// The caller of this function should notify the gc if the returned value is true.
2906 pub fn unbind_keys_for_user(
2907 &mut self,
2908 user_id: u32,
2909 keep_non_super_encrypted_keys: bool,
2910 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002911 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2912
Hasini Gunasingheda895552021-01-27 19:34:37 +00002913 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2914 let mut stmt = tx
2915 .prepare(&format!(
2916 "SELECT id from persistent.keyentry
2917 WHERE (
2918 key_type = ?
2919 AND domain = ?
2920 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2921 AND state = ?
2922 ) OR (
2923 key_type = ?
2924 AND namespace = ?
2925 AND alias = ?
2926 AND state = ?
2927 );",
2928 aid_user_offset = AID_USER_OFFSET
2929 ))
2930 .context(concat!(
2931 "In unbind_keys_for_user. ",
2932 "Failed to prepare the query to find the keys created by apps."
2933 ))?;
2934
2935 let mut rows = stmt
2936 .query(params![
2937 // WHERE client key:
2938 KeyType::Client,
2939 Domain::APP.0 as u32,
2940 user_id,
2941 KeyLifeCycle::Live,
2942 // OR super key:
2943 KeyType::Super,
2944 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002945 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002946 KeyLifeCycle::Live
2947 ])
2948 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2949
2950 let mut key_ids: Vec<i64> = Vec::new();
2951 db_utils::with_rows_extract_all(&mut rows, |row| {
2952 key_ids
2953 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2954 Ok(())
2955 })
2956 .context("In unbind_keys_for_user.")?;
2957
2958 let mut notify_gc = false;
2959 for key_id in key_ids {
2960 if keep_non_super_encrypted_keys {
2961 // Load metadata and filter out non-super-encrypted keys.
2962 if let (_, Some((_, blob_metadata)), _, _) =
2963 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2964 .context("In unbind_keys_for_user: Trying to load blob info.")?
2965 {
2966 if blob_metadata.encrypted_by().is_none() {
2967 continue;
2968 }
2969 }
2970 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002971 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002972 .context("In unbind_keys_for_user.")?
2973 || notify_gc;
2974 }
2975 Ok(()).do_gc(notify_gc)
2976 })
2977 .context("In unbind_keys_for_user.")
2978 }
2979
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002980 fn load_key_components(
2981 tx: &Transaction,
2982 load_bits: KeyEntryLoadBits,
2983 key_id: i64,
2984 ) -> Result<KeyEntry> {
2985 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2986
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002987 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002988 Self::load_blob_components(key_id, load_bits, &tx)
2989 .context("In load_key_components.")?;
2990
Max Bires8e93d2b2021-01-14 13:17:59 -08002991 let parameters = Self::load_key_parameters(key_id, &tx)
2992 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002993
Max Bires8e93d2b2021-01-14 13:17:59 -08002994 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2995 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002996
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002997 Ok(KeyEntry {
2998 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002999 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003000 cert: cert_blob,
3001 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003002 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003003 parameters,
3004 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003005 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003006 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003007 }
3008
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003009 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3010 /// The key descriptors will have the domain, nspace, and alias field set.
3011 /// Domain must be APP or SELINUX, the caller must make sure of that.
3012 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003013 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3014
Janis Danisevskis66784c42021-01-27 08:40:25 -08003015 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3016 let mut stmt = tx
3017 .prepare(
3018 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003019 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003020 )
3021 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003022
Janis Danisevskis66784c42021-01-27 08:40:25 -08003023 let mut rows = stmt
3024 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
3025 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003026
Janis Danisevskis66784c42021-01-27 08:40:25 -08003027 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3028 db_utils::with_rows_extract_all(&mut rows, |row| {
3029 descriptors.push(KeyDescriptor {
3030 domain,
3031 nspace: namespace,
3032 alias: Some(row.get(0).context("Trying to extract alias.")?),
3033 blob: None,
3034 });
3035 Ok(())
3036 })
3037 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003038 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003039 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003040 }
3041
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003042 /// Adds a grant to the grant table.
3043 /// Like `load_key_entry` this function loads the access tuple before
3044 /// it uses the callback for a permission check. Upon success,
3045 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3046 /// grant table. The new row will have a randomized id, which is used as
3047 /// grant id in the namespace field of the resulting KeyDescriptor.
3048 pub fn grant(
3049 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003050 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003051 caller_uid: u32,
3052 grantee_uid: u32,
3053 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003054 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003055 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003056 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3057
Janis Danisevskis66784c42021-01-27 08:40:25 -08003058 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3059 // Load the key_id and complete the access control tuple.
3060 // We ignore the access vector here because grants cannot be granted.
3061 // The access vector returned here expresses the permissions the
3062 // grantee has if key.domain == Domain::GRANT. But this vector
3063 // cannot include the grant permission by design, so there is no way the
3064 // subsequent permission check can pass.
3065 // We could check key.domain == Domain::GRANT and fail early.
3066 // But even if we load the access tuple by grant here, the permission
3067 // check denies the attempt to create a grant by grant descriptor.
3068 let (key_id, access_key_descriptor, _) =
3069 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3070 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003071
Janis Danisevskis66784c42021-01-27 08:40:25 -08003072 // Perform access control. It is vital that we return here if the permission
3073 // was denied. So do not touch that '?' at the end of the line.
3074 // This permission check checks if the caller has the grant permission
3075 // for the given key and in addition to all of the permissions
3076 // expressed in `access_vector`.
3077 check_permission(&access_key_descriptor, &access_vector)
3078 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003079
Janis Danisevskis66784c42021-01-27 08:40:25 -08003080 let grant_id = if let Some(grant_id) = tx
3081 .query_row(
3082 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003083 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003084 params![key_id, grantee_uid],
3085 |row| row.get(0),
3086 )
3087 .optional()
3088 .context("In grant: Failed get optional existing grant id.")?
3089 {
3090 tx.execute(
3091 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003092 SET access_vector = ?
3093 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003094 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003095 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003096 .context("In grant: Failed to update existing grant.")?;
3097 grant_id
3098 } else {
3099 Self::insert_with_retry(|id| {
3100 tx.execute(
3101 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3102 VALUES (?, ?, ?, ?);",
3103 params![id, grantee_uid, key_id, i32::from(access_vector)],
3104 )
3105 })
3106 .context("In grant")?
3107 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003108
Janis Danisevskis66784c42021-01-27 08:40:25 -08003109 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003110 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003111 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003112 }
3113
3114 /// This function checks permissions like `grant` and `load_key_entry`
3115 /// before removing a grant from the grant table.
3116 pub fn ungrant(
3117 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003118 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003119 caller_uid: u32,
3120 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003121 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003122 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003123 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3124
Janis Danisevskis66784c42021-01-27 08:40:25 -08003125 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3126 // Load the key_id and complete the access control tuple.
3127 // We ignore the access vector here because grants cannot be granted.
3128 let (key_id, access_key_descriptor, _) =
3129 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3130 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003131
Janis Danisevskis66784c42021-01-27 08:40:25 -08003132 // Perform access control. We must return here if the permission
3133 // was denied. So do not touch the '?' at the end of this line.
3134 check_permission(&access_key_descriptor)
3135 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003136
Janis Danisevskis66784c42021-01-27 08:40:25 -08003137 tx.execute(
3138 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003139 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003140 params![key_id, grantee_uid],
3141 )
3142 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003143
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003144 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003145 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003146 }
3147
Joel Galenson845f74b2020-09-09 14:11:55 -07003148 // Generates a random id and passes it to the given function, which will
3149 // try to insert it into a database. If that insertion fails, retry;
3150 // otherwise return the id.
3151 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3152 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003153 let newid: i64 = match random() {
3154 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3155 i => i,
3156 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003157 match inserter(newid) {
3158 // If the id already existed, try again.
3159 Err(rusqlite::Error::SqliteFailure(
3160 libsqlite3_sys::Error {
3161 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3162 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3163 },
3164 _,
3165 )) => (),
3166 Err(e) => {
3167 return Err(e).context("In insert_with_retry: failed to insert into database.")
3168 }
3169 _ => return Ok(newid),
3170 }
3171 }
3172 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003173
3174 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
3175 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003176 let _wp = wd::watch_millis("KeystoreDB::insert_auth_token", 500);
3177
Janis Danisevskis66784c42021-01-27 08:40:25 -08003178 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3179 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003180 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
3181 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
3182 params![
3183 auth_token.challenge,
3184 auth_token.userId,
3185 auth_token.authenticatorId,
3186 auth_token.authenticatorType.0 as i32,
3187 auth_token.timestamp.milliSeconds as i64,
3188 auth_token.mac,
3189 MonotonicRawTime::now(),
3190 ],
3191 )
3192 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003193 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003194 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003195 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003196
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003197 /// Find the newest auth token matching the given predicate.
3198 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003199 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003200 p: F,
3201 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
3202 where
3203 F: Fn(&AuthTokenEntry) -> bool,
3204 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003205 let _wp = wd::watch_millis("KeystoreDB::find_auth_token_entry", 500);
3206
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003207 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3208 let mut stmt = tx
3209 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
3210 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003211
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003212 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003213
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003214 while let Some(row) = rows.next().context("Failed to get next row.")? {
3215 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003216 HardwareAuthToken {
3217 challenge: row.get(1)?,
3218 userId: row.get(2)?,
3219 authenticatorId: row.get(3)?,
3220 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3221 timestamp: Timestamp { milliSeconds: row.get(5)? },
3222 mac: row.get(6)?,
3223 },
3224 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003225 );
3226 if p(&entry) {
3227 return Ok(Some((
3228 entry,
3229 Self::get_last_off_body(tx)
3230 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003231 )))
3232 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003233 }
3234 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003235 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003236 })
3237 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003238 }
3239
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003240 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003241 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003242 let _wp = wd::watch_millis("KeystoreDB::insert_last_off_body", 500);
3243
Janis Danisevskis66784c42021-01-27 08:40:25 -08003244 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3245 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003246 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3247 params!["last_off_body", last_off_body],
3248 )
3249 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003250 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003251 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003252 }
3253
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003254 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003255 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003256 let _wp = wd::watch_millis("KeystoreDB::update_last_off_body", 500);
3257
Janis Danisevskis66784c42021-01-27 08:40:25 -08003258 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3259 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003260 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3261 params![last_off_body, "last_off_body"],
3262 )
3263 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003264 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003265 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003266 }
3267
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003268 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003269 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003270 let _wp = wd::watch_millis("KeystoreDB::get_last_off_body", 500);
3271
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003272 tx.query_row(
3273 "SELECT value from perboot.metadata WHERE key = ?;",
3274 params!["last_off_body"],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07003275 |row| row.get(0),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003276 )
3277 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003278 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003279}
3280
3281#[cfg(test)]
3282mod tests {
3283
3284 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003285 use crate::key_parameter::{
3286 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3287 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3288 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003289 use crate::key_perm_set;
3290 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003291 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003292 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003293 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3294 HardwareAuthToken::HardwareAuthToken,
3295 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003296 };
3297 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003298 Timestamp::Timestamp,
3299 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003300 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003301 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003302 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003303 use std::collections::BTreeMap;
3304 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003305 use std::sync::atomic::{AtomicU8, Ordering};
3306 use std::sync::Arc;
3307 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003308 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003309 #[cfg(disabled)]
3310 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003311
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003312 fn new_test_db() -> Result<KeystoreDB> {
3313 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3314
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003315 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003316 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003317 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003318 })?;
3319 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003320 }
3321
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003322 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3323 where
3324 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3325 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003326 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003327
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003328 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003329 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003330
Janis Danisevskis3395f862021-05-06 10:54:17 -07003331 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003332 }
3333
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003334 fn rebind_alias(
3335 db: &mut KeystoreDB,
3336 newid: &KeyIdGuard,
3337 alias: &str,
3338 domain: Domain,
3339 namespace: i64,
3340 ) -> Result<bool> {
3341 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003342 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003343 })
3344 .context("In rebind_alias.")
3345 }
3346
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003347 #[test]
3348 fn datetime() -> Result<()> {
3349 let conn = Connection::open_in_memory()?;
3350 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3351 let now = SystemTime::now();
3352 let duration = Duration::from_secs(1000);
3353 let then = now.checked_sub(duration).unwrap();
3354 let soon = now.checked_add(duration).unwrap();
3355 conn.execute(
3356 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3357 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3358 )?;
3359 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3360 let mut rows = stmt.query(NO_PARAMS)?;
3361 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3362 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3363 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3364 assert!(rows.next()?.is_none());
3365 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3366 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3367 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3368 Ok(())
3369 }
3370
Joel Galenson0891bc12020-07-20 10:37:03 -07003371 // Ensure that we're using the "injected" random function, not the real one.
3372 #[test]
3373 fn test_mocked_random() {
3374 let rand1 = random();
3375 let rand2 = random();
3376 let rand3 = random();
3377 if rand1 == rand2 {
3378 assert_eq!(rand2 + 1, rand3);
3379 } else {
3380 assert_eq!(rand1 + 1, rand2);
3381 assert_eq!(rand2, rand3);
3382 }
3383 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003384
Joel Galenson26f4d012020-07-17 14:57:21 -07003385 // Test that we have the correct tables.
3386 #[test]
3387 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003388 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003389 let tables = db
3390 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003391 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003392 .query_map(params![], |row| row.get(0))?
3393 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003394 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003395 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003396 assert_eq!(tables[1], "blobmetadata");
3397 assert_eq!(tables[2], "grant");
3398 assert_eq!(tables[3], "keyentry");
3399 assert_eq!(tables[4], "keymetadata");
3400 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003401 let tables = db
3402 .conn
3403 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3404 .query_map(params![], |row| row.get(0))?
3405 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003406
3407 assert_eq!(tables.len(), 2);
3408 assert_eq!(tables[0], "authtoken");
3409 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003410 Ok(())
3411 }
3412
3413 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003414 fn test_auth_token_table_invariant() -> Result<()> {
3415 let mut db = new_test_db()?;
3416 let auth_token1 = HardwareAuthToken {
3417 challenge: i64::MAX,
3418 userId: 200,
3419 authenticatorId: 200,
3420 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3421 timestamp: Timestamp { milliSeconds: 500 },
3422 mac: String::from("mac").into_bytes(),
3423 };
3424 db.insert_auth_token(&auth_token1)?;
3425 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3426 assert_eq!(auth_tokens_returned.len(), 1);
3427
3428 // insert another auth token with the same values for the columns in the UNIQUE constraint
3429 // of the auth token table and different value for timestamp
3430 let auth_token2 = HardwareAuthToken {
3431 challenge: i64::MAX,
3432 userId: 200,
3433 authenticatorId: 200,
3434 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3435 timestamp: Timestamp { milliSeconds: 600 },
3436 mac: String::from("mac").into_bytes(),
3437 };
3438
3439 db.insert_auth_token(&auth_token2)?;
3440 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3441 assert_eq!(auth_tokens_returned.len(), 1);
3442
3443 if let Some(auth_token) = auth_tokens_returned.pop() {
3444 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3445 }
3446
3447 // insert another auth token with the different values for the columns in the UNIQUE
3448 // constraint of the auth token table
3449 let auth_token3 = HardwareAuthToken {
3450 challenge: i64::MAX,
3451 userId: 201,
3452 authenticatorId: 200,
3453 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3454 timestamp: Timestamp { milliSeconds: 600 },
3455 mac: String::from("mac").into_bytes(),
3456 };
3457
3458 db.insert_auth_token(&auth_token3)?;
3459 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3460 assert_eq!(auth_tokens_returned.len(), 2);
3461
3462 Ok(())
3463 }
3464
3465 // utility function for test_auth_token_table_invariant()
3466 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3467 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3468
3469 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3470 .query_map(NO_PARAMS, |row| {
3471 Ok(AuthTokenEntry::new(
3472 HardwareAuthToken {
3473 challenge: row.get(1)?,
3474 userId: row.get(2)?,
3475 authenticatorId: row.get(3)?,
3476 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3477 timestamp: Timestamp { milliSeconds: row.get(5)? },
3478 mac: row.get(6)?,
3479 },
3480 row.get(7)?,
3481 ))
3482 })?
3483 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3484 Ok(auth_token_entries)
3485 }
3486
3487 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003488 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003489 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003490 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003491
Janis Danisevskis66784c42021-01-27 08:40:25 -08003492 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003493 let entries = get_keyentry(&db)?;
3494 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003495
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003496 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003497
3498 let entries_new = get_keyentry(&db)?;
3499 assert_eq!(entries, entries_new);
3500 Ok(())
3501 }
3502
3503 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003504 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003505 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3506 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003507 }
3508
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003509 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003510
Janis Danisevskis66784c42021-01-27 08:40:25 -08003511 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3512 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003513
3514 let entries = get_keyentry(&db)?;
3515 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003516 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3517 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003518
3519 // Test that we must pass in a valid Domain.
3520 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003521 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003522 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003523 );
3524 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003525 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003526 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003527 );
3528 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003529 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003530 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003531 );
3532
3533 Ok(())
3534 }
3535
Joel Galenson33c04ad2020-08-03 11:04:38 -07003536 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003537 fn test_add_unsigned_key() -> Result<()> {
3538 let mut db = new_test_db()?;
3539 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3540 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3541 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3542 db.create_attestation_key_entry(
3543 &public_key,
3544 &raw_public_key,
3545 &private_key,
3546 &KEYSTORE_UUID,
3547 )?;
3548 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3549 assert_eq!(keys.len(), 1);
3550 assert_eq!(keys[0], public_key);
3551 Ok(())
3552 }
3553
3554 #[test]
3555 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3556 let mut db = new_test_db()?;
3557 let expiration_date: i64 = 20;
3558 let namespace: i64 = 30;
3559 let base_byte: u8 = 1;
3560 let loaded_values =
3561 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3562 let chain =
3563 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3564 assert_eq!(true, chain.is_some());
3565 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003566 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003567 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3568 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003569 Ok(())
3570 }
3571
3572 #[test]
3573 fn test_get_attestation_pool_status() -> Result<()> {
3574 let mut db = new_test_db()?;
3575 let namespace: i64 = 30;
3576 load_attestation_key_pool(
3577 &mut db, 10, /* expiration */
3578 namespace, 0x01, /* base_byte */
3579 )?;
3580 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3581 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3582 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3583 assert_eq!(status.expiring, 0);
3584 assert_eq!(status.attested, 3);
3585 assert_eq!(status.unassigned, 0);
3586 assert_eq!(status.total, 3);
3587 assert_eq!(
3588 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3589 1
3590 );
3591 assert_eq!(
3592 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3593 2
3594 );
3595 assert_eq!(
3596 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3597 3
3598 );
3599 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3600 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3601 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3602 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003603 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003604 db.create_attestation_key_entry(
3605 &public_key,
3606 &raw_public_key,
3607 &private_key,
3608 &KEYSTORE_UUID,
3609 )?;
3610 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3611 assert_eq!(status.attested, 3);
3612 assert_eq!(status.unassigned, 0);
3613 assert_eq!(status.total, 4);
3614 db.store_signed_attestation_certificate_chain(
3615 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003616 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003617 &cert_chain,
3618 20,
3619 &KEYSTORE_UUID,
3620 )?;
3621 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3622 assert_eq!(status.attested, 4);
3623 assert_eq!(status.unassigned, 1);
3624 assert_eq!(status.total, 4);
3625 Ok(())
3626 }
3627
3628 #[test]
3629 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003630 let temp_dir =
3631 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3632 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003633 let expiration_date: i64 =
3634 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3635 let namespace: i64 = 30;
3636 let namespace_del1: i64 = 45;
3637 let namespace_del2: i64 = 60;
3638 let entry_values = load_attestation_key_pool(
3639 &mut db,
3640 expiration_date,
3641 namespace,
3642 0x01, /* base_byte */
3643 )?;
3644 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3645 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003646
3647 let blob_entry_row_count: u32 = db
3648 .conn
3649 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3650 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003651 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3652 // one key, one certificate chain, and one certificate.
3653 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003654
Max Bires2b2e6562020-09-22 11:22:36 -07003655 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3656
3657 let mut cert_chain =
3658 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003659 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003660 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003661 assert_eq!(entry_values.batch_cert, value.batch_cert);
3662 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003663 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003664
3665 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3666 Domain::APP,
3667 namespace_del1,
3668 &KEYSTORE_UUID,
3669 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003670 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003671 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3672 Domain::APP,
3673 namespace_del2,
3674 &KEYSTORE_UUID,
3675 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003676 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003677
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003678 // Give the garbage collector half a second to catch up.
3679 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003680
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003681 let blob_entry_row_count: u32 = db
3682 .conn
3683 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3684 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003685 // There shound be 3 blob entries left, because we deleted two of the attestation
3686 // key entries with three blobs each.
3687 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003688
Max Bires2b2e6562020-09-22 11:22:36 -07003689 Ok(())
3690 }
3691
3692 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003693 fn test_delete_all_attestation_keys() -> Result<()> {
3694 let mut db = new_test_db()?;
3695 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3696 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3697 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3698 let result = db.delete_all_attestation_keys()?;
3699
3700 // Give the garbage collector half a second to catch up.
3701 std::thread::sleep(Duration::from_millis(500));
3702
3703 // Attestation keys should be deleted, and the regular key should remain.
3704 assert_eq!(result, 2);
3705
3706 Ok(())
3707 }
3708
3709 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003710 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003711 fn extractor(
3712 ke: &KeyEntryRow,
3713 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3714 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003715 }
3716
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003717 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003718 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3719 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003720 let entries = get_keyentry(&db)?;
3721 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003722 assert_eq!(
3723 extractor(&entries[0]),
3724 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3725 );
3726 assert_eq!(
3727 extractor(&entries[1]),
3728 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3729 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003730
3731 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003732 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003733 let entries = get_keyentry(&db)?;
3734 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003735 assert_eq!(
3736 extractor(&entries[0]),
3737 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3738 );
3739 assert_eq!(
3740 extractor(&entries[1]),
3741 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3742 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003743
3744 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003745 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003746 let entries = get_keyentry(&db)?;
3747 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003748 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3749 assert_eq!(
3750 extractor(&entries[1]),
3751 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3752 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003753
3754 // Test that we must pass in a valid Domain.
3755 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003756 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003757 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003758 );
3759 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003760 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003761 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003762 );
3763 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003764 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003765 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003766 );
3767
3768 // Test that we correctly handle setting an alias for something that does not exist.
3769 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003770 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003771 "Expected to update a single entry but instead updated 0",
3772 );
3773 // Test that we correctly abort the transaction in this case.
3774 let entries = get_keyentry(&db)?;
3775 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003776 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3777 assert_eq!(
3778 extractor(&entries[1]),
3779 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3780 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003781
3782 Ok(())
3783 }
3784
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003785 #[test]
3786 fn test_grant_ungrant() -> Result<()> {
3787 const CALLER_UID: u32 = 15;
3788 const GRANTEE_UID: u32 = 12;
3789 const SELINUX_NAMESPACE: i64 = 7;
3790
3791 let mut db = new_test_db()?;
3792 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003793 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3794 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3795 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003796 )?;
3797 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003798 domain: super::Domain::APP,
3799 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003800 alias: Some("key".to_string()),
3801 blob: None,
3802 };
3803 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3804 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3805
3806 // Reset totally predictable random number generator in case we
3807 // are not the first test running on this thread.
3808 reset_random();
3809 let next_random = 0i64;
3810
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003811 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003812 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003813 assert_eq!(*a, PVEC1);
3814 assert_eq!(
3815 *k,
3816 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003817 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003818 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003819 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003820 alias: Some("key".to_string()),
3821 blob: None,
3822 }
3823 );
3824 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003825 })
3826 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003827
3828 assert_eq!(
3829 app_granted_key,
3830 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003831 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003832 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003833 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003834 alias: None,
3835 blob: None,
3836 }
3837 );
3838
3839 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003840 domain: super::Domain::SELINUX,
3841 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003842 alias: Some("yek".to_string()),
3843 blob: None,
3844 };
3845
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003846 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003847 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003848 assert_eq!(*a, PVEC1);
3849 assert_eq!(
3850 *k,
3851 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003852 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003853 // namespace must be the supplied SELinux
3854 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003855 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003856 alias: Some("yek".to_string()),
3857 blob: None,
3858 }
3859 );
3860 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003861 })
3862 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003863
3864 assert_eq!(
3865 selinux_granted_key,
3866 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003867 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003868 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003869 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003870 alias: None,
3871 blob: None,
3872 }
3873 );
3874
3875 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003876 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003877 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003878 assert_eq!(*a, PVEC2);
3879 assert_eq!(
3880 *k,
3881 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003882 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003883 // namespace must be the supplied SELinux
3884 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003885 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003886 alias: Some("yek".to_string()),
3887 blob: None,
3888 }
3889 );
3890 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003891 })
3892 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003893
3894 assert_eq!(
3895 selinux_granted_key,
3896 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003897 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003898 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003899 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003900 alias: None,
3901 blob: None,
3902 }
3903 );
3904
3905 {
3906 // Limiting scope of stmt, because it borrows db.
3907 let mut stmt = db
3908 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003909 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003910 let mut rows =
3911 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3912 Ok((
3913 row.get(0)?,
3914 row.get(1)?,
3915 row.get(2)?,
3916 KeyPermSet::from(row.get::<_, i32>(3)?),
3917 ))
3918 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003919
3920 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003921 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003922 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003923 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003924 assert!(rows.next().is_none());
3925 }
3926
3927 debug_dump_keyentry_table(&mut db)?;
3928 println!("app_key {:?}", app_key);
3929 println!("selinux_key {:?}", selinux_key);
3930
Janis Danisevskis66784c42021-01-27 08:40:25 -08003931 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3932 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003933
3934 Ok(())
3935 }
3936
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003937 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003938 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3939 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3940
3941 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003942 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003943 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003944 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003945 let mut blob_metadata = BlobMetaData::new();
3946 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3947 db.set_blob(
3948 &key_id,
3949 SubComponentType::KEY_BLOB,
3950 Some(TEST_KEY_BLOB),
3951 Some(&blob_metadata),
3952 )?;
3953 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3954 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003955 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003956
3957 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003958 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003959 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003960 )?;
3961 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003962 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3963 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003964 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003965 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003966 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003967 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003968 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003969 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003970 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003971
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003972 drop(rows);
3973 drop(stmt);
3974
3975 assert_eq!(
3976 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3977 BlobMetaData::load_from_db(id, tx).no_gc()
3978 })
3979 .expect("Should find blob metadata."),
3980 blob_metadata
3981 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003982 Ok(())
3983 }
3984
3985 static TEST_ALIAS: &str = "my super duper key";
3986
3987 #[test]
3988 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3989 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003990 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003991 .context("test_insert_and_load_full_keyentry_domain_app")?
3992 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003993 let (_key_guard, key_entry) = db
3994 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003995 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003996 domain: Domain::APP,
3997 nspace: 0,
3998 alias: Some(TEST_ALIAS.to_string()),
3999 blob: None,
4000 },
4001 KeyType::Client,
4002 KeyEntryLoadBits::BOTH,
4003 1,
4004 |_k, _av| Ok(()),
4005 )
4006 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004007 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004008
4009 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004010 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004011 domain: Domain::APP,
4012 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004013 alias: Some(TEST_ALIAS.to_string()),
4014 blob: None,
4015 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004016 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004017 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004018 |_, _| Ok(()),
4019 )
4020 .unwrap();
4021
4022 assert_eq!(
4023 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4024 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004025 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004026 domain: Domain::APP,
4027 nspace: 0,
4028 alias: Some(TEST_ALIAS.to_string()),
4029 blob: None,
4030 },
4031 KeyType::Client,
4032 KeyEntryLoadBits::NONE,
4033 1,
4034 |_k, _av| Ok(()),
4035 )
4036 .unwrap_err()
4037 .root_cause()
4038 .downcast_ref::<KsError>()
4039 );
4040
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004041 Ok(())
4042 }
4043
4044 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004045 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4046 let mut db = new_test_db()?;
4047
4048 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004049 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004050 domain: Domain::APP,
4051 nspace: 1,
4052 alias: Some(TEST_ALIAS.to_string()),
4053 blob: None,
4054 },
4055 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004056 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004057 )
4058 .expect("Trying to insert cert.");
4059
4060 let (_key_guard, mut key_entry) = db
4061 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004062 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004063 domain: Domain::APP,
4064 nspace: 1,
4065 alias: Some(TEST_ALIAS.to_string()),
4066 blob: None,
4067 },
4068 KeyType::Client,
4069 KeyEntryLoadBits::PUBLIC,
4070 1,
4071 |_k, _av| Ok(()),
4072 )
4073 .expect("Trying to read certificate entry.");
4074
4075 assert!(key_entry.pure_cert());
4076 assert!(key_entry.cert().is_none());
4077 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4078
4079 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004080 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004081 domain: Domain::APP,
4082 nspace: 1,
4083 alias: Some(TEST_ALIAS.to_string()),
4084 blob: None,
4085 },
4086 KeyType::Client,
4087 1,
4088 |_, _| Ok(()),
4089 )
4090 .unwrap();
4091
4092 assert_eq!(
4093 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4094 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004095 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004096 domain: Domain::APP,
4097 nspace: 1,
4098 alias: Some(TEST_ALIAS.to_string()),
4099 blob: None,
4100 },
4101 KeyType::Client,
4102 KeyEntryLoadBits::NONE,
4103 1,
4104 |_k, _av| Ok(()),
4105 )
4106 .unwrap_err()
4107 .root_cause()
4108 .downcast_ref::<KsError>()
4109 );
4110
4111 Ok(())
4112 }
4113
4114 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004115 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4116 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004117 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004118 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4119 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004120 let (_key_guard, key_entry) = db
4121 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004122 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004123 domain: Domain::SELINUX,
4124 nspace: 1,
4125 alias: Some(TEST_ALIAS.to_string()),
4126 blob: None,
4127 },
4128 KeyType::Client,
4129 KeyEntryLoadBits::BOTH,
4130 1,
4131 |_k, _av| Ok(()),
4132 )
4133 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004134 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004135
4136 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004137 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004138 domain: Domain::SELINUX,
4139 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004140 alias: Some(TEST_ALIAS.to_string()),
4141 blob: None,
4142 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004143 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004144 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004145 |_, _| Ok(()),
4146 )
4147 .unwrap();
4148
4149 assert_eq!(
4150 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4151 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004152 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004153 domain: Domain::SELINUX,
4154 nspace: 1,
4155 alias: Some(TEST_ALIAS.to_string()),
4156 blob: None,
4157 },
4158 KeyType::Client,
4159 KeyEntryLoadBits::NONE,
4160 1,
4161 |_k, _av| Ok(()),
4162 )
4163 .unwrap_err()
4164 .root_cause()
4165 .downcast_ref::<KsError>()
4166 );
4167
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004168 Ok(())
4169 }
4170
4171 #[test]
4172 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4173 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004174 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004175 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4176 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004177 let (_, key_entry) = db
4178 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004179 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004180 KeyType::Client,
4181 KeyEntryLoadBits::BOTH,
4182 1,
4183 |_k, _av| Ok(()),
4184 )
4185 .unwrap();
4186
Qi Wub9433b52020-12-01 14:52:46 +08004187 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004188
4189 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004190 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004191 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004192 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004193 |_, _| Ok(()),
4194 )
4195 .unwrap();
4196
4197 assert_eq!(
4198 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4199 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004200 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004201 KeyType::Client,
4202 KeyEntryLoadBits::NONE,
4203 1,
4204 |_k, _av| Ok(()),
4205 )
4206 .unwrap_err()
4207 .root_cause()
4208 .downcast_ref::<KsError>()
4209 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004210
4211 Ok(())
4212 }
4213
4214 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004215 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4216 let mut db = new_test_db()?;
4217 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4218 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4219 .0;
4220 // Update the usage count of the limited use key.
4221 db.check_and_update_key_usage_count(key_id)?;
4222
4223 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004224 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004225 KeyType::Client,
4226 KeyEntryLoadBits::BOTH,
4227 1,
4228 |_k, _av| Ok(()),
4229 )?;
4230
4231 // The usage count is decremented now.
4232 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4233
4234 Ok(())
4235 }
4236
4237 #[test]
4238 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4239 let mut db = new_test_db()?;
4240 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4241 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4242 .0;
4243 // Update the usage count of the limited use key.
4244 db.check_and_update_key_usage_count(key_id).expect(concat!(
4245 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4246 "This should succeed."
4247 ));
4248
4249 // Try to update the exhausted limited use key.
4250 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4251 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4252 "This should fail."
4253 ));
4254 assert_eq!(
4255 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4256 e.root_cause().downcast_ref::<KsError>().unwrap()
4257 );
4258
4259 Ok(())
4260 }
4261
4262 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004263 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4264 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004265 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004266 .context("test_insert_and_load_full_keyentry_from_grant")?
4267 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004268
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004269 let granted_key = db
4270 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004271 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004272 domain: Domain::APP,
4273 nspace: 0,
4274 alias: Some(TEST_ALIAS.to_string()),
4275 blob: None,
4276 },
4277 1,
4278 2,
4279 key_perm_set![KeyPerm::use_()],
4280 |_k, _av| Ok(()),
4281 )
4282 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004283
4284 debug_dump_grant_table(&mut db)?;
4285
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004286 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004287 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4288 assert_eq!(Domain::GRANT, k.domain);
4289 assert!(av.unwrap().includes(KeyPerm::use_()));
4290 Ok(())
4291 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004292 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004293
Qi Wub9433b52020-12-01 14:52:46 +08004294 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004295
Janis Danisevskis66784c42021-01-27 08:40:25 -08004296 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004297
4298 assert_eq!(
4299 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4300 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004301 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004302 KeyType::Client,
4303 KeyEntryLoadBits::NONE,
4304 2,
4305 |_k, _av| Ok(()),
4306 )
4307 .unwrap_err()
4308 .root_cause()
4309 .downcast_ref::<KsError>()
4310 );
4311
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004312 Ok(())
4313 }
4314
Janis Danisevskis45760022021-01-19 16:34:10 -08004315 // This test attempts to load a key by key id while the caller is not the owner
4316 // but a grant exists for the given key and the caller.
4317 #[test]
4318 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4319 let mut db = new_test_db()?;
4320 const OWNER_UID: u32 = 1u32;
4321 const GRANTEE_UID: u32 = 2u32;
4322 const SOMEONE_ELSE_UID: u32 = 3u32;
4323 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4324 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4325 .0;
4326
4327 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004328 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004329 domain: Domain::APP,
4330 nspace: 0,
4331 alias: Some(TEST_ALIAS.to_string()),
4332 blob: None,
4333 },
4334 OWNER_UID,
4335 GRANTEE_UID,
4336 key_perm_set![KeyPerm::use_()],
4337 |_k, _av| Ok(()),
4338 )
4339 .unwrap();
4340
4341 debug_dump_grant_table(&mut db)?;
4342
4343 let id_descriptor =
4344 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4345
4346 let (_, key_entry) = db
4347 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004348 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004349 KeyType::Client,
4350 KeyEntryLoadBits::BOTH,
4351 GRANTEE_UID,
4352 |k, av| {
4353 assert_eq!(Domain::APP, k.domain);
4354 assert_eq!(OWNER_UID as i64, k.nspace);
4355 assert!(av.unwrap().includes(KeyPerm::use_()));
4356 Ok(())
4357 },
4358 )
4359 .unwrap();
4360
4361 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4362
4363 let (_, key_entry) = db
4364 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004365 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004366 KeyType::Client,
4367 KeyEntryLoadBits::BOTH,
4368 SOMEONE_ELSE_UID,
4369 |k, av| {
4370 assert_eq!(Domain::APP, k.domain);
4371 assert_eq!(OWNER_UID as i64, k.nspace);
4372 assert!(av.is_none());
4373 Ok(())
4374 },
4375 )
4376 .unwrap();
4377
4378 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4379
Janis Danisevskis66784c42021-01-27 08:40:25 -08004380 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004381
4382 assert_eq!(
4383 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4384 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004385 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004386 KeyType::Client,
4387 KeyEntryLoadBits::NONE,
4388 GRANTEE_UID,
4389 |_k, _av| Ok(()),
4390 )
4391 .unwrap_err()
4392 .root_cause()
4393 .downcast_ref::<KsError>()
4394 );
4395
4396 Ok(())
4397 }
4398
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004399 // Creates a key migrates it to a different location and then tries to access it by the old
4400 // and new location.
4401 #[test]
4402 fn test_migrate_key_app_to_app() -> Result<()> {
4403 let mut db = new_test_db()?;
4404 const SOURCE_UID: u32 = 1u32;
4405 const DESTINATION_UID: u32 = 2u32;
4406 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4407 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4408 let key_id_guard =
4409 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4410 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4411
4412 let source_descriptor: KeyDescriptor = KeyDescriptor {
4413 domain: Domain::APP,
4414 nspace: -1,
4415 alias: Some(SOURCE_ALIAS.to_string()),
4416 blob: None,
4417 };
4418
4419 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4420 domain: Domain::APP,
4421 nspace: -1,
4422 alias: Some(DESTINATION_ALIAS.to_string()),
4423 blob: None,
4424 };
4425
4426 let key_id = key_id_guard.id();
4427
4428 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4429 Ok(())
4430 })
4431 .unwrap();
4432
4433 let (_, key_entry) = db
4434 .load_key_entry(
4435 &destination_descriptor,
4436 KeyType::Client,
4437 KeyEntryLoadBits::BOTH,
4438 DESTINATION_UID,
4439 |k, av| {
4440 assert_eq!(Domain::APP, k.domain);
4441 assert_eq!(DESTINATION_UID as i64, k.nspace);
4442 assert!(av.is_none());
4443 Ok(())
4444 },
4445 )
4446 .unwrap();
4447
4448 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4449
4450 assert_eq!(
4451 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4452 db.load_key_entry(
4453 &source_descriptor,
4454 KeyType::Client,
4455 KeyEntryLoadBits::NONE,
4456 SOURCE_UID,
4457 |_k, _av| Ok(()),
4458 )
4459 .unwrap_err()
4460 .root_cause()
4461 .downcast_ref::<KsError>()
4462 );
4463
4464 Ok(())
4465 }
4466
4467 // Creates a key migrates it to a different location and then tries to access it by the old
4468 // and new location.
4469 #[test]
4470 fn test_migrate_key_app_to_selinux() -> Result<()> {
4471 let mut db = new_test_db()?;
4472 const SOURCE_UID: u32 = 1u32;
4473 const DESTINATION_UID: u32 = 2u32;
4474 const DESTINATION_NAMESPACE: i64 = 1000i64;
4475 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4476 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4477 let key_id_guard =
4478 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4479 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4480
4481 let source_descriptor: KeyDescriptor = KeyDescriptor {
4482 domain: Domain::APP,
4483 nspace: -1,
4484 alias: Some(SOURCE_ALIAS.to_string()),
4485 blob: None,
4486 };
4487
4488 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4489 domain: Domain::SELINUX,
4490 nspace: DESTINATION_NAMESPACE,
4491 alias: Some(DESTINATION_ALIAS.to_string()),
4492 blob: None,
4493 };
4494
4495 let key_id = key_id_guard.id();
4496
4497 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4498 Ok(())
4499 })
4500 .unwrap();
4501
4502 let (_, key_entry) = db
4503 .load_key_entry(
4504 &destination_descriptor,
4505 KeyType::Client,
4506 KeyEntryLoadBits::BOTH,
4507 DESTINATION_UID,
4508 |k, av| {
4509 assert_eq!(Domain::SELINUX, k.domain);
4510 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4511 assert!(av.is_none());
4512 Ok(())
4513 },
4514 )
4515 .unwrap();
4516
4517 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4518
4519 assert_eq!(
4520 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4521 db.load_key_entry(
4522 &source_descriptor,
4523 KeyType::Client,
4524 KeyEntryLoadBits::NONE,
4525 SOURCE_UID,
4526 |_k, _av| Ok(()),
4527 )
4528 .unwrap_err()
4529 .root_cause()
4530 .downcast_ref::<KsError>()
4531 );
4532
4533 Ok(())
4534 }
4535
4536 // Creates two keys and tries to migrate the first to the location of the second which
4537 // is expected to fail.
4538 #[test]
4539 fn test_migrate_key_destination_occupied() -> Result<()> {
4540 let mut db = new_test_db()?;
4541 const SOURCE_UID: u32 = 1u32;
4542 const DESTINATION_UID: u32 = 2u32;
4543 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4544 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4545 let key_id_guard =
4546 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4547 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4548 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4549 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4550
4551 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4552 domain: Domain::APP,
4553 nspace: -1,
4554 alias: Some(DESTINATION_ALIAS.to_string()),
4555 blob: None,
4556 };
4557
4558 assert_eq!(
4559 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4560 db.migrate_key_namespace(
4561 key_id_guard,
4562 &destination_descriptor,
4563 DESTINATION_UID,
4564 |_k| Ok(())
4565 )
4566 .unwrap_err()
4567 .root_cause()
4568 .downcast_ref::<KsError>()
4569 );
4570
4571 Ok(())
4572 }
4573
Janis Danisevskisaec14592020-11-12 09:41:49 -08004574 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4575
Janis Danisevskisaec14592020-11-12 09:41:49 -08004576 #[test]
4577 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4578 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004579 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4580 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004581 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004582 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004583 .context("test_insert_and_load_full_keyentry_domain_app")?
4584 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004585 let (_key_guard, key_entry) = db
4586 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004587 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004588 domain: Domain::APP,
4589 nspace: 0,
4590 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4591 blob: None,
4592 },
4593 KeyType::Client,
4594 KeyEntryLoadBits::BOTH,
4595 33,
4596 |_k, _av| Ok(()),
4597 )
4598 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004599 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004600 let state = Arc::new(AtomicU8::new(1));
4601 let state2 = state.clone();
4602
4603 // Spawning a second thread that attempts to acquire the key id lock
4604 // for the same key as the primary thread. The primary thread then
4605 // waits, thereby forcing the secondary thread into the second stage
4606 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4607 // The test succeeds if the secondary thread observes the transition
4608 // of `state` from 1 to 2, despite having a whole second to overtake
4609 // the primary thread.
4610 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004611 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004612 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004613 assert!(db
4614 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004615 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004616 domain: Domain::APP,
4617 nspace: 0,
4618 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4619 blob: None,
4620 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004621 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004622 KeyEntryLoadBits::BOTH,
4623 33,
4624 |_k, _av| Ok(()),
4625 )
4626 .is_ok());
4627 // We should only see a 2 here because we can only return
4628 // from load_key_entry when the `_key_guard` expires,
4629 // which happens at the end of the scope.
4630 assert_eq!(2, state2.load(Ordering::Relaxed));
4631 });
4632
4633 thread::sleep(std::time::Duration::from_millis(1000));
4634
4635 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4636
4637 // Return the handle from this scope so we can join with the
4638 // secondary thread after the key id lock has expired.
4639 handle
4640 // This is where the `_key_guard` goes out of scope,
4641 // which is the reason for concurrent load_key_entry on the same key
4642 // to unblock.
4643 };
4644 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4645 // main test thread. We will not see failing asserts in secondary threads otherwise.
4646 handle.join().unwrap();
4647 Ok(())
4648 }
4649
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004650 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004651 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004652 let temp_dir =
4653 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4654
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004655 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4656 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004657
4658 let _tx1 = db1
4659 .conn
4660 .transaction_with_behavior(TransactionBehavior::Immediate)
4661 .expect("Failed to create first transaction.");
4662
4663 let error = db2
4664 .conn
4665 .transaction_with_behavior(TransactionBehavior::Immediate)
4666 .context("Transaction begin failed.")
4667 .expect_err("This should fail.");
4668 let root_cause = error.root_cause();
4669 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4670 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4671 {
4672 return;
4673 }
4674 panic!(
4675 "Unexpected error {:?} \n{:?} \n{:?}",
4676 error,
4677 root_cause,
4678 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4679 )
4680 }
4681
4682 #[cfg(disabled)]
4683 #[test]
4684 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4685 let temp_dir = Arc::new(
4686 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4687 .expect("Failed to create temp dir."),
4688 );
4689
4690 let test_begin = Instant::now();
4691
4692 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4693 const KEY_COUNT: u32 = 500u32;
4694 const OPEN_DB_COUNT: u32 = 50u32;
4695
4696 let mut actual_key_count = KEY_COUNT;
4697 // First insert KEY_COUNT keys.
4698 for count in 0..KEY_COUNT {
4699 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4700 actual_key_count = count;
4701 break;
4702 }
4703 let alias = format!("test_alias_{}", count);
4704 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4705 .expect("Failed to make key entry.");
4706 }
4707
4708 // Insert more keys from a different thread and into a different namespace.
4709 let temp_dir1 = temp_dir.clone();
4710 let handle1 = thread::spawn(move || {
4711 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4712
4713 for count in 0..actual_key_count {
4714 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4715 return;
4716 }
4717 let alias = format!("test_alias_{}", count);
4718 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4719 .expect("Failed to make key entry.");
4720 }
4721
4722 // then unbind them again.
4723 for count in 0..actual_key_count {
4724 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4725 return;
4726 }
4727 let key = KeyDescriptor {
4728 domain: Domain::APP,
4729 nspace: -1,
4730 alias: Some(format!("test_alias_{}", count)),
4731 blob: None,
4732 };
4733 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4734 }
4735 });
4736
4737 // And start unbinding the first set of keys.
4738 let temp_dir2 = temp_dir.clone();
4739 let handle2 = thread::spawn(move || {
4740 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4741
4742 for count in 0..actual_key_count {
4743 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4744 return;
4745 }
4746 let key = KeyDescriptor {
4747 domain: Domain::APP,
4748 nspace: -1,
4749 alias: Some(format!("test_alias_{}", count)),
4750 blob: None,
4751 };
4752 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4753 }
4754 });
4755
4756 let stop_deleting = Arc::new(AtomicU8::new(0));
4757 let stop_deleting2 = stop_deleting.clone();
4758
4759 // And delete anything that is unreferenced keys.
4760 let temp_dir3 = temp_dir.clone();
4761 let handle3 = thread::spawn(move || {
4762 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4763
4764 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4765 while let Some((key_guard, _key)) =
4766 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4767 {
4768 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4769 return;
4770 }
4771 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4772 }
4773 std::thread::sleep(std::time::Duration::from_millis(100));
4774 }
4775 });
4776
4777 // While a lot of inserting and deleting is going on we have to open database connections
4778 // successfully and use them.
4779 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4780 // out of scope.
4781 #[allow(clippy::redundant_clone)]
4782 let temp_dir4 = temp_dir.clone();
4783 let handle4 = thread::spawn(move || {
4784 for count in 0..OPEN_DB_COUNT {
4785 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4786 return;
4787 }
4788 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4789
4790 let alias = format!("test_alias_{}", count);
4791 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4792 .expect("Failed to make key entry.");
4793 let key = KeyDescriptor {
4794 domain: Domain::APP,
4795 nspace: -1,
4796 alias: Some(alias),
4797 blob: None,
4798 };
4799 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4800 }
4801 });
4802
4803 handle1.join().expect("Thread 1 panicked.");
4804 handle2.join().expect("Thread 2 panicked.");
4805 handle4.join().expect("Thread 4 panicked.");
4806
4807 stop_deleting.store(1, Ordering::Relaxed);
4808 handle3.join().expect("Thread 3 panicked.");
4809
4810 Ok(())
4811 }
4812
4813 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004814 fn list() -> Result<()> {
4815 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004816 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004817 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4818 (Domain::APP, 1, "test1"),
4819 (Domain::APP, 1, "test2"),
4820 (Domain::APP, 1, "test3"),
4821 (Domain::APP, 1, "test4"),
4822 (Domain::APP, 1, "test5"),
4823 (Domain::APP, 1, "test6"),
4824 (Domain::APP, 1, "test7"),
4825 (Domain::APP, 2, "test1"),
4826 (Domain::APP, 2, "test2"),
4827 (Domain::APP, 2, "test3"),
4828 (Domain::APP, 2, "test4"),
4829 (Domain::APP, 2, "test5"),
4830 (Domain::APP, 2, "test6"),
4831 (Domain::APP, 2, "test8"),
4832 (Domain::SELINUX, 100, "test1"),
4833 (Domain::SELINUX, 100, "test2"),
4834 (Domain::SELINUX, 100, "test3"),
4835 (Domain::SELINUX, 100, "test4"),
4836 (Domain::SELINUX, 100, "test5"),
4837 (Domain::SELINUX, 100, "test6"),
4838 (Domain::SELINUX, 100, "test9"),
4839 ];
4840
4841 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4842 .iter()
4843 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004844 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4845 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004846 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4847 });
4848 (entry.id(), *ns)
4849 })
4850 .collect();
4851
4852 for (domain, namespace) in
4853 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4854 {
4855 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4856 .iter()
4857 .filter_map(|(domain, ns, alias)| match ns {
4858 ns if *ns == *namespace => Some(KeyDescriptor {
4859 domain: *domain,
4860 nspace: *ns,
4861 alias: Some(alias.to_string()),
4862 blob: None,
4863 }),
4864 _ => None,
4865 })
4866 .collect();
4867 list_o_descriptors.sort();
4868 let mut list_result = db.list(*domain, *namespace)?;
4869 list_result.sort();
4870 assert_eq!(list_o_descriptors, list_result);
4871
4872 let mut list_o_ids: Vec<i64> = list_o_descriptors
4873 .into_iter()
4874 .map(|d| {
4875 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004876 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004877 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004878 KeyType::Client,
4879 KeyEntryLoadBits::NONE,
4880 *namespace as u32,
4881 |_, _| Ok(()),
4882 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004883 .unwrap();
4884 entry.id()
4885 })
4886 .collect();
4887 list_o_ids.sort_unstable();
4888 let mut loaded_entries: Vec<i64> = list_o_keys
4889 .iter()
4890 .filter_map(|(id, ns)| match ns {
4891 ns if *ns == *namespace => Some(*id),
4892 _ => None,
4893 })
4894 .collect();
4895 loaded_entries.sort_unstable();
4896 assert_eq!(list_o_ids, loaded_entries);
4897 }
4898 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4899
4900 Ok(())
4901 }
4902
Joel Galenson0891bc12020-07-20 10:37:03 -07004903 // Helpers
4904
4905 // Checks that the given result is an error containing the given string.
4906 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4907 let error_str = format!(
4908 "{:#?}",
4909 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4910 );
4911 assert!(
4912 error_str.contains(target),
4913 "The string \"{}\" should contain \"{}\"",
4914 error_str,
4915 target
4916 );
4917 }
4918
Joel Galenson2aab4432020-07-22 15:27:57 -07004919 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004920 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004921 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004922 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004923 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004924 namespace: Option<i64>,
4925 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004926 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004927 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004928 }
4929
4930 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4931 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004932 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004933 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004934 Ok(KeyEntryRow {
4935 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004936 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004937 domain: match row.get(2)? {
4938 Some(i) => Some(Domain(i)),
4939 None => None,
4940 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004941 namespace: row.get(3)?,
4942 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004943 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004944 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004945 })
4946 })?
4947 .map(|r| r.context("Could not read keyentry row."))
4948 .collect::<Result<Vec<_>>>()
4949 }
4950
Max Biresb2e1d032021-02-08 21:35:05 -08004951 struct RemoteProvValues {
4952 cert_chain: Vec<u8>,
4953 priv_key: Vec<u8>,
4954 batch_cert: Vec<u8>,
4955 }
4956
Max Bires2b2e6562020-09-22 11:22:36 -07004957 fn load_attestation_key_pool(
4958 db: &mut KeystoreDB,
4959 expiration_date: i64,
4960 namespace: i64,
4961 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004962 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004963 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4964 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4965 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4966 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004967 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004968 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4969 db.store_signed_attestation_certificate_chain(
4970 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004971 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004972 &cert_chain,
4973 expiration_date,
4974 &KEYSTORE_UUID,
4975 )?;
4976 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004977 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004978 }
4979
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004980 // Note: The parameters and SecurityLevel associations are nonsensical. This
4981 // collection is only used to check if the parameters are preserved as expected by the
4982 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004983 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4984 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004985 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4986 KeyParameter::new(
4987 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4988 SecurityLevel::TRUSTED_ENVIRONMENT,
4989 ),
4990 KeyParameter::new(
4991 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4992 SecurityLevel::TRUSTED_ENVIRONMENT,
4993 ),
4994 KeyParameter::new(
4995 KeyParameterValue::Algorithm(Algorithm::RSA),
4996 SecurityLevel::TRUSTED_ENVIRONMENT,
4997 ),
4998 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4999 KeyParameter::new(
5000 KeyParameterValue::BlockMode(BlockMode::ECB),
5001 SecurityLevel::TRUSTED_ENVIRONMENT,
5002 ),
5003 KeyParameter::new(
5004 KeyParameterValue::BlockMode(BlockMode::GCM),
5005 SecurityLevel::TRUSTED_ENVIRONMENT,
5006 ),
5007 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5008 KeyParameter::new(
5009 KeyParameterValue::Digest(Digest::MD5),
5010 SecurityLevel::TRUSTED_ENVIRONMENT,
5011 ),
5012 KeyParameter::new(
5013 KeyParameterValue::Digest(Digest::SHA_2_224),
5014 SecurityLevel::TRUSTED_ENVIRONMENT,
5015 ),
5016 KeyParameter::new(
5017 KeyParameterValue::Digest(Digest::SHA_2_256),
5018 SecurityLevel::STRONGBOX,
5019 ),
5020 KeyParameter::new(
5021 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5022 SecurityLevel::TRUSTED_ENVIRONMENT,
5023 ),
5024 KeyParameter::new(
5025 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5026 SecurityLevel::TRUSTED_ENVIRONMENT,
5027 ),
5028 KeyParameter::new(
5029 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5030 SecurityLevel::STRONGBOX,
5031 ),
5032 KeyParameter::new(
5033 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5034 SecurityLevel::TRUSTED_ENVIRONMENT,
5035 ),
5036 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5037 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5038 KeyParameter::new(
5039 KeyParameterValue::EcCurve(EcCurve::P_224),
5040 SecurityLevel::TRUSTED_ENVIRONMENT,
5041 ),
5042 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5043 KeyParameter::new(
5044 KeyParameterValue::EcCurve(EcCurve::P_384),
5045 SecurityLevel::TRUSTED_ENVIRONMENT,
5046 ),
5047 KeyParameter::new(
5048 KeyParameterValue::EcCurve(EcCurve::P_521),
5049 SecurityLevel::TRUSTED_ENVIRONMENT,
5050 ),
5051 KeyParameter::new(
5052 KeyParameterValue::RSAPublicExponent(3),
5053 SecurityLevel::TRUSTED_ENVIRONMENT,
5054 ),
5055 KeyParameter::new(
5056 KeyParameterValue::IncludeUniqueID,
5057 SecurityLevel::TRUSTED_ENVIRONMENT,
5058 ),
5059 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5060 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5061 KeyParameter::new(
5062 KeyParameterValue::ActiveDateTime(1234567890),
5063 SecurityLevel::STRONGBOX,
5064 ),
5065 KeyParameter::new(
5066 KeyParameterValue::OriginationExpireDateTime(1234567890),
5067 SecurityLevel::TRUSTED_ENVIRONMENT,
5068 ),
5069 KeyParameter::new(
5070 KeyParameterValue::UsageExpireDateTime(1234567890),
5071 SecurityLevel::TRUSTED_ENVIRONMENT,
5072 ),
5073 KeyParameter::new(
5074 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5075 SecurityLevel::TRUSTED_ENVIRONMENT,
5076 ),
5077 KeyParameter::new(
5078 KeyParameterValue::MaxUsesPerBoot(1234567890),
5079 SecurityLevel::TRUSTED_ENVIRONMENT,
5080 ),
5081 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5082 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5083 KeyParameter::new(
5084 KeyParameterValue::NoAuthRequired,
5085 SecurityLevel::TRUSTED_ENVIRONMENT,
5086 ),
5087 KeyParameter::new(
5088 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5089 SecurityLevel::TRUSTED_ENVIRONMENT,
5090 ),
5091 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5092 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5093 KeyParameter::new(
5094 KeyParameterValue::TrustedUserPresenceRequired,
5095 SecurityLevel::TRUSTED_ENVIRONMENT,
5096 ),
5097 KeyParameter::new(
5098 KeyParameterValue::TrustedConfirmationRequired,
5099 SecurityLevel::TRUSTED_ENVIRONMENT,
5100 ),
5101 KeyParameter::new(
5102 KeyParameterValue::UnlockedDeviceRequired,
5103 SecurityLevel::TRUSTED_ENVIRONMENT,
5104 ),
5105 KeyParameter::new(
5106 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5107 SecurityLevel::SOFTWARE,
5108 ),
5109 KeyParameter::new(
5110 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5111 SecurityLevel::SOFTWARE,
5112 ),
5113 KeyParameter::new(
5114 KeyParameterValue::CreationDateTime(12345677890),
5115 SecurityLevel::SOFTWARE,
5116 ),
5117 KeyParameter::new(
5118 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5119 SecurityLevel::TRUSTED_ENVIRONMENT,
5120 ),
5121 KeyParameter::new(
5122 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5123 SecurityLevel::TRUSTED_ENVIRONMENT,
5124 ),
5125 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5126 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5127 KeyParameter::new(
5128 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5129 SecurityLevel::SOFTWARE,
5130 ),
5131 KeyParameter::new(
5132 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5133 SecurityLevel::TRUSTED_ENVIRONMENT,
5134 ),
5135 KeyParameter::new(
5136 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5137 SecurityLevel::TRUSTED_ENVIRONMENT,
5138 ),
5139 KeyParameter::new(
5140 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5141 SecurityLevel::TRUSTED_ENVIRONMENT,
5142 ),
5143 KeyParameter::new(
5144 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5145 SecurityLevel::TRUSTED_ENVIRONMENT,
5146 ),
5147 KeyParameter::new(
5148 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5149 SecurityLevel::TRUSTED_ENVIRONMENT,
5150 ),
5151 KeyParameter::new(
5152 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5153 SecurityLevel::TRUSTED_ENVIRONMENT,
5154 ),
5155 KeyParameter::new(
5156 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5157 SecurityLevel::TRUSTED_ENVIRONMENT,
5158 ),
5159 KeyParameter::new(
5160 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5161 SecurityLevel::TRUSTED_ENVIRONMENT,
5162 ),
5163 KeyParameter::new(
5164 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5165 SecurityLevel::TRUSTED_ENVIRONMENT,
5166 ),
5167 KeyParameter::new(
5168 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5169 SecurityLevel::TRUSTED_ENVIRONMENT,
5170 ),
5171 KeyParameter::new(
5172 KeyParameterValue::VendorPatchLevel(3),
5173 SecurityLevel::TRUSTED_ENVIRONMENT,
5174 ),
5175 KeyParameter::new(
5176 KeyParameterValue::BootPatchLevel(4),
5177 SecurityLevel::TRUSTED_ENVIRONMENT,
5178 ),
5179 KeyParameter::new(
5180 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5181 SecurityLevel::TRUSTED_ENVIRONMENT,
5182 ),
5183 KeyParameter::new(
5184 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5185 SecurityLevel::TRUSTED_ENVIRONMENT,
5186 ),
5187 KeyParameter::new(
5188 KeyParameterValue::MacLength(256),
5189 SecurityLevel::TRUSTED_ENVIRONMENT,
5190 ),
5191 KeyParameter::new(
5192 KeyParameterValue::ResetSinceIdRotation,
5193 SecurityLevel::TRUSTED_ENVIRONMENT,
5194 ),
5195 KeyParameter::new(
5196 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5197 SecurityLevel::TRUSTED_ENVIRONMENT,
5198 ),
Qi Wub9433b52020-12-01 14:52:46 +08005199 ];
5200 if let Some(value) = max_usage_count {
5201 params.push(KeyParameter::new(
5202 KeyParameterValue::UsageCountLimit(value),
5203 SecurityLevel::SOFTWARE,
5204 ));
5205 }
5206 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005207 }
5208
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005209 fn make_test_key_entry(
5210 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005211 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005212 namespace: i64,
5213 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005214 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005215 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005216 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005217 let mut blob_metadata = BlobMetaData::new();
5218 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5219 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5220 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5221 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5222 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5223
5224 db.set_blob(
5225 &key_id,
5226 SubComponentType::KEY_BLOB,
5227 Some(TEST_KEY_BLOB),
5228 Some(&blob_metadata),
5229 )?;
5230 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5231 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005232
5233 let params = make_test_params(max_usage_count);
5234 db.insert_keyparameter(&key_id, &params)?;
5235
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005236 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005237 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005238 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005239 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005240 Ok(key_id)
5241 }
5242
Qi Wub9433b52020-12-01 14:52:46 +08005243 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5244 let params = make_test_params(max_usage_count);
5245
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005246 let mut blob_metadata = BlobMetaData::new();
5247 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5248 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5249 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5250 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5251 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5252
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005253 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005254 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005255
5256 KeyEntry {
5257 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005258 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005259 cert: Some(TEST_CERT_BLOB.to_vec()),
5260 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005261 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005262 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005263 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005264 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005265 }
5266 }
5267
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005268 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005269 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005270 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005271 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005272 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005273 NO_PARAMS,
5274 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005275 Ok((
5276 row.get(0)?,
5277 row.get(1)?,
5278 row.get(2)?,
5279 row.get(3)?,
5280 row.get(4)?,
5281 row.get(5)?,
5282 row.get(6)?,
5283 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005284 },
5285 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005286
5287 println!("Key entry table rows:");
5288 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005289 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005290 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005291 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5292 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005293 );
5294 }
5295 Ok(())
5296 }
5297
5298 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005299 let mut stmt = db
5300 .conn
5301 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005302 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5303 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5304 })?;
5305
5306 println!("Grant table rows:");
5307 for r in rows {
5308 let (id, gt, ki, av) = r.unwrap();
5309 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5310 }
5311 Ok(())
5312 }
5313
Joel Galenson0891bc12020-07-20 10:37:03 -07005314 // Use a custom random number generator that repeats each number once.
5315 // This allows us to test repeated elements.
5316
5317 thread_local! {
5318 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5319 }
5320
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005321 fn reset_random() {
5322 RANDOM_COUNTER.with(|counter| {
5323 *counter.borrow_mut() = 0;
5324 })
5325 }
5326
Joel Galenson0891bc12020-07-20 10:37:03 -07005327 pub fn random() -> i64 {
5328 RANDOM_COUNTER.with(|counter| {
5329 let result = *counter.borrow() / 2;
5330 *counter.borrow_mut() += 1;
5331 result
5332 })
5333 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005334
5335 #[test]
5336 fn test_last_off_body() -> Result<()> {
5337 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005338 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005339 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5340 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5341 tx.commit()?;
5342 let one_second = Duration::from_secs(1);
5343 thread::sleep(one_second);
5344 db.update_last_off_body(MonotonicRawTime::now())?;
5345 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5346 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5347 tx2.commit()?;
5348 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5349 Ok(())
5350 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005351
5352 #[test]
5353 fn test_unbind_keys_for_user() -> Result<()> {
5354 let mut db = new_test_db()?;
5355 db.unbind_keys_for_user(1, false)?;
5356
5357 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5358 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5359 db.unbind_keys_for_user(2, false)?;
5360
5361 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5362 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5363
5364 db.unbind_keys_for_user(1, true)?;
5365 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5366
5367 Ok(())
5368 }
5369
5370 #[test]
5371 fn test_store_super_key() -> Result<()> {
5372 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005373 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005374 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005375 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005376 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005377 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005378
5379 let (encrypted_super_key, metadata) =
5380 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005381 db.store_super_key(
5382 1,
5383 &USER_SUPER_KEY,
5384 &encrypted_super_key,
5385 &metadata,
5386 &KeyMetaData::new(),
5387 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005388
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005389 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005390 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005391
Paul Crowley7a658392021-03-18 17:08:20 -07005392 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005393 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5394 USER_SUPER_KEY.algorithm,
5395 key_entry,
5396 &pw,
5397 None,
5398 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005399
Paul Crowley7a658392021-03-18 17:08:20 -07005400 let decrypted_secret_bytes =
5401 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5402 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005403 Ok(())
5404 }
Seth Moore78c091f2021-04-09 21:38:30 +00005405
5406 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5407 vec![
5408 StatsdStorageType::KeyEntry,
5409 StatsdStorageType::KeyEntryIdIndex,
5410 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5411 StatsdStorageType::BlobEntry,
5412 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5413 StatsdStorageType::KeyParameter,
5414 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5415 StatsdStorageType::KeyMetadata,
5416 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5417 StatsdStorageType::Grant,
5418 StatsdStorageType::AuthToken,
5419 StatsdStorageType::BlobMetadata,
5420 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5421 ]
5422 }
5423
5424 /// Perform a simple check to ensure that we can query all the storage types
5425 /// that are supported by the DB. Check for reasonable values.
5426 #[test]
5427 fn test_query_all_valid_table_sizes() -> Result<()> {
5428 const PAGE_SIZE: i64 = 4096;
5429
5430 let mut db = new_test_db()?;
5431
5432 for t in get_valid_statsd_storage_types() {
5433 let stat = db.get_storage_stat(t)?;
5434 assert!(stat.size >= PAGE_SIZE);
5435 assert!(stat.size >= stat.unused_size);
5436 }
5437
5438 Ok(())
5439 }
5440
5441 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5442 get_valid_statsd_storage_types()
5443 .into_iter()
5444 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5445 .collect()
5446 }
5447
5448 fn assert_storage_increased(
5449 db: &mut KeystoreDB,
5450 increased_storage_types: Vec<StatsdStorageType>,
5451 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5452 ) {
5453 for storage in increased_storage_types {
5454 // Verify the expected storage increased.
5455 let new = db.get_storage_stat(storage).unwrap();
5456 let storage = storage as i32;
5457 let old = &baseline[&storage];
5458 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5459 assert!(
5460 new.unused_size <= old.unused_size,
5461 "{}: {} <= {}",
5462 storage,
5463 new.unused_size,
5464 old.unused_size
5465 );
5466
5467 // Update the baseline with the new value so that it succeeds in the
5468 // later comparison.
5469 baseline.insert(storage, new);
5470 }
5471
5472 // Get an updated map of the storage and verify there were no unexpected changes.
5473 let updated_stats = get_storage_stats_map(db);
5474 assert_eq!(updated_stats.len(), baseline.len());
5475
5476 for &k in baseline.keys() {
5477 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5478 let mut s = String::new();
5479 for &k in map.keys() {
5480 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5481 .expect("string concat failed");
5482 }
5483 s
5484 };
5485
5486 assert!(
5487 updated_stats[&k].size == baseline[&k].size
5488 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5489 "updated_stats:\n{}\nbaseline:\n{}",
5490 stringify(&updated_stats),
5491 stringify(&baseline)
5492 );
5493 }
5494 }
5495
5496 #[test]
5497 fn test_verify_key_table_size_reporting() -> Result<()> {
5498 let mut db = new_test_db()?;
5499 let mut working_stats = get_storage_stats_map(&mut db);
5500
5501 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5502 assert_storage_increased(
5503 &mut db,
5504 vec![
5505 StatsdStorageType::KeyEntry,
5506 StatsdStorageType::KeyEntryIdIndex,
5507 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5508 ],
5509 &mut working_stats,
5510 );
5511
5512 let mut blob_metadata = BlobMetaData::new();
5513 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5514 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5515 assert_storage_increased(
5516 &mut db,
5517 vec![
5518 StatsdStorageType::BlobEntry,
5519 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5520 StatsdStorageType::BlobMetadata,
5521 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5522 ],
5523 &mut working_stats,
5524 );
5525
5526 let params = make_test_params(None);
5527 db.insert_keyparameter(&key_id, &params)?;
5528 assert_storage_increased(
5529 &mut db,
5530 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5531 &mut working_stats,
5532 );
5533
5534 let mut metadata = KeyMetaData::new();
5535 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5536 db.insert_key_metadata(&key_id, &metadata)?;
5537 assert_storage_increased(
5538 &mut db,
5539 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5540 &mut working_stats,
5541 );
5542
5543 let mut sum = 0;
5544 for stat in working_stats.values() {
5545 sum += stat.size;
5546 }
5547 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5548 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5549
5550 Ok(())
5551 }
5552
5553 #[test]
5554 fn test_verify_auth_table_size_reporting() -> Result<()> {
5555 let mut db = new_test_db()?;
5556 let mut working_stats = get_storage_stats_map(&mut db);
5557 db.insert_auth_token(&HardwareAuthToken {
5558 challenge: 123,
5559 userId: 456,
5560 authenticatorId: 789,
5561 authenticatorType: kmhw_authenticator_type::ANY,
5562 timestamp: Timestamp { milliSeconds: 10 },
5563 mac: b"mac".to_vec(),
5564 })?;
5565 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5566 Ok(())
5567 }
5568
5569 #[test]
5570 fn test_verify_grant_table_size_reporting() -> Result<()> {
5571 const OWNER: i64 = 1;
5572 let mut db = new_test_db()?;
5573 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5574
5575 let mut working_stats = get_storage_stats_map(&mut db);
5576 db.grant(
5577 &KeyDescriptor {
5578 domain: Domain::APP,
5579 nspace: 0,
5580 alias: Some(TEST_ALIAS.to_string()),
5581 blob: None,
5582 },
5583 OWNER as u32,
5584 123,
5585 key_perm_set![KeyPerm::use_()],
5586 |_, _| Ok(()),
5587 )?;
5588
5589 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5590
5591 Ok(())
5592 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005593}