blob: 28ff02da3d7bcffe1330e4a12db075618ca9a676 [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
Matthew Maurer4fb19112021-05-06 15:40:44 -07001048 // Drop the cache size from default (2M) to 0.5M
1049 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1050 .context("Failed to decrease cache size for persistent db")?;
1051 conn.execute("PRAGMA perboot.cache_size = -500;", params![])
1052 .context("Failed to decrease cache size for perboot db")?;
1053
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001054 Ok(conn)
1055 }
1056
Seth Moore78c091f2021-04-09 21:38:30 +00001057 fn do_table_size_query(
1058 &mut self,
1059 storage_type: StatsdStorageType,
1060 query: &str,
1061 params: &[&str],
1062 ) -> Result<Keystore2StorageStats> {
1063 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1064 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1065 .with_context(|| {
1066 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1067 })
1068 .no_gc()
1069 })?;
1070 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1071 }
1072
1073 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1074 self.do_table_size_query(
1075 StatsdStorageType::Database,
1076 "SELECT page_count * page_size, freelist_count * page_size
1077 FROM pragma_page_count('persistent'),
1078 pragma_page_size('persistent'),
1079 persistent.pragma_freelist_count();",
1080 &[],
1081 )
1082 }
1083
1084 fn get_table_size(
1085 &mut self,
1086 storage_type: StatsdStorageType,
1087 schema: &str,
1088 table: &str,
1089 ) -> Result<Keystore2StorageStats> {
1090 self.do_table_size_query(
1091 storage_type,
1092 "SELECT pgsize,unused FROM dbstat(?1)
1093 WHERE name=?2 AND aggregate=TRUE;",
1094 &[schema, table],
1095 )
1096 }
1097
1098 /// Fetches a storage statisitics atom for a given storage type. For storage
1099 /// types that map to a table, information about the table's storage is
1100 /// returned. Requests for storage types that are not DB tables return None.
1101 pub fn get_storage_stat(
1102 &mut self,
1103 storage_type: StatsdStorageType,
1104 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001105 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1106
Seth Moore78c091f2021-04-09 21:38:30 +00001107 match storage_type {
1108 StatsdStorageType::Database => self.get_total_size(),
1109 StatsdStorageType::KeyEntry => {
1110 self.get_table_size(storage_type, "persistent", "keyentry")
1111 }
1112 StatsdStorageType::KeyEntryIdIndex => {
1113 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1114 }
1115 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1116 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1117 }
1118 StatsdStorageType::BlobEntry => {
1119 self.get_table_size(storage_type, "persistent", "blobentry")
1120 }
1121 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1122 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1123 }
1124 StatsdStorageType::KeyParameter => {
1125 self.get_table_size(storage_type, "persistent", "keyparameter")
1126 }
1127 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1128 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1129 }
1130 StatsdStorageType::KeyMetadata => {
1131 self.get_table_size(storage_type, "persistent", "keymetadata")
1132 }
1133 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1134 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1135 }
1136 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1137 StatsdStorageType::AuthToken => {
1138 self.get_table_size(storage_type, "perboot", "authtoken")
1139 }
1140 StatsdStorageType::BlobMetadata => {
1141 self.get_table_size(storage_type, "persistent", "blobmetadata")
1142 }
1143 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1144 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1145 }
1146 _ => Err(anyhow::Error::msg(format!(
1147 "Unsupported storage type: {}",
1148 storage_type as i32
1149 ))),
1150 }
1151 }
1152
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1155 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001156 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1157 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001158 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001159 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001160 blob_ids_to_delete: &[i64],
1161 max_blobs: usize,
1162 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001163 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001164 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 // Delete the given blobs.
1166 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167 tx.execute(
1168 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001169 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001170 )
1171 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1173 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001174 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001175
1176 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1177
Janis Danisevskis3395f862021-05-06 10:54:17 -07001178 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1179 let result: Vec<(i64, Vec<u8>)> = {
1180 let mut stmt = tx
1181 .prepare(
1182 "SELECT id, blob FROM persistent.blobentry
1183 WHERE subcomponent_type = ?
1184 AND (
1185 id NOT IN (
1186 SELECT MAX(id) FROM persistent.blobentry
1187 WHERE subcomponent_type = ?
1188 GROUP BY keyentryid, subcomponent_type
1189 )
1190 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1191 ) LIMIT ?;",
1192 )
1193 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001194
Janis Danisevskis3395f862021-05-06 10:54:17 -07001195 let rows = stmt
1196 .query_map(
1197 params![
1198 SubComponentType::KEY_BLOB,
1199 SubComponentType::KEY_BLOB,
1200 max_blobs as i64,
1201 ],
1202 |row| Ok((row.get(0)?, row.get(1)?)),
1203 )
1204 .context("Trying to query superseded blob.")?;
1205
1206 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1207 .context("Trying to extract superseded blobs.")?
1208 };
1209
1210 let result = result
1211 .into_iter()
1212 .map(|(blob_id, blob)| {
1213 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1214 })
1215 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1216 .context("Trying to load blob metadata.")?;
1217 if !result.is_empty() {
1218 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001219 }
1220
1221 // We did not find any superseded key blob, so let's remove other superseded blob in
1222 // one transaction.
1223 tx.execute(
1224 "DELETE FROM persistent.blobentry
1225 WHERE NOT subcomponent_type = ?
1226 AND (
1227 id NOT IN (
1228 SELECT MAX(id) FROM persistent.blobentry
1229 WHERE NOT subcomponent_type = ?
1230 GROUP BY keyentryid, subcomponent_type
1231 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1232 );",
1233 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1234 )
1235 .context("Trying to purge superseded blobs.")?;
1236
Janis Danisevskis3395f862021-05-06 10:54:17 -07001237 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001238 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001239 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001240 }
1241
1242 /// This maintenance function should be called only once before the database is used for the
1243 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1244 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1245 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1246 /// Keystore crashed at some point during key generation. Callers may want to log such
1247 /// occurrences.
1248 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1249 /// it to `KeyLifeCycle::Live` may have grants.
1250 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001251 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1252
Janis Danisevskis66784c42021-01-27 08:40:25 -08001253 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1254 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001255 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1256 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1257 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001258 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001259 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001260 })
1261 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001262 }
1263
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001264 /// Checks if a key exists with given key type and key descriptor properties.
1265 pub fn key_exists(
1266 &mut self,
1267 domain: Domain,
1268 nspace: i64,
1269 alias: &str,
1270 key_type: KeyType,
1271 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001272 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1273
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001274 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1275 let key_descriptor =
1276 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1277 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1278 match result {
1279 Ok(_) => Ok(true),
1280 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1281 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1282 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1283 },
1284 }
1285 .no_gc()
1286 })
1287 .context("In key_exists.")
1288 }
1289
Hasini Gunasingheda895552021-01-27 19:34:37 +00001290 /// Stores a super key in the database.
1291 pub fn store_super_key(
1292 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001293 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001294 key_type: &SuperKeyType,
1295 blob: &[u8],
1296 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001297 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001299 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1300
Hasini Gunasingheda895552021-01-27 19:34:37 +00001301 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1302 let key_id = Self::insert_with_retry(|id| {
1303 tx.execute(
1304 "INSERT into persistent.keyentry
1305 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001306 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001307 params![
1308 id,
1309 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001310 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001311 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001312 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 KeyLifeCycle::Live,
1314 &KEYSTORE_UUID,
1315 ],
1316 )
1317 })
1318 .context("Failed to insert into keyentry table.")?;
1319
Paul Crowley8d5b2532021-03-19 10:53:07 -07001320 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1321
Hasini Gunasingheda895552021-01-27 19:34:37 +00001322 Self::set_blob_internal(
1323 &tx,
1324 key_id,
1325 SubComponentType::KEY_BLOB,
1326 Some(blob),
1327 Some(blob_metadata),
1328 )
1329 .context("Failed to store key blob.")?;
1330
1331 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1332 .context("Trying to load key components.")
1333 .no_gc()
1334 })
1335 .context("In store_super_key.")
1336 }
1337
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001338 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001339 pub fn load_super_key(
1340 &mut self,
1341 key_type: &SuperKeyType,
1342 user_id: u32,
1343 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001344 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1345
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001346 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1347 let key_descriptor = KeyDescriptor {
1348 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001349 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001350 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001351 blob: None,
1352 };
1353 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1354 match id {
1355 Ok(id) => {
1356 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1357 .context("In load_super_key. Failed to load key entry.")?;
1358 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1359 }
1360 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1361 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1362 _ => Err(error).context("In load_super_key."),
1363 },
1364 }
1365 .no_gc()
1366 })
1367 .context("In load_super_key.")
1368 }
1369
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001370 /// Atomically loads a key entry and associated metadata or creates it using the
1371 /// callback create_new_key callback. The callback is called during a database
1372 /// transaction. This means that implementers should be mindful about using
1373 /// blocking operations such as IPC or grabbing mutexes.
1374 pub fn get_or_create_key_with<F>(
1375 &mut self,
1376 domain: Domain,
1377 namespace: i64,
1378 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001379 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001380 create_new_key: F,
1381 ) -> Result<(KeyIdGuard, KeyEntry)>
1382 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001383 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001384 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001385 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1386
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1388 let id = {
1389 let mut stmt = tx
1390 .prepare(
1391 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001392 WHERE
1393 key_type = ?
1394 AND domain = ?
1395 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001396 AND alias = ?
1397 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 )
1399 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1400 let mut rows = stmt
1401 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1402 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 db_utils::with_rows_extract_one(&mut rows, |row| {
1405 Ok(match row {
1406 Some(r) => r.get(0).context("Failed to unpack id.")?,
1407 None => None,
1408 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001409 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001410 .context("In get_or_create_key_with.")?
1411 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001412
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 let (id, entry) = match id {
1414 Some(id) => (
1415 id,
1416 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1417 .context("In get_or_create_key_with.")?,
1418 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001419
Janis Danisevskis66784c42021-01-27 08:40:25 -08001420 None => {
1421 let id = Self::insert_with_retry(|id| {
1422 tx.execute(
1423 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001424 (id, key_type, domain, namespace, alias, state, km_uuid)
1425 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001426 params![
1427 id,
1428 KeyType::Super,
1429 domain.0,
1430 namespace,
1431 alias,
1432 KeyLifeCycle::Live,
1433 km_uuid,
1434 ],
1435 )
1436 })
1437 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001438
Janis Danisevskis66784c42021-01-27 08:40:25 -08001439 let (blob, metadata) =
1440 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001441 Self::set_blob_internal(
1442 &tx,
1443 id,
1444 SubComponentType::KEY_BLOB,
1445 Some(&blob),
1446 Some(&metadata),
1447 )
Paul Crowley7a658392021-03-18 17:08:20 -07001448 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001449 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001450 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001451 KeyEntry {
1452 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001453 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001454 pure_cert: false,
1455 ..Default::default()
1456 },
1457 )
1458 }
1459 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001460 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001461 })
1462 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001463 }
1464
Janis Danisevskis66784c42021-01-27 08:40:25 -08001465 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1466 /// waiting for the database file to become available. This makes it
1467 /// impossible to successfully recover from a locked database when the
1468 /// transaction holding the device busy is in the same process on a
1469 /// different connection. As a result the busy handler has to time out and
1470 /// fail in order to make progress.
1471 ///
1472 /// Instead, we set the busy handler to None (return immediately). And catch
1473 /// Busy and Locked errors (the latter occur on in memory databases with
1474 /// shared cache, e.g., the per-boot database.) and restart the transaction
1475 /// after a grace period of half a millisecond.
1476 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001477 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001478 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1479 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001480 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1481 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001482 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001483 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001484 loop {
1485 match self
1486 .conn
1487 .transaction_with_behavior(behavior)
1488 .context("In with_transaction.")
1489 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1490 .and_then(|(result, tx)| {
1491 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1492 Ok(result)
1493 }) {
1494 Ok(result) => break Ok(result),
1495 Err(e) => {
1496 if Self::is_locked_error(&e) {
1497 std::thread::sleep(std::time::Duration::from_micros(500));
1498 continue;
1499 } else {
1500 return Err(e).context("In with_transaction.");
1501 }
1502 }
1503 }
1504 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001505 .map(|(need_gc, result)| {
1506 if need_gc {
1507 if let Some(ref gc) = self.gc {
1508 gc.notify_gc();
1509 }
1510 }
1511 result
1512 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001513 }
1514
1515 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001516 matches!(
1517 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1518 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1519 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1520 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001521 }
1522
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001523 /// Creates a new key entry and allocates a new randomized id for the new key.
1524 /// The key id gets associated with a domain and namespace but not with an alias.
1525 /// To complete key generation `rebind_alias` should be called after all of the
1526 /// key artifacts, i.e., blobs and parameters have been associated with the new
1527 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1528 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001529 pub fn create_key_entry(
1530 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001531 domain: &Domain,
1532 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001533 km_uuid: &Uuid,
1534 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001535 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1536
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001537 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001538 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001539 })
1540 .context("In create_key_entry.")
1541 }
1542
1543 fn create_key_entry_internal(
1544 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001545 domain: &Domain,
1546 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001547 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001548 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001549 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001550 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001551 _ => {
1552 return Err(KsError::sys())
1553 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1554 }
1555 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001556 Ok(KEY_ID_LOCK.get(
1557 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001558 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001559 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001560 (id, key_type, domain, namespace, alias, state, km_uuid)
1561 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001562 params![
1563 id,
1564 KeyType::Client,
1565 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001566 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001567 KeyLifeCycle::Existing,
1568 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001569 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001570 )
1571 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001572 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001573 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001574 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001575
Max Bires2b2e6562020-09-22 11:22:36 -07001576 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1577 /// The key id gets associated with a domain and namespace later but not with an alias. The
1578 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1579 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1580 /// a key.
1581 pub fn create_attestation_key_entry(
1582 &mut self,
1583 maced_public_key: &[u8],
1584 raw_public_key: &[u8],
1585 private_key: &[u8],
1586 km_uuid: &Uuid,
1587 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001588 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1589
Max Bires2b2e6562020-09-22 11:22:36 -07001590 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1591 let key_id = KEY_ID_LOCK.get(
1592 Self::insert_with_retry(|id| {
1593 tx.execute(
1594 "INSERT into persistent.keyentry
1595 (id, key_type, domain, namespace, alias, state, km_uuid)
1596 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1597 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1598 )
1599 })
1600 .context("In create_key_entry")?,
1601 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001602 Self::set_blob_internal(
1603 &tx,
1604 key_id.0,
1605 SubComponentType::KEY_BLOB,
1606 Some(private_key),
1607 None,
1608 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001609 let mut metadata = KeyMetaData::new();
1610 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1611 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1612 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001613 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001614 })
1615 .context("In create_attestation_key_entry")
1616 }
1617
Janis Danisevskis377d1002021-01-27 19:07:48 -08001618 /// Set a new blob and associates it with the given key id. Each blob
1619 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001620 /// Each key can have one of each sub component type associated. If more
1621 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001622 /// will get garbage collected.
1623 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1624 /// removed by setting blob to None.
1625 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001626 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001627 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001628 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001629 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001630 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001631 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001632 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1633
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001634 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001635 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001636 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001637 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001638 }
1639
Janis Danisevskiseed69842021-02-18 20:04:10 -08001640 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1641 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1642 /// We use this to insert key blobs into the database which can then be garbage collected
1643 /// lazily by the key garbage collector.
1644 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001645 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1646
Janis Danisevskiseed69842021-02-18 20:04:10 -08001647 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1648 Self::set_blob_internal(
1649 &tx,
1650 Self::UNASSIGNED_KEY_ID,
1651 SubComponentType::KEY_BLOB,
1652 Some(blob),
1653 Some(blob_metadata),
1654 )
1655 .need_gc()
1656 })
1657 .context("In set_deleted_blob.")
1658 }
1659
Janis Danisevskis377d1002021-01-27 19:07:48 -08001660 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001661 tx: &Transaction,
1662 key_id: i64,
1663 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001664 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001665 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001666 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001667 match (blob, sc_type) {
1668 (Some(blob), _) => {
1669 tx.execute(
1670 "INSERT INTO persistent.blobentry
1671 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1672 params![sc_type, key_id, blob],
1673 )
1674 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001675 if let Some(blob_metadata) = blob_metadata {
1676 let blob_id = tx
1677 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1678 row.get(0)
1679 })
1680 .context("In set_blob_internal: Failed to get new blob id.")?;
1681 blob_metadata
1682 .store_in_db(blob_id, tx)
1683 .context("In set_blob_internal: Trying to store blob metadata.")?;
1684 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001685 }
1686 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1687 tx.execute(
1688 "DELETE FROM persistent.blobentry
1689 WHERE subcomponent_type = ? AND keyentryid = ?;",
1690 params![sc_type, key_id],
1691 )
1692 .context("In set_blob_internal: Failed to delete blob.")?;
1693 }
1694 (None, _) => {
1695 return Err(KsError::sys())
1696 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1697 }
1698 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001699 Ok(())
1700 }
1701
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001702 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1703 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001704 #[cfg(test)]
1705 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001706 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001707 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001708 })
1709 .context("In insert_keyparameter.")
1710 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001711
Janis Danisevskis66784c42021-01-27 08:40:25 -08001712 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001713 tx: &Transaction,
1714 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001715 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001716 ) -> Result<()> {
1717 let mut stmt = tx
1718 .prepare(
1719 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1720 VALUES (?, ?, ?, ?);",
1721 )
1722 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1723
Janis Danisevskis66784c42021-01-27 08:40:25 -08001724 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001725 stmt.insert(params![
1726 key_id.0,
1727 p.get_tag().0,
1728 p.key_parameter_value(),
1729 p.security_level().0
1730 ])
1731 .with_context(|| {
1732 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1733 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001734 }
1735 Ok(())
1736 }
1737
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001738 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001739 #[cfg(test)]
1740 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001741 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001742 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001743 })
1744 .context("In insert_key_metadata.")
1745 }
1746
Max Bires2b2e6562020-09-22 11:22:36 -07001747 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1748 /// on the public key.
1749 pub fn store_signed_attestation_certificate_chain(
1750 &mut self,
1751 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001752 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001753 cert_chain: &[u8],
1754 expiration_date: i64,
1755 km_uuid: &Uuid,
1756 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001757 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1758
Max Bires2b2e6562020-09-22 11:22:36 -07001759 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1760 let mut stmt = tx
1761 .prepare(
1762 "SELECT keyentryid
1763 FROM persistent.keymetadata
1764 WHERE tag = ? AND data = ? AND keyentryid IN
1765 (SELECT id
1766 FROM persistent.keyentry
1767 WHERE
1768 alias IS NULL AND
1769 domain IS NULL AND
1770 namespace IS NULL AND
1771 key_type = ? AND
1772 km_uuid = ?);",
1773 )
1774 .context("Failed to store attestation certificate chain.")?;
1775 let mut rows = stmt
1776 .query(params![
1777 KeyMetaData::AttestationRawPubKey,
1778 raw_public_key,
1779 KeyType::Attestation,
1780 km_uuid
1781 ])
1782 .context("Failed to fetch keyid")?;
1783 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1784 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1785 .get(0)
1786 .context("Failed to unpack id.")
1787 })
1788 .context("Failed to get key_id.")?;
1789 let num_updated = tx
1790 .execute(
1791 "UPDATE persistent.keyentry
1792 SET alias = ?
1793 WHERE id = ?;",
1794 params!["signed", key_id],
1795 )
1796 .context("Failed to update alias.")?;
1797 if num_updated != 1 {
1798 return Err(KsError::sys()).context("Alias not updated for the key.");
1799 }
1800 let mut metadata = KeyMetaData::new();
1801 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1802 expiration_date,
1803 )));
1804 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001805 Self::set_blob_internal(
1806 &tx,
1807 key_id,
1808 SubComponentType::CERT_CHAIN,
1809 Some(cert_chain),
1810 None,
1811 )
1812 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001813 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1814 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001815 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001816 })
1817 .context("In store_signed_attestation_certificate_chain: ")
1818 }
1819
1820 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1821 /// currently have a key assigned to it.
1822 pub fn assign_attestation_key(
1823 &mut self,
1824 domain: Domain,
1825 namespace: i64,
1826 km_uuid: &Uuid,
1827 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001828 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1829
Max Bires2b2e6562020-09-22 11:22:36 -07001830 match domain {
1831 Domain::APP | Domain::SELINUX => {}
1832 _ => {
1833 return Err(KsError::sys()).context(format!(
1834 concat!(
1835 "In assign_attestation_key: Domain {:?} ",
1836 "must be either App or SELinux.",
1837 ),
1838 domain
1839 ));
1840 }
1841 }
1842 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1843 let result = tx
1844 .execute(
1845 "UPDATE persistent.keyentry
1846 SET domain=?1, namespace=?2
1847 WHERE
1848 id =
1849 (SELECT MIN(id)
1850 FROM persistent.keyentry
1851 WHERE ALIAS IS NOT NULL
1852 AND domain IS NULL
1853 AND key_type IS ?3
1854 AND state IS ?4
1855 AND km_uuid IS ?5)
1856 AND
1857 (SELECT COUNT(*)
1858 FROM persistent.keyentry
1859 WHERE domain=?1
1860 AND namespace=?2
1861 AND key_type IS ?3
1862 AND state IS ?4
1863 AND km_uuid IS ?5) = 0;",
1864 params![
1865 domain.0 as u32,
1866 namespace,
1867 KeyType::Attestation,
1868 KeyLifeCycle::Live,
1869 km_uuid,
1870 ],
1871 )
1872 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001873 if result == 0 {
1874 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1875 } else if result > 1 {
1876 return Err(KsError::sys())
1877 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001878 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001879 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001880 })
1881 .context("In assign_attestation_key: ")
1882 }
1883
1884 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1885 /// provisioning server, or the maximum number available if there are not num_keys number of
1886 /// entries in the table.
1887 pub fn fetch_unsigned_attestation_keys(
1888 &mut self,
1889 num_keys: i32,
1890 km_uuid: &Uuid,
1891 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001892 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1893
Max Bires2b2e6562020-09-22 11:22:36 -07001894 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1895 let mut stmt = tx
1896 .prepare(
1897 "SELECT data
1898 FROM persistent.keymetadata
1899 WHERE tag = ? AND keyentryid IN
1900 (SELECT id
1901 FROM persistent.keyentry
1902 WHERE
1903 alias IS NULL AND
1904 domain IS NULL AND
1905 namespace IS NULL AND
1906 key_type = ? AND
1907 km_uuid = ?
1908 LIMIT ?);",
1909 )
1910 .context("Failed to prepare statement")?;
1911 let rows = stmt
1912 .query_map(
1913 params![
1914 KeyMetaData::AttestationMacedPublicKey,
1915 KeyType::Attestation,
1916 km_uuid,
1917 num_keys
1918 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001919 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001920 )?
1921 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1922 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001923 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001924 })
1925 .context("In fetch_unsigned_attestation_keys")
1926 }
1927
1928 /// Removes any keys that have expired as of the current time. Returns the number of keys
1929 /// marked unreferenced that are bound to be garbage collected.
1930 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001931 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1932
Max Bires2b2e6562020-09-22 11:22:36 -07001933 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1934 let mut stmt = tx
1935 .prepare(
1936 "SELECT keyentryid, data
1937 FROM persistent.keymetadata
1938 WHERE tag = ? AND keyentryid IN
1939 (SELECT id
1940 FROM persistent.keyentry
1941 WHERE key_type = ?);",
1942 )
1943 .context("Failed to prepare query")?;
1944 let key_ids_to_check = stmt
1945 .query_map(
1946 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1947 |row| Ok((row.get(0)?, row.get(1)?)),
1948 )?
1949 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1950 .context("Failed to get date metadata")?;
1951 let curr_time = DateTime::from_millis_epoch(
1952 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1953 );
1954 let mut num_deleted = 0;
1955 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1956 if Self::mark_unreferenced(&tx, id)? {
1957 num_deleted += 1;
1958 }
1959 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001960 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001961 })
1962 .context("In delete_expired_attestation_keys: ")
1963 }
1964
Max Bires60d7ed12021-03-05 15:59:22 -08001965 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1966 /// they are in. This is useful primarily as a testing mechanism.
1967 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001968 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1969
Max Bires60d7ed12021-03-05 15:59:22 -08001970 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1971 let mut stmt = tx
1972 .prepare(
1973 "SELECT id FROM persistent.keyentry
1974 WHERE key_type IS ?;",
1975 )
1976 .context("Failed to prepare statement")?;
1977 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001978 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001979 .collect::<rusqlite::Result<Vec<i64>>>()
1980 .context("Failed to execute statement")?;
1981 let num_deleted = keys_to_delete
1982 .iter()
1983 .map(|id| Self::mark_unreferenced(&tx, *id))
1984 .collect::<Result<Vec<bool>>>()
1985 .context("Failed to execute mark_unreferenced on a keyid")?
1986 .into_iter()
1987 .filter(|result| *result)
1988 .count() as i64;
1989 Ok(num_deleted).do_gc(num_deleted != 0)
1990 })
1991 .context("In delete_all_attestation_keys: ")
1992 }
1993
Max Bires2b2e6562020-09-22 11:22:36 -07001994 /// Counts the number of keys that will expire by the provided epoch date and the number of
1995 /// keys not currently assigned to a domain.
1996 pub fn get_attestation_pool_status(
1997 &mut self,
1998 date: i64,
1999 km_uuid: &Uuid,
2000 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002001 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
2002
Max Bires2b2e6562020-09-22 11:22:36 -07002003 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2004 let mut stmt = tx.prepare(
2005 "SELECT data
2006 FROM persistent.keymetadata
2007 WHERE tag = ? AND keyentryid IN
2008 (SELECT id
2009 FROM persistent.keyentry
2010 WHERE alias IS NOT NULL
2011 AND key_type = ?
2012 AND km_uuid = ?
2013 AND state = ?);",
2014 )?;
2015 let times = stmt
2016 .query_map(
2017 params![
2018 KeyMetaData::AttestationExpirationDate,
2019 KeyType::Attestation,
2020 km_uuid,
2021 KeyLifeCycle::Live
2022 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002023 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002024 )?
2025 .collect::<rusqlite::Result<Vec<DateTime>>>()
2026 .context("Failed to execute metadata statement")?;
2027 let expiring =
2028 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2029 as i32;
2030 stmt = tx.prepare(
2031 "SELECT alias, domain
2032 FROM persistent.keyentry
2033 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2034 )?;
2035 let rows = stmt
2036 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2037 Ok((row.get(0)?, row.get(1)?))
2038 })?
2039 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2040 .context("Failed to execute keyentry statement")?;
2041 let mut unassigned = 0i32;
2042 let mut attested = 0i32;
2043 let total = rows.len() as i32;
2044 for (alias, domain) in rows {
2045 match (alias, domain) {
2046 (Some(_alias), None) => {
2047 attested += 1;
2048 unassigned += 1;
2049 }
2050 (Some(_alias), Some(_domain)) => {
2051 attested += 1;
2052 }
2053 _ => {}
2054 }
2055 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002056 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002057 })
2058 .context("In get_attestation_pool_status: ")
2059 }
2060
2061 /// Fetches the private key and corresponding certificate chain assigned to a
2062 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2063 /// not assigned, or one CertificateChain.
2064 pub fn retrieve_attestation_key_and_cert_chain(
2065 &mut self,
2066 domain: Domain,
2067 namespace: i64,
2068 km_uuid: &Uuid,
2069 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002070 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2071
Max Bires2b2e6562020-09-22 11:22:36 -07002072 match domain {
2073 Domain::APP | Domain::SELINUX => {}
2074 _ => {
2075 return Err(KsError::sys())
2076 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2077 }
2078 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002079 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2080 let mut stmt = tx.prepare(
2081 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002082 FROM persistent.blobentry
2083 WHERE keyentryid IN
2084 (SELECT id
2085 FROM persistent.keyentry
2086 WHERE key_type = ?
2087 AND domain = ?
2088 AND namespace = ?
2089 AND state = ?
2090 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002091 )?;
2092 let rows = stmt
2093 .query_map(
2094 params![
2095 KeyType::Attestation,
2096 domain.0 as u32,
2097 namespace,
2098 KeyLifeCycle::Live,
2099 km_uuid
2100 ],
2101 |row| Ok((row.get(0)?, row.get(1)?)),
2102 )?
2103 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002104 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002105 if rows.is_empty() {
2106 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002107 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002108 return Err(KsError::sys()).context(format!(
2109 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002110 "Expected to get a single attestation",
2111 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2112 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002113 rows.len()
2114 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002115 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002116 let mut km_blob: Vec<u8> = Vec::new();
2117 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002118 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002119 for row in rows {
2120 let sub_type: SubComponentType = row.0;
2121 match sub_type {
2122 SubComponentType::KEY_BLOB => {
2123 km_blob = row.1;
2124 }
2125 SubComponentType::CERT_CHAIN => {
2126 cert_chain_blob = row.1;
2127 }
Max Biresb2e1d032021-02-08 21:35:05 -08002128 SubComponentType::CERT => {
2129 batch_cert_blob = row.1;
2130 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002131 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2132 }
2133 }
2134 Ok(Some(CertificateChain {
2135 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002136 batch_cert: batch_cert_blob,
2137 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002138 }))
2139 .no_gc()
2140 })
Max Biresb2e1d032021-02-08 21:35:05 -08002141 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002142 }
2143
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002144 /// Updates the alias column of the given key id `newid` with the given alias,
2145 /// and atomically, removes the alias, domain, and namespace from another row
2146 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002147 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2148 /// collector.
2149 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002150 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002151 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002152 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002153 domain: &Domain,
2154 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002155 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002156 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002157 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002158 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002159 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002160 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002161 domain
2162 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002163 }
2164 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002165 let updated = tx
2166 .execute(
2167 "UPDATE persistent.keyentry
2168 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002169 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002170 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2171 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002172 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002173 let result = tx
2174 .execute(
2175 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002176 SET alias = ?, state = ?
2177 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2178 params![
2179 alias,
2180 KeyLifeCycle::Live,
2181 newid.0,
2182 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002183 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002184 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002185 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002186 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002187 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002188 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002189 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002190 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002191 result
2192 ));
2193 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002194 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002195 }
2196
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002197 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2198 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2199 pub fn migrate_key_namespace(
2200 &mut self,
2201 key_id_guard: KeyIdGuard,
2202 destination: &KeyDescriptor,
2203 caller_uid: u32,
2204 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2205 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002206 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2207
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002208 let destination = match destination.domain {
2209 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2210 Domain::SELINUX => (*destination).clone(),
2211 domain => {
2212 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2213 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2214 }
2215 };
2216
2217 // Security critical: Must return immediately on failure. Do not remove the '?';
2218 check_permission(&destination)
2219 .context("In migrate_key_namespace: Trying to check permission.")?;
2220
2221 let alias = destination
2222 .alias
2223 .as_ref()
2224 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2225 .context("In migrate_key_namespace: Alias must be specified.")?;
2226
2227 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2228 // Query the destination location. If there is a key, the migration request fails.
2229 if tx
2230 .query_row(
2231 "SELECT id FROM persistent.keyentry
2232 WHERE alias = ? AND domain = ? AND namespace = ?;",
2233 params![alias, destination.domain.0, destination.nspace],
2234 |_| Ok(()),
2235 )
2236 .optional()
2237 .context("Failed to query destination.")?
2238 .is_some()
2239 {
2240 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2241 .context("Target already exists.");
2242 }
2243
2244 let updated = tx
2245 .execute(
2246 "UPDATE persistent.keyentry
2247 SET alias = ?, domain = ?, namespace = ?
2248 WHERE id = ?;",
2249 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2250 )
2251 .context("Failed to update key entry.")?;
2252
2253 if updated != 1 {
2254 return Err(KsError::sys())
2255 .context(format!("Update succeeded, but {} rows were updated.", updated));
2256 }
2257 Ok(()).no_gc()
2258 })
2259 .context("In migrate_key_namespace:")
2260 }
2261
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002262 /// Store a new key in a single transaction.
2263 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2264 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002265 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2266 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002267 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002268 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002269 key: &KeyDescriptor,
2270 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002271 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002272 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002274 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002275 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002276 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2277
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002278 let (alias, domain, namespace) = match key {
2279 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2280 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2281 (alias, key.domain, nspace)
2282 }
2283 _ => {
2284 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2285 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2286 }
2287 };
2288 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002289 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002290 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002291 let (blob, blob_metadata) = *blob_info;
2292 Self::set_blob_internal(
2293 tx,
2294 key_id.id(),
2295 SubComponentType::KEY_BLOB,
2296 Some(blob),
2297 Some(&blob_metadata),
2298 )
2299 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002300 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002301 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002302 .context("Trying to insert the certificate.")?;
2303 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002304 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002305 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002306 tx,
2307 key_id.id(),
2308 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002309 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002310 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002311 )
2312 .context("Trying to insert the certificate chain.")?;
2313 }
2314 Self::insert_keyparameter_internal(tx, &key_id, params)
2315 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002316 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002317 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002318 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002319 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002320 })
2321 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002322 }
2323
Janis Danisevskis377d1002021-01-27 19:07:48 -08002324 /// Store a new certificate
2325 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2326 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002327 pub fn store_new_certificate(
2328 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002329 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002330 cert: &[u8],
2331 km_uuid: &Uuid,
2332 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002333 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2334
Janis Danisevskis377d1002021-01-27 19:07:48 -08002335 let (alias, domain, namespace) = match key {
2336 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2337 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2338 (alias, key.domain, nspace)
2339 }
2340 _ => {
2341 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2342 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2343 )
2344 }
2345 };
2346 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002347 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002348 .context("Trying to create new key entry.")?;
2349
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002350 Self::set_blob_internal(
2351 tx,
2352 key_id.id(),
2353 SubComponentType::CERT_CHAIN,
2354 Some(cert),
2355 None,
2356 )
2357 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002358
2359 let mut metadata = KeyMetaData::new();
2360 metadata.add(KeyMetaEntry::CreationDate(
2361 DateTime::now().context("Trying to make creation time.")?,
2362 ));
2363
2364 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2365
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002366 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002367 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002368 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002369 })
2370 .context("In store_new_certificate.")
2371 }
2372
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002373 // Helper function loading the key_id given the key descriptor
2374 // tuple comprising domain, namespace, and alias.
2375 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002376 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002377 let alias = key
2378 .alias
2379 .as_ref()
2380 .map_or_else(|| Err(KsError::sys()), Ok)
2381 .context("In load_key_entry_id: Alias must be specified.")?;
2382 let mut stmt = tx
2383 .prepare(
2384 "SELECT id FROM persistent.keyentry
2385 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002386 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002387 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002388 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002389 AND alias = ?
2390 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002391 )
2392 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2393 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002394 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002395 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002396 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002397 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002398 .get(0)
2399 .context("Failed to unpack id.")
2400 })
2401 .context("In load_key_entry_id.")
2402 }
2403
2404 /// This helper function completes the access tuple of a key, which is required
2405 /// to perform access control. The strategy depends on the `domain` field in the
2406 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002407 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002409 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002410 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002411 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002412 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002413 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002414 /// `namespace`.
2415 /// In each case the information returned is sufficient to perform the access
2416 /// check and the key id can be used to load further key artifacts.
2417 fn load_access_tuple(
2418 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002419 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002420 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002421 caller_uid: u32,
2422 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2423 match key.domain {
2424 // Domain App or SELinux. In this case we load the key_id from
2425 // the keyentry database for further loading of key components.
2426 // We already have the full access tuple to perform access control.
2427 // The only distinction is that we use the caller_uid instead
2428 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002429 // Domain::APP.
2430 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002431 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002432 if access_key.domain == Domain::APP {
2433 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002434 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002435 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002436 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002437
2438 Ok((key_id, access_key, None))
2439 }
2440
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002441 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002442 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002443 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002444 let mut stmt = tx
2445 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002446 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002447 WHERE grantee = ? AND id = ?;",
2448 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002449 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002450 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002451 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002452 .context("Domain:Grant: query failed.")?;
2453 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002454 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002455 let r =
2456 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002457 Ok((
2458 r.get(0).context("Failed to unpack key_id.")?,
2459 r.get(1).context("Failed to unpack access_vector.")?,
2460 ))
2461 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002462 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002463 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002464 }
2465
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002466 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002467 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002468 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002469 let (domain, namespace): (Domain, i64) = {
2470 let mut stmt = tx
2471 .prepare(
2472 "SELECT domain, namespace FROM persistent.keyentry
2473 WHERE
2474 id = ?
2475 AND state = ?;",
2476 )
2477 .context("Domain::KEY_ID: prepare statement failed")?;
2478 let mut rows = stmt
2479 .query(params![key.nspace, KeyLifeCycle::Live])
2480 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002481 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002482 let r =
2483 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002484 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002485 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002486 r.get(1).context("Failed to unpack namespace.")?,
2487 ))
2488 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002489 .context("Domain::KEY_ID.")?
2490 };
2491
2492 // We may use a key by id after loading it by grant.
2493 // In this case we have to check if the caller has a grant for this particular
2494 // key. We can skip this if we already know that the caller is the owner.
2495 // But we cannot know this if domain is anything but App. E.g. in the case
2496 // of Domain::SELINUX we have to speculatively check for grants because we have to
2497 // consult the SEPolicy before we know if the caller is the owner.
2498 let access_vector: Option<KeyPermSet> =
2499 if domain != Domain::APP || namespace != caller_uid as i64 {
2500 let access_vector: Option<i32> = tx
2501 .query_row(
2502 "SELECT access_vector FROM persistent.grant
2503 WHERE grantee = ? AND keyentryid = ?;",
2504 params![caller_uid as i64, key.nspace],
2505 |row| row.get(0),
2506 )
2507 .optional()
2508 .context("Domain::KEY_ID: query grant failed.")?;
2509 access_vector.map(|p| p.into())
2510 } else {
2511 None
2512 };
2513
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002514 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002515 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002516 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002517 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002518
Janis Danisevskis45760022021-01-19 16:34:10 -08002519 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002520 }
2521 _ => Err(anyhow!(KsError::sys())),
2522 }
2523 }
2524
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002525 fn load_blob_components(
2526 key_id: i64,
2527 load_bits: KeyEntryLoadBits,
2528 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002529 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002530 let mut stmt = tx
2531 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002532 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002533 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2534 )
2535 .context("In load_blob_components: prepare statement failed.")?;
2536
2537 let mut rows =
2538 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2539
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002540 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002541 let mut cert_blob: Option<Vec<u8>> = None;
2542 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002543 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002544 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002545 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002546 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002547 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002548 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2549 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002550 key_blob = Some((
2551 row.get(0).context("Failed to extract key blob id.")?,
2552 row.get(2).context("Failed to extract key blob.")?,
2553 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002554 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002555 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002556 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002557 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002558 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002559 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002560 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002561 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002562 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002563 (SubComponentType::CERT, _, _)
2564 | (SubComponentType::CERT_CHAIN, _, _)
2565 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002566 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2567 }
2568 Ok(())
2569 })
2570 .context("In load_blob_components.")?;
2571
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002572 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2573 Ok(Some((
2574 blob,
2575 BlobMetaData::load_from_db(blob_id, tx)
2576 .context("In load_blob_components: Trying to load blob_metadata.")?,
2577 )))
2578 })?;
2579
2580 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002581 }
2582
2583 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2584 let mut stmt = tx
2585 .prepare(
2586 "SELECT tag, data, security_level from persistent.keyparameter
2587 WHERE keyentryid = ?;",
2588 )
2589 .context("In load_key_parameters: prepare statement failed.")?;
2590
2591 let mut parameters: Vec<KeyParameter> = Vec::new();
2592
2593 let mut rows =
2594 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002595 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002596 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2597 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002598 parameters.push(
2599 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2600 .context("Failed to read KeyParameter.")?,
2601 );
2602 Ok(())
2603 })
2604 .context("In load_key_parameters.")?;
2605
2606 Ok(parameters)
2607 }
2608
Qi Wub9433b52020-12-01 14:52:46 +08002609 /// Decrements the usage count of a limited use key. This function first checks whether the
2610 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2611 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2612 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002613 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002614 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2615
Qi Wub9433b52020-12-01 14:52:46 +08002616 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2617 let limit: Option<i32> = tx
2618 .query_row(
2619 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2620 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2621 |row| row.get(0),
2622 )
2623 .optional()
2624 .context("Trying to load usage count")?;
2625
2626 let limit = limit
2627 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2628 .context("The Key no longer exists. Key is exhausted.")?;
2629
2630 tx.execute(
2631 "UPDATE persistent.keyparameter
2632 SET data = data - 1
2633 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2634 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2635 )
2636 .context("Failed to update key usage count.")?;
2637
2638 match limit {
2639 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002640 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002641 .context("Trying to mark limited use key for deletion."),
2642 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002643 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002644 }
2645 })
2646 .context("In check_and_update_key_usage_count.")
2647 }
2648
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002649 /// Load a key entry by the given key descriptor.
2650 /// It uses the `check_permission` callback to verify if the access is allowed
2651 /// given the key access tuple read from the database using `load_access_tuple`.
2652 /// With `load_bits` the caller may specify which blobs shall be loaded from
2653 /// the blob database.
2654 pub fn load_key_entry(
2655 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002656 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002657 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002658 load_bits: KeyEntryLoadBits,
2659 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002660 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2661 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002662 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2663
Janis Danisevskis66784c42021-01-27 08:40:25 -08002664 loop {
2665 match self.load_key_entry_internal(
2666 key,
2667 key_type,
2668 load_bits,
2669 caller_uid,
2670 &check_permission,
2671 ) {
2672 Ok(result) => break Ok(result),
2673 Err(e) => {
2674 if Self::is_locked_error(&e) {
2675 std::thread::sleep(std::time::Duration::from_micros(500));
2676 continue;
2677 } else {
2678 return Err(e).context("In load_key_entry.");
2679 }
2680 }
2681 }
2682 }
2683 }
2684
2685 fn load_key_entry_internal(
2686 &mut self,
2687 key: &KeyDescriptor,
2688 key_type: KeyType,
2689 load_bits: KeyEntryLoadBits,
2690 caller_uid: u32,
2691 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002692 ) -> Result<(KeyIdGuard, KeyEntry)> {
2693 // KEY ID LOCK 1/2
2694 // If we got a key descriptor with a key id we can get the lock right away.
2695 // Otherwise we have to defer it until we know the key id.
2696 let key_id_guard = match key.domain {
2697 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2698 _ => None,
2699 };
2700
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002701 let tx = self
2702 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002703 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002704 .context("In load_key_entry: Failed to initialize transaction.")?;
2705
2706 // Load the key_id and complete the access control tuple.
2707 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002708 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2709 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002710
2711 // Perform access control. It is vital that we return here if the permission is denied.
2712 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002713 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002714
Janis Danisevskisaec14592020-11-12 09:41:49 -08002715 // KEY ID LOCK 2/2
2716 // If we did not get a key id lock by now, it was because we got a key descriptor
2717 // without a key id. At this point we got the key id, so we can try and get a lock.
2718 // However, we cannot block here, because we are in the middle of the transaction.
2719 // So first we try to get the lock non blocking. If that fails, we roll back the
2720 // transaction and block until we get the lock. After we successfully got the lock,
2721 // we start a new transaction and load the access tuple again.
2722 //
2723 // We don't need to perform access control again, because we already established
2724 // that the caller had access to the given key. But we need to make sure that the
2725 // key id still exists. So we have to load the key entry by key id this time.
2726 let (key_id_guard, tx) = match key_id_guard {
2727 None => match KEY_ID_LOCK.try_get(key_id) {
2728 None => {
2729 // Roll back the transaction.
2730 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002731
Janis Danisevskisaec14592020-11-12 09:41:49 -08002732 // Block until we have a key id lock.
2733 let key_id_guard = KEY_ID_LOCK.get(key_id);
2734
2735 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002736 let tx = self
2737 .conn
2738 .unchecked_transaction()
2739 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002740
2741 Self::load_access_tuple(
2742 &tx,
2743 // This time we have to load the key by the retrieved key id, because the
2744 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002745 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002746 domain: Domain::KEY_ID,
2747 nspace: key_id,
2748 ..Default::default()
2749 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002750 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002751 caller_uid,
2752 )
2753 .context("In load_key_entry. (deferred key lock)")?;
2754 (key_id_guard, tx)
2755 }
2756 Some(l) => (l, tx),
2757 },
2758 Some(key_id_guard) => (key_id_guard, tx),
2759 };
2760
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002761 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2762 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002763
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002764 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2765
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002766 Ok((key_id_guard, key_entry))
2767 }
2768
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002769 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002770 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002771 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2772 .context("Trying to delete keyentry.")?;
2773 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2774 .context("Trying to delete keymetadata.")?;
2775 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2776 .context("Trying to delete keyparameters.")?;
2777 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2778 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002779 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002780 }
2781
2782 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002783 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002784 pub fn unbind_key(
2785 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002786 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002787 key_type: KeyType,
2788 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002789 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002790 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002791 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2792
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002793 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2794 let (key_id, access_key_descriptor, access_vector) =
2795 Self::load_access_tuple(tx, key, key_type, caller_uid)
2796 .context("Trying to get access tuple.")?;
2797
2798 // Perform access control. It is vital that we return here if the permission is denied.
2799 // So do not touch that '?' at the end.
2800 check_permission(&access_key_descriptor, access_vector)
2801 .context("While checking permission.")?;
2802
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002803 Self::mark_unreferenced(tx, key_id)
2804 .map(|need_gc| (need_gc, ()))
2805 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002806 })
2807 .context("In unbind_key.")
2808 }
2809
Max Bires8e93d2b2021-01-14 13:17:59 -08002810 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2811 tx.query_row(
2812 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2813 params![key_id],
2814 |row| row.get(0),
2815 )
2816 .context("In get_key_km_uuid.")
2817 }
2818
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002819 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2820 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2821 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002822 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2823
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002824 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2825 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2826 .context("In unbind_keys_for_namespace.");
2827 }
2828 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2829 tx.execute(
2830 "DELETE FROM persistent.keymetadata
2831 WHERE keyentryid IN (
2832 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002833 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002834 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002835 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002836 )
2837 .context("Trying to delete keymetadata.")?;
2838 tx.execute(
2839 "DELETE FROM persistent.keyparameter
2840 WHERE keyentryid IN (
2841 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002842 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002843 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002844 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002845 )
2846 .context("Trying to delete keyparameters.")?;
2847 tx.execute(
2848 "DELETE FROM persistent.grant
2849 WHERE keyentryid IN (
2850 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002851 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002852 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002853 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002854 )
2855 .context("Trying to delete grants.")?;
2856 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002857 "DELETE FROM persistent.keyentry
2858 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2859 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002860 )
2861 .context("Trying to delete keyentry.")?;
2862 Ok(()).need_gc()
2863 })
2864 .context("In unbind_keys_for_namespace")
2865 }
2866
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002867 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2868 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2869 {
2870 tx.execute(
2871 "DELETE FROM persistent.keymetadata
2872 WHERE keyentryid IN (
2873 SELECT id FROM persistent.keyentry
2874 WHERE state = ?
2875 );",
2876 params![KeyLifeCycle::Unreferenced],
2877 )
2878 .context("Trying to delete keymetadata.")?;
2879 tx.execute(
2880 "DELETE FROM persistent.keyparameter
2881 WHERE keyentryid IN (
2882 SELECT id FROM persistent.keyentry
2883 WHERE state = ?
2884 );",
2885 params![KeyLifeCycle::Unreferenced],
2886 )
2887 .context("Trying to delete keyparameters.")?;
2888 tx.execute(
2889 "DELETE FROM persistent.grant
2890 WHERE keyentryid IN (
2891 SELECT id FROM persistent.keyentry
2892 WHERE state = ?
2893 );",
2894 params![KeyLifeCycle::Unreferenced],
2895 )
2896 .context("Trying to delete grants.")?;
2897 tx.execute(
2898 "DELETE FROM persistent.keyentry
2899 WHERE state = ?;",
2900 params![KeyLifeCycle::Unreferenced],
2901 )
2902 .context("Trying to delete keyentry.")?;
2903 Result::<()>::Ok(())
2904 }
2905 .context("In cleanup_unreferenced")
2906 }
2907
Hasini Gunasingheda895552021-01-27 19:34:37 +00002908 /// Delete the keys created on behalf of the user, denoted by the user id.
2909 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2910 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2911 /// The caller of this function should notify the gc if the returned value is true.
2912 pub fn unbind_keys_for_user(
2913 &mut self,
2914 user_id: u32,
2915 keep_non_super_encrypted_keys: bool,
2916 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002917 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2918
Hasini Gunasingheda895552021-01-27 19:34:37 +00002919 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2920 let mut stmt = tx
2921 .prepare(&format!(
2922 "SELECT id from persistent.keyentry
2923 WHERE (
2924 key_type = ?
2925 AND domain = ?
2926 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2927 AND state = ?
2928 ) OR (
2929 key_type = ?
2930 AND namespace = ?
2931 AND alias = ?
2932 AND state = ?
2933 );",
2934 aid_user_offset = AID_USER_OFFSET
2935 ))
2936 .context(concat!(
2937 "In unbind_keys_for_user. ",
2938 "Failed to prepare the query to find the keys created by apps."
2939 ))?;
2940
2941 let mut rows = stmt
2942 .query(params![
2943 // WHERE client key:
2944 KeyType::Client,
2945 Domain::APP.0 as u32,
2946 user_id,
2947 KeyLifeCycle::Live,
2948 // OR super key:
2949 KeyType::Super,
2950 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002951 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002952 KeyLifeCycle::Live
2953 ])
2954 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2955
2956 let mut key_ids: Vec<i64> = Vec::new();
2957 db_utils::with_rows_extract_all(&mut rows, |row| {
2958 key_ids
2959 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2960 Ok(())
2961 })
2962 .context("In unbind_keys_for_user.")?;
2963
2964 let mut notify_gc = false;
2965 for key_id in key_ids {
2966 if keep_non_super_encrypted_keys {
2967 // Load metadata and filter out non-super-encrypted keys.
2968 if let (_, Some((_, blob_metadata)), _, _) =
2969 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2970 .context("In unbind_keys_for_user: Trying to load blob info.")?
2971 {
2972 if blob_metadata.encrypted_by().is_none() {
2973 continue;
2974 }
2975 }
2976 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002977 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002978 .context("In unbind_keys_for_user.")?
2979 || notify_gc;
2980 }
2981 Ok(()).do_gc(notify_gc)
2982 })
2983 .context("In unbind_keys_for_user.")
2984 }
2985
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002986 fn load_key_components(
2987 tx: &Transaction,
2988 load_bits: KeyEntryLoadBits,
2989 key_id: i64,
2990 ) -> Result<KeyEntry> {
2991 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2992
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002993 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002994 Self::load_blob_components(key_id, load_bits, &tx)
2995 .context("In load_key_components.")?;
2996
Max Bires8e93d2b2021-01-14 13:17:59 -08002997 let parameters = Self::load_key_parameters(key_id, &tx)
2998 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002999
Max Bires8e93d2b2021-01-14 13:17:59 -08003000 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
3001 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003002
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003003 Ok(KeyEntry {
3004 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003005 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003006 cert: cert_blob,
3007 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003008 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003009 parameters,
3010 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003011 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003012 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003013 }
3014
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003015 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3016 /// The key descriptors will have the domain, nspace, and alias field set.
3017 /// Domain must be APP or SELINUX, the caller must make sure of that.
3018 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003019 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3020
Janis Danisevskis66784c42021-01-27 08:40:25 -08003021 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3022 let mut stmt = tx
3023 .prepare(
3024 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003025 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003026 )
3027 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003028
Janis Danisevskis66784c42021-01-27 08:40:25 -08003029 let mut rows = stmt
3030 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
3031 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003032
Janis Danisevskis66784c42021-01-27 08:40:25 -08003033 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3034 db_utils::with_rows_extract_all(&mut rows, |row| {
3035 descriptors.push(KeyDescriptor {
3036 domain,
3037 nspace: namespace,
3038 alias: Some(row.get(0).context("Trying to extract alias.")?),
3039 blob: None,
3040 });
3041 Ok(())
3042 })
3043 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003044 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003045 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003046 }
3047
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003048 /// Adds a grant to the grant table.
3049 /// Like `load_key_entry` this function loads the access tuple before
3050 /// it uses the callback for a permission check. Upon success,
3051 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3052 /// grant table. The new row will have a randomized id, which is used as
3053 /// grant id in the namespace field of the resulting KeyDescriptor.
3054 pub fn grant(
3055 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003056 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003057 caller_uid: u32,
3058 grantee_uid: u32,
3059 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003060 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003061 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003062 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3063
Janis Danisevskis66784c42021-01-27 08:40:25 -08003064 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3065 // Load the key_id and complete the access control tuple.
3066 // We ignore the access vector here because grants cannot be granted.
3067 // The access vector returned here expresses the permissions the
3068 // grantee has if key.domain == Domain::GRANT. But this vector
3069 // cannot include the grant permission by design, so there is no way the
3070 // subsequent permission check can pass.
3071 // We could check key.domain == Domain::GRANT and fail early.
3072 // But even if we load the access tuple by grant here, the permission
3073 // check denies the attempt to create a grant by grant descriptor.
3074 let (key_id, access_key_descriptor, _) =
3075 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3076 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003077
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 // Perform access control. It is vital that we return here if the permission
3079 // was denied. So do not touch that '?' at the end of the line.
3080 // This permission check checks if the caller has the grant permission
3081 // for the given key and in addition to all of the permissions
3082 // expressed in `access_vector`.
3083 check_permission(&access_key_descriptor, &access_vector)
3084 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003085
Janis Danisevskis66784c42021-01-27 08:40:25 -08003086 let grant_id = if let Some(grant_id) = tx
3087 .query_row(
3088 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003089 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003090 params![key_id, grantee_uid],
3091 |row| row.get(0),
3092 )
3093 .optional()
3094 .context("In grant: Failed get optional existing grant id.")?
3095 {
3096 tx.execute(
3097 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003098 SET access_vector = ?
3099 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003100 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003101 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003102 .context("In grant: Failed to update existing grant.")?;
3103 grant_id
3104 } else {
3105 Self::insert_with_retry(|id| {
3106 tx.execute(
3107 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3108 VALUES (?, ?, ?, ?);",
3109 params![id, grantee_uid, key_id, i32::from(access_vector)],
3110 )
3111 })
3112 .context("In grant")?
3113 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003114
Janis Danisevskis66784c42021-01-27 08:40:25 -08003115 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003116 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003117 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003118 }
3119
3120 /// This function checks permissions like `grant` and `load_key_entry`
3121 /// before removing a grant from the grant table.
3122 pub fn ungrant(
3123 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003124 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003125 caller_uid: u32,
3126 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003127 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003128 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003129 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3130
Janis Danisevskis66784c42021-01-27 08:40:25 -08003131 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3132 // Load the key_id and complete the access control tuple.
3133 // We ignore the access vector here because grants cannot be granted.
3134 let (key_id, access_key_descriptor, _) =
3135 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3136 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003137
Janis Danisevskis66784c42021-01-27 08:40:25 -08003138 // Perform access control. We must return here if the permission
3139 // was denied. So do not touch the '?' at the end of this line.
3140 check_permission(&access_key_descriptor)
3141 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003142
Janis Danisevskis66784c42021-01-27 08:40:25 -08003143 tx.execute(
3144 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003145 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003146 params![key_id, grantee_uid],
3147 )
3148 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003149
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003150 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003151 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003152 }
3153
Joel Galenson845f74b2020-09-09 14:11:55 -07003154 // Generates a random id and passes it to the given function, which will
3155 // try to insert it into a database. If that insertion fails, retry;
3156 // otherwise return the id.
3157 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3158 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003159 let newid: i64 = match random() {
3160 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3161 i => i,
3162 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003163 match inserter(newid) {
3164 // If the id already existed, try again.
3165 Err(rusqlite::Error::SqliteFailure(
3166 libsqlite3_sys::Error {
3167 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3168 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3169 },
3170 _,
3171 )) => (),
3172 Err(e) => {
3173 return Err(e).context("In insert_with_retry: failed to insert into database.")
3174 }
3175 _ => return Ok(newid),
3176 }
3177 }
3178 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003179
3180 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
3181 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003182 let _wp = wd::watch_millis("KeystoreDB::insert_auth_token", 500);
3183
Janis Danisevskis66784c42021-01-27 08:40:25 -08003184 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3185 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003186 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
3187 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
3188 params![
3189 auth_token.challenge,
3190 auth_token.userId,
3191 auth_token.authenticatorId,
3192 auth_token.authenticatorType.0 as i32,
3193 auth_token.timestamp.milliSeconds as i64,
3194 auth_token.mac,
3195 MonotonicRawTime::now(),
3196 ],
3197 )
3198 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003199 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003200 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003201 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003202
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003203 /// Find the newest auth token matching the given predicate.
3204 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003205 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003206 p: F,
3207 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
3208 where
3209 F: Fn(&AuthTokenEntry) -> bool,
3210 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003211 let _wp = wd::watch_millis("KeystoreDB::find_auth_token_entry", 500);
3212
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003213 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3214 let mut stmt = tx
3215 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
3216 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003217
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003218 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003219
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003220 while let Some(row) = rows.next().context("Failed to get next row.")? {
3221 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003222 HardwareAuthToken {
3223 challenge: row.get(1)?,
3224 userId: row.get(2)?,
3225 authenticatorId: row.get(3)?,
3226 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3227 timestamp: Timestamp { milliSeconds: row.get(5)? },
3228 mac: row.get(6)?,
3229 },
3230 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003231 );
3232 if p(&entry) {
3233 return Ok(Some((
3234 entry,
3235 Self::get_last_off_body(tx)
3236 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003237 )))
3238 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003239 }
3240 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003241 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003242 })
3243 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003244 }
3245
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003246 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003247 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003248 let _wp = wd::watch_millis("KeystoreDB::insert_last_off_body", 500);
3249
Janis Danisevskis66784c42021-01-27 08:40:25 -08003250 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3251 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003252 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3253 params!["last_off_body", last_off_body],
3254 )
3255 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003256 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003257 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003258 }
3259
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003260 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003261 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003262 let _wp = wd::watch_millis("KeystoreDB::update_last_off_body", 500);
3263
Janis Danisevskis66784c42021-01-27 08:40:25 -08003264 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3265 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003266 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3267 params![last_off_body, "last_off_body"],
3268 )
3269 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003270 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003271 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003272 }
3273
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003274 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003275 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003276 let _wp = wd::watch_millis("KeystoreDB::get_last_off_body", 500);
3277
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003278 tx.query_row(
3279 "SELECT value from perboot.metadata WHERE key = ?;",
3280 params!["last_off_body"],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07003281 |row| row.get(0),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003282 )
3283 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003284 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003285}
3286
3287#[cfg(test)]
3288mod tests {
3289
3290 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003291 use crate::key_parameter::{
3292 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3293 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3294 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003295 use crate::key_perm_set;
3296 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003297 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003298 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003299 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3300 HardwareAuthToken::HardwareAuthToken,
3301 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003302 };
3303 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003304 Timestamp::Timestamp,
3305 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003306 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003307 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003308 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003309 use std::collections::BTreeMap;
3310 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003311 use std::sync::atomic::{AtomicU8, Ordering};
3312 use std::sync::Arc;
3313 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003314 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003315 #[cfg(disabled)]
3316 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003317
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003318 fn new_test_db() -> Result<KeystoreDB> {
3319 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3320
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003321 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003322 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003323 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003324 })?;
3325 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003326 }
3327
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003328 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3329 where
3330 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3331 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003332 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003333
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003334 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003335 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003336
Janis Danisevskis3395f862021-05-06 10:54:17 -07003337 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003338 }
3339
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003340 fn rebind_alias(
3341 db: &mut KeystoreDB,
3342 newid: &KeyIdGuard,
3343 alias: &str,
3344 domain: Domain,
3345 namespace: i64,
3346 ) -> Result<bool> {
3347 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003348 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003349 })
3350 .context("In rebind_alias.")
3351 }
3352
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003353 #[test]
3354 fn datetime() -> Result<()> {
3355 let conn = Connection::open_in_memory()?;
3356 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3357 let now = SystemTime::now();
3358 let duration = Duration::from_secs(1000);
3359 let then = now.checked_sub(duration).unwrap();
3360 let soon = now.checked_add(duration).unwrap();
3361 conn.execute(
3362 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3363 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3364 )?;
3365 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3366 let mut rows = stmt.query(NO_PARAMS)?;
3367 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3368 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3369 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3370 assert!(rows.next()?.is_none());
3371 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3372 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3373 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3374 Ok(())
3375 }
3376
Joel Galenson0891bc12020-07-20 10:37:03 -07003377 // Ensure that we're using the "injected" random function, not the real one.
3378 #[test]
3379 fn test_mocked_random() {
3380 let rand1 = random();
3381 let rand2 = random();
3382 let rand3 = random();
3383 if rand1 == rand2 {
3384 assert_eq!(rand2 + 1, rand3);
3385 } else {
3386 assert_eq!(rand1 + 1, rand2);
3387 assert_eq!(rand2, rand3);
3388 }
3389 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003390
Joel Galenson26f4d012020-07-17 14:57:21 -07003391 // Test that we have the correct tables.
3392 #[test]
3393 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003394 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003395 let tables = db
3396 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003397 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003398 .query_map(params![], |row| row.get(0))?
3399 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003400 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003401 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003402 assert_eq!(tables[1], "blobmetadata");
3403 assert_eq!(tables[2], "grant");
3404 assert_eq!(tables[3], "keyentry");
3405 assert_eq!(tables[4], "keymetadata");
3406 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003407 let tables = db
3408 .conn
3409 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3410 .query_map(params![], |row| row.get(0))?
3411 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003412
3413 assert_eq!(tables.len(), 2);
3414 assert_eq!(tables[0], "authtoken");
3415 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003416 Ok(())
3417 }
3418
3419 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003420 fn test_auth_token_table_invariant() -> Result<()> {
3421 let mut db = new_test_db()?;
3422 let auth_token1 = HardwareAuthToken {
3423 challenge: i64::MAX,
3424 userId: 200,
3425 authenticatorId: 200,
3426 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3427 timestamp: Timestamp { milliSeconds: 500 },
3428 mac: String::from("mac").into_bytes(),
3429 };
3430 db.insert_auth_token(&auth_token1)?;
3431 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3432 assert_eq!(auth_tokens_returned.len(), 1);
3433
3434 // insert another auth token with the same values for the columns in the UNIQUE constraint
3435 // of the auth token table and different value for timestamp
3436 let auth_token2 = HardwareAuthToken {
3437 challenge: i64::MAX,
3438 userId: 200,
3439 authenticatorId: 200,
3440 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3441 timestamp: Timestamp { milliSeconds: 600 },
3442 mac: String::from("mac").into_bytes(),
3443 };
3444
3445 db.insert_auth_token(&auth_token2)?;
3446 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3447 assert_eq!(auth_tokens_returned.len(), 1);
3448
3449 if let Some(auth_token) = auth_tokens_returned.pop() {
3450 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3451 }
3452
3453 // insert another auth token with the different values for the columns in the UNIQUE
3454 // constraint of the auth token table
3455 let auth_token3 = HardwareAuthToken {
3456 challenge: i64::MAX,
3457 userId: 201,
3458 authenticatorId: 200,
3459 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3460 timestamp: Timestamp { milliSeconds: 600 },
3461 mac: String::from("mac").into_bytes(),
3462 };
3463
3464 db.insert_auth_token(&auth_token3)?;
3465 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3466 assert_eq!(auth_tokens_returned.len(), 2);
3467
3468 Ok(())
3469 }
3470
3471 // utility function for test_auth_token_table_invariant()
3472 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3473 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3474
3475 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3476 .query_map(NO_PARAMS, |row| {
3477 Ok(AuthTokenEntry::new(
3478 HardwareAuthToken {
3479 challenge: row.get(1)?,
3480 userId: row.get(2)?,
3481 authenticatorId: row.get(3)?,
3482 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3483 timestamp: Timestamp { milliSeconds: row.get(5)? },
3484 mac: row.get(6)?,
3485 },
3486 row.get(7)?,
3487 ))
3488 })?
3489 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3490 Ok(auth_token_entries)
3491 }
3492
3493 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003494 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003495 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003496 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003497
Janis Danisevskis66784c42021-01-27 08:40:25 -08003498 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003499 let entries = get_keyentry(&db)?;
3500 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003501
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003502 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003503
3504 let entries_new = get_keyentry(&db)?;
3505 assert_eq!(entries, entries_new);
3506 Ok(())
3507 }
3508
3509 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003510 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003511 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3512 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003513 }
3514
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003515 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003516
Janis Danisevskis66784c42021-01-27 08:40:25 -08003517 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3518 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003519
3520 let entries = get_keyentry(&db)?;
3521 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003522 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3523 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003524
3525 // Test that we must pass in a valid Domain.
3526 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003527 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003528 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003529 );
3530 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003531 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003532 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003533 );
3534 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003535 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003536 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003537 );
3538
3539 Ok(())
3540 }
3541
Joel Galenson33c04ad2020-08-03 11:04:38 -07003542 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003543 fn test_add_unsigned_key() -> Result<()> {
3544 let mut db = new_test_db()?;
3545 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3546 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3547 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3548 db.create_attestation_key_entry(
3549 &public_key,
3550 &raw_public_key,
3551 &private_key,
3552 &KEYSTORE_UUID,
3553 )?;
3554 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3555 assert_eq!(keys.len(), 1);
3556 assert_eq!(keys[0], public_key);
3557 Ok(())
3558 }
3559
3560 #[test]
3561 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3562 let mut db = new_test_db()?;
3563 let expiration_date: i64 = 20;
3564 let namespace: i64 = 30;
3565 let base_byte: u8 = 1;
3566 let loaded_values =
3567 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3568 let chain =
3569 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3570 assert_eq!(true, chain.is_some());
3571 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003572 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003573 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3574 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003575 Ok(())
3576 }
3577
3578 #[test]
3579 fn test_get_attestation_pool_status() -> Result<()> {
3580 let mut db = new_test_db()?;
3581 let namespace: i64 = 30;
3582 load_attestation_key_pool(
3583 &mut db, 10, /* expiration */
3584 namespace, 0x01, /* base_byte */
3585 )?;
3586 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3587 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3588 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3589 assert_eq!(status.expiring, 0);
3590 assert_eq!(status.attested, 3);
3591 assert_eq!(status.unassigned, 0);
3592 assert_eq!(status.total, 3);
3593 assert_eq!(
3594 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3595 1
3596 );
3597 assert_eq!(
3598 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3599 2
3600 );
3601 assert_eq!(
3602 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3603 3
3604 );
3605 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3606 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3607 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3608 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003609 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003610 db.create_attestation_key_entry(
3611 &public_key,
3612 &raw_public_key,
3613 &private_key,
3614 &KEYSTORE_UUID,
3615 )?;
3616 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3617 assert_eq!(status.attested, 3);
3618 assert_eq!(status.unassigned, 0);
3619 assert_eq!(status.total, 4);
3620 db.store_signed_attestation_certificate_chain(
3621 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003622 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003623 &cert_chain,
3624 20,
3625 &KEYSTORE_UUID,
3626 )?;
3627 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3628 assert_eq!(status.attested, 4);
3629 assert_eq!(status.unassigned, 1);
3630 assert_eq!(status.total, 4);
3631 Ok(())
3632 }
3633
3634 #[test]
3635 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003636 let temp_dir =
3637 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3638 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003639 let expiration_date: i64 =
3640 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3641 let namespace: i64 = 30;
3642 let namespace_del1: i64 = 45;
3643 let namespace_del2: i64 = 60;
3644 let entry_values = load_attestation_key_pool(
3645 &mut db,
3646 expiration_date,
3647 namespace,
3648 0x01, /* base_byte */
3649 )?;
3650 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3651 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003652
3653 let blob_entry_row_count: u32 = db
3654 .conn
3655 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3656 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003657 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3658 // one key, one certificate chain, and one certificate.
3659 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003660
Max Bires2b2e6562020-09-22 11:22:36 -07003661 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3662
3663 let mut cert_chain =
3664 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003665 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003666 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003667 assert_eq!(entry_values.batch_cert, value.batch_cert);
3668 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003669 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003670
3671 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3672 Domain::APP,
3673 namespace_del1,
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 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3678 Domain::APP,
3679 namespace_del2,
3680 &KEYSTORE_UUID,
3681 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003682 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003683
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003684 // Give the garbage collector half a second to catch up.
3685 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003686
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003687 let blob_entry_row_count: u32 = db
3688 .conn
3689 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3690 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003691 // There shound be 3 blob entries left, because we deleted two of the attestation
3692 // key entries with three blobs each.
3693 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003694
Max Bires2b2e6562020-09-22 11:22:36 -07003695 Ok(())
3696 }
3697
3698 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003699 fn test_delete_all_attestation_keys() -> Result<()> {
3700 let mut db = new_test_db()?;
3701 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3702 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3703 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3704 let result = db.delete_all_attestation_keys()?;
3705
3706 // Give the garbage collector half a second to catch up.
3707 std::thread::sleep(Duration::from_millis(500));
3708
3709 // Attestation keys should be deleted, and the regular key should remain.
3710 assert_eq!(result, 2);
3711
3712 Ok(())
3713 }
3714
3715 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003716 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003717 fn extractor(
3718 ke: &KeyEntryRow,
3719 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3720 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003721 }
3722
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003723 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003724 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3725 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003726 let entries = get_keyentry(&db)?;
3727 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003728 assert_eq!(
3729 extractor(&entries[0]),
3730 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3731 );
3732 assert_eq!(
3733 extractor(&entries[1]),
3734 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3735 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003736
3737 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003738 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003739 let entries = get_keyentry(&db)?;
3740 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003741 assert_eq!(
3742 extractor(&entries[0]),
3743 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3744 );
3745 assert_eq!(
3746 extractor(&entries[1]),
3747 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3748 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003749
3750 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003751 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003752 let entries = get_keyentry(&db)?;
3753 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003754 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3755 assert_eq!(
3756 extractor(&entries[1]),
3757 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3758 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003759
3760 // Test that we must pass in a valid Domain.
3761 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003762 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003763 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003764 );
3765 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003766 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003767 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003768 );
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::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003771 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003772 );
3773
3774 // Test that we correctly handle setting an alias for something that does not exist.
3775 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003776 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003777 "Expected to update a single entry but instead updated 0",
3778 );
3779 // Test that we correctly abort the transaction in this case.
3780 let entries = get_keyentry(&db)?;
3781 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003782 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3783 assert_eq!(
3784 extractor(&entries[1]),
3785 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3786 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003787
3788 Ok(())
3789 }
3790
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003791 #[test]
3792 fn test_grant_ungrant() -> Result<()> {
3793 const CALLER_UID: u32 = 15;
3794 const GRANTEE_UID: u32 = 12;
3795 const SELINUX_NAMESPACE: i64 = 7;
3796
3797 let mut db = new_test_db()?;
3798 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003799 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3800 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3801 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003802 )?;
3803 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003804 domain: super::Domain::APP,
3805 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003806 alias: Some("key".to_string()),
3807 blob: None,
3808 };
3809 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3810 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3811
3812 // Reset totally predictable random number generator in case we
3813 // are not the first test running on this thread.
3814 reset_random();
3815 let next_random = 0i64;
3816
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003817 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003818 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003819 assert_eq!(*a, PVEC1);
3820 assert_eq!(
3821 *k,
3822 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003823 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003824 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003825 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003826 alias: Some("key".to_string()),
3827 blob: None,
3828 }
3829 );
3830 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003831 })
3832 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003833
3834 assert_eq!(
3835 app_granted_key,
3836 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003837 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003838 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003839 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003840 alias: None,
3841 blob: None,
3842 }
3843 );
3844
3845 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003846 domain: super::Domain::SELINUX,
3847 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003848 alias: Some("yek".to_string()),
3849 blob: None,
3850 };
3851
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003852 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003853 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003854 assert_eq!(*a, PVEC1);
3855 assert_eq!(
3856 *k,
3857 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003858 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003859 // namespace must be the supplied SELinux
3860 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003861 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003862 alias: Some("yek".to_string()),
3863 blob: None,
3864 }
3865 );
3866 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003867 })
3868 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003869
3870 assert_eq!(
3871 selinux_granted_key,
3872 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003873 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003874 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003875 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003876 alias: None,
3877 blob: None,
3878 }
3879 );
3880
3881 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003882 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003883 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003884 assert_eq!(*a, PVEC2);
3885 assert_eq!(
3886 *k,
3887 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003888 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003889 // namespace must be the supplied SELinux
3890 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003891 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003892 alias: Some("yek".to_string()),
3893 blob: None,
3894 }
3895 );
3896 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003897 })
3898 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003899
3900 assert_eq!(
3901 selinux_granted_key,
3902 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003903 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003904 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003905 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003906 alias: None,
3907 blob: None,
3908 }
3909 );
3910
3911 {
3912 // Limiting scope of stmt, because it borrows db.
3913 let mut stmt = db
3914 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003915 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003916 let mut rows =
3917 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3918 Ok((
3919 row.get(0)?,
3920 row.get(1)?,
3921 row.get(2)?,
3922 KeyPermSet::from(row.get::<_, i32>(3)?),
3923 ))
3924 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003925
3926 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003927 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003928 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003929 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003930 assert!(rows.next().is_none());
3931 }
3932
3933 debug_dump_keyentry_table(&mut db)?;
3934 println!("app_key {:?}", app_key);
3935 println!("selinux_key {:?}", selinux_key);
3936
Janis Danisevskis66784c42021-01-27 08:40:25 -08003937 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3938 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003939
3940 Ok(())
3941 }
3942
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003943 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003944 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3945 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3946
3947 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003948 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003949 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003950 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003951 let mut blob_metadata = BlobMetaData::new();
3952 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3953 db.set_blob(
3954 &key_id,
3955 SubComponentType::KEY_BLOB,
3956 Some(TEST_KEY_BLOB),
3957 Some(&blob_metadata),
3958 )?;
3959 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3960 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003961 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003962
3963 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003964 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003965 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003966 )?;
3967 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003968 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3969 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003970 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003971 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003972 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003973 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003974 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003975 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003976 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003977
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003978 drop(rows);
3979 drop(stmt);
3980
3981 assert_eq!(
3982 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3983 BlobMetaData::load_from_db(id, tx).no_gc()
3984 })
3985 .expect("Should find blob metadata."),
3986 blob_metadata
3987 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003988 Ok(())
3989 }
3990
3991 static TEST_ALIAS: &str = "my super duper key";
3992
3993 #[test]
3994 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3995 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003996 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003997 .context("test_insert_and_load_full_keyentry_domain_app")?
3998 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003999 let (_key_guard, key_entry) = db
4000 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004001 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004002 domain: Domain::APP,
4003 nspace: 0,
4004 alias: Some(TEST_ALIAS.to_string()),
4005 blob: None,
4006 },
4007 KeyType::Client,
4008 KeyEntryLoadBits::BOTH,
4009 1,
4010 |_k, _av| Ok(()),
4011 )
4012 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004013 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004014
4015 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004016 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004017 domain: Domain::APP,
4018 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004019 alias: Some(TEST_ALIAS.to_string()),
4020 blob: None,
4021 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004022 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004023 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004024 |_, _| Ok(()),
4025 )
4026 .unwrap();
4027
4028 assert_eq!(
4029 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4030 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004031 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004032 domain: Domain::APP,
4033 nspace: 0,
4034 alias: Some(TEST_ALIAS.to_string()),
4035 blob: None,
4036 },
4037 KeyType::Client,
4038 KeyEntryLoadBits::NONE,
4039 1,
4040 |_k, _av| Ok(()),
4041 )
4042 .unwrap_err()
4043 .root_cause()
4044 .downcast_ref::<KsError>()
4045 );
4046
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004047 Ok(())
4048 }
4049
4050 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004051 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4052 let mut db = new_test_db()?;
4053
4054 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004055 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004056 domain: Domain::APP,
4057 nspace: 1,
4058 alias: Some(TEST_ALIAS.to_string()),
4059 blob: None,
4060 },
4061 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004062 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004063 )
4064 .expect("Trying to insert cert.");
4065
4066 let (_key_guard, mut key_entry) = db
4067 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004068 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004069 domain: Domain::APP,
4070 nspace: 1,
4071 alias: Some(TEST_ALIAS.to_string()),
4072 blob: None,
4073 },
4074 KeyType::Client,
4075 KeyEntryLoadBits::PUBLIC,
4076 1,
4077 |_k, _av| Ok(()),
4078 )
4079 .expect("Trying to read certificate entry.");
4080
4081 assert!(key_entry.pure_cert());
4082 assert!(key_entry.cert().is_none());
4083 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4084
4085 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004086 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004087 domain: Domain::APP,
4088 nspace: 1,
4089 alias: Some(TEST_ALIAS.to_string()),
4090 blob: None,
4091 },
4092 KeyType::Client,
4093 1,
4094 |_, _| Ok(()),
4095 )
4096 .unwrap();
4097
4098 assert_eq!(
4099 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4100 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004101 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004102 domain: Domain::APP,
4103 nspace: 1,
4104 alias: Some(TEST_ALIAS.to_string()),
4105 blob: None,
4106 },
4107 KeyType::Client,
4108 KeyEntryLoadBits::NONE,
4109 1,
4110 |_k, _av| Ok(()),
4111 )
4112 .unwrap_err()
4113 .root_cause()
4114 .downcast_ref::<KsError>()
4115 );
4116
4117 Ok(())
4118 }
4119
4120 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004121 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4122 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004123 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004124 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4125 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004126 let (_key_guard, key_entry) = db
4127 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004128 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004129 domain: Domain::SELINUX,
4130 nspace: 1,
4131 alias: Some(TEST_ALIAS.to_string()),
4132 blob: None,
4133 },
4134 KeyType::Client,
4135 KeyEntryLoadBits::BOTH,
4136 1,
4137 |_k, _av| Ok(()),
4138 )
4139 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004140 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004141
4142 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004143 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004144 domain: Domain::SELINUX,
4145 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004146 alias: Some(TEST_ALIAS.to_string()),
4147 blob: None,
4148 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004149 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004150 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004151 |_, _| Ok(()),
4152 )
4153 .unwrap();
4154
4155 assert_eq!(
4156 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4157 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004158 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004159 domain: Domain::SELINUX,
4160 nspace: 1,
4161 alias: Some(TEST_ALIAS.to_string()),
4162 blob: None,
4163 },
4164 KeyType::Client,
4165 KeyEntryLoadBits::NONE,
4166 1,
4167 |_k, _av| Ok(()),
4168 )
4169 .unwrap_err()
4170 .root_cause()
4171 .downcast_ref::<KsError>()
4172 );
4173
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004174 Ok(())
4175 }
4176
4177 #[test]
4178 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4179 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004180 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004181 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4182 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004183 let (_, key_entry) = db
4184 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004185 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004186 KeyType::Client,
4187 KeyEntryLoadBits::BOTH,
4188 1,
4189 |_k, _av| Ok(()),
4190 )
4191 .unwrap();
4192
Qi Wub9433b52020-12-01 14:52:46 +08004193 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004194
4195 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004196 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004197 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004198 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004199 |_, _| Ok(()),
4200 )
4201 .unwrap();
4202
4203 assert_eq!(
4204 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4205 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004206 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004207 KeyType::Client,
4208 KeyEntryLoadBits::NONE,
4209 1,
4210 |_k, _av| Ok(()),
4211 )
4212 .unwrap_err()
4213 .root_cause()
4214 .downcast_ref::<KsError>()
4215 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004216
4217 Ok(())
4218 }
4219
4220 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004221 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4222 let mut db = new_test_db()?;
4223 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4224 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4225 .0;
4226 // Update the usage count of the limited use key.
4227 db.check_and_update_key_usage_count(key_id)?;
4228
4229 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004230 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004231 KeyType::Client,
4232 KeyEntryLoadBits::BOTH,
4233 1,
4234 |_k, _av| Ok(()),
4235 )?;
4236
4237 // The usage count is decremented now.
4238 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4239
4240 Ok(())
4241 }
4242
4243 #[test]
4244 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4245 let mut db = new_test_db()?;
4246 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4247 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4248 .0;
4249 // Update the usage count of the limited use key.
4250 db.check_and_update_key_usage_count(key_id).expect(concat!(
4251 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4252 "This should succeed."
4253 ));
4254
4255 // Try to update the exhausted limited use key.
4256 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4257 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4258 "This should fail."
4259 ));
4260 assert_eq!(
4261 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4262 e.root_cause().downcast_ref::<KsError>().unwrap()
4263 );
4264
4265 Ok(())
4266 }
4267
4268 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004269 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4270 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004271 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004272 .context("test_insert_and_load_full_keyentry_from_grant")?
4273 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004274
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004275 let granted_key = db
4276 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004277 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004278 domain: Domain::APP,
4279 nspace: 0,
4280 alias: Some(TEST_ALIAS.to_string()),
4281 blob: None,
4282 },
4283 1,
4284 2,
4285 key_perm_set![KeyPerm::use_()],
4286 |_k, _av| Ok(()),
4287 )
4288 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004289
4290 debug_dump_grant_table(&mut db)?;
4291
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004292 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004293 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4294 assert_eq!(Domain::GRANT, k.domain);
4295 assert!(av.unwrap().includes(KeyPerm::use_()));
4296 Ok(())
4297 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004298 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004299
Qi Wub9433b52020-12-01 14:52:46 +08004300 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004301
Janis Danisevskis66784c42021-01-27 08:40:25 -08004302 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004303
4304 assert_eq!(
4305 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4306 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004307 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004308 KeyType::Client,
4309 KeyEntryLoadBits::NONE,
4310 2,
4311 |_k, _av| Ok(()),
4312 )
4313 .unwrap_err()
4314 .root_cause()
4315 .downcast_ref::<KsError>()
4316 );
4317
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004318 Ok(())
4319 }
4320
Janis Danisevskis45760022021-01-19 16:34:10 -08004321 // This test attempts to load a key by key id while the caller is not the owner
4322 // but a grant exists for the given key and the caller.
4323 #[test]
4324 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4325 let mut db = new_test_db()?;
4326 const OWNER_UID: u32 = 1u32;
4327 const GRANTEE_UID: u32 = 2u32;
4328 const SOMEONE_ELSE_UID: u32 = 3u32;
4329 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4330 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4331 .0;
4332
4333 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004334 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004335 domain: Domain::APP,
4336 nspace: 0,
4337 alias: Some(TEST_ALIAS.to_string()),
4338 blob: None,
4339 },
4340 OWNER_UID,
4341 GRANTEE_UID,
4342 key_perm_set![KeyPerm::use_()],
4343 |_k, _av| Ok(()),
4344 )
4345 .unwrap();
4346
4347 debug_dump_grant_table(&mut db)?;
4348
4349 let id_descriptor =
4350 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4351
4352 let (_, key_entry) = db
4353 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004354 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004355 KeyType::Client,
4356 KeyEntryLoadBits::BOTH,
4357 GRANTEE_UID,
4358 |k, av| {
4359 assert_eq!(Domain::APP, k.domain);
4360 assert_eq!(OWNER_UID as i64, k.nspace);
4361 assert!(av.unwrap().includes(KeyPerm::use_()));
4362 Ok(())
4363 },
4364 )
4365 .unwrap();
4366
4367 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4368
4369 let (_, key_entry) = db
4370 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004371 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004372 KeyType::Client,
4373 KeyEntryLoadBits::BOTH,
4374 SOMEONE_ELSE_UID,
4375 |k, av| {
4376 assert_eq!(Domain::APP, k.domain);
4377 assert_eq!(OWNER_UID as i64, k.nspace);
4378 assert!(av.is_none());
4379 Ok(())
4380 },
4381 )
4382 .unwrap();
4383
4384 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4385
Janis Danisevskis66784c42021-01-27 08:40:25 -08004386 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004387
4388 assert_eq!(
4389 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4390 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004391 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004392 KeyType::Client,
4393 KeyEntryLoadBits::NONE,
4394 GRANTEE_UID,
4395 |_k, _av| Ok(()),
4396 )
4397 .unwrap_err()
4398 .root_cause()
4399 .downcast_ref::<KsError>()
4400 );
4401
4402 Ok(())
4403 }
4404
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004405 // Creates a key migrates it to a different location and then tries to access it by the old
4406 // and new location.
4407 #[test]
4408 fn test_migrate_key_app_to_app() -> Result<()> {
4409 let mut db = new_test_db()?;
4410 const SOURCE_UID: u32 = 1u32;
4411 const DESTINATION_UID: u32 = 2u32;
4412 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4413 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4414 let key_id_guard =
4415 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4416 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4417
4418 let source_descriptor: KeyDescriptor = KeyDescriptor {
4419 domain: Domain::APP,
4420 nspace: -1,
4421 alias: Some(SOURCE_ALIAS.to_string()),
4422 blob: None,
4423 };
4424
4425 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4426 domain: Domain::APP,
4427 nspace: -1,
4428 alias: Some(DESTINATION_ALIAS.to_string()),
4429 blob: None,
4430 };
4431
4432 let key_id = key_id_guard.id();
4433
4434 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4435 Ok(())
4436 })
4437 .unwrap();
4438
4439 let (_, key_entry) = db
4440 .load_key_entry(
4441 &destination_descriptor,
4442 KeyType::Client,
4443 KeyEntryLoadBits::BOTH,
4444 DESTINATION_UID,
4445 |k, av| {
4446 assert_eq!(Domain::APP, k.domain);
4447 assert_eq!(DESTINATION_UID as i64, k.nspace);
4448 assert!(av.is_none());
4449 Ok(())
4450 },
4451 )
4452 .unwrap();
4453
4454 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4455
4456 assert_eq!(
4457 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4458 db.load_key_entry(
4459 &source_descriptor,
4460 KeyType::Client,
4461 KeyEntryLoadBits::NONE,
4462 SOURCE_UID,
4463 |_k, _av| Ok(()),
4464 )
4465 .unwrap_err()
4466 .root_cause()
4467 .downcast_ref::<KsError>()
4468 );
4469
4470 Ok(())
4471 }
4472
4473 // Creates a key migrates it to a different location and then tries to access it by the old
4474 // and new location.
4475 #[test]
4476 fn test_migrate_key_app_to_selinux() -> Result<()> {
4477 let mut db = new_test_db()?;
4478 const SOURCE_UID: u32 = 1u32;
4479 const DESTINATION_UID: u32 = 2u32;
4480 const DESTINATION_NAMESPACE: i64 = 1000i64;
4481 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4482 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4483 let key_id_guard =
4484 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4485 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4486
4487 let source_descriptor: KeyDescriptor = KeyDescriptor {
4488 domain: Domain::APP,
4489 nspace: -1,
4490 alias: Some(SOURCE_ALIAS.to_string()),
4491 blob: None,
4492 };
4493
4494 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4495 domain: Domain::SELINUX,
4496 nspace: DESTINATION_NAMESPACE,
4497 alias: Some(DESTINATION_ALIAS.to_string()),
4498 blob: None,
4499 };
4500
4501 let key_id = key_id_guard.id();
4502
4503 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4504 Ok(())
4505 })
4506 .unwrap();
4507
4508 let (_, key_entry) = db
4509 .load_key_entry(
4510 &destination_descriptor,
4511 KeyType::Client,
4512 KeyEntryLoadBits::BOTH,
4513 DESTINATION_UID,
4514 |k, av| {
4515 assert_eq!(Domain::SELINUX, k.domain);
4516 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4517 assert!(av.is_none());
4518 Ok(())
4519 },
4520 )
4521 .unwrap();
4522
4523 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4524
4525 assert_eq!(
4526 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4527 db.load_key_entry(
4528 &source_descriptor,
4529 KeyType::Client,
4530 KeyEntryLoadBits::NONE,
4531 SOURCE_UID,
4532 |_k, _av| Ok(()),
4533 )
4534 .unwrap_err()
4535 .root_cause()
4536 .downcast_ref::<KsError>()
4537 );
4538
4539 Ok(())
4540 }
4541
4542 // Creates two keys and tries to migrate the first to the location of the second which
4543 // is expected to fail.
4544 #[test]
4545 fn test_migrate_key_destination_occupied() -> Result<()> {
4546 let mut db = new_test_db()?;
4547 const SOURCE_UID: u32 = 1u32;
4548 const DESTINATION_UID: u32 = 2u32;
4549 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4550 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4551 let key_id_guard =
4552 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4553 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4554 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4555 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4556
4557 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4558 domain: Domain::APP,
4559 nspace: -1,
4560 alias: Some(DESTINATION_ALIAS.to_string()),
4561 blob: None,
4562 };
4563
4564 assert_eq!(
4565 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4566 db.migrate_key_namespace(
4567 key_id_guard,
4568 &destination_descriptor,
4569 DESTINATION_UID,
4570 |_k| Ok(())
4571 )
4572 .unwrap_err()
4573 .root_cause()
4574 .downcast_ref::<KsError>()
4575 );
4576
4577 Ok(())
4578 }
4579
Janis Danisevskisaec14592020-11-12 09:41:49 -08004580 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4581
Janis Danisevskisaec14592020-11-12 09:41:49 -08004582 #[test]
4583 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4584 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004585 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4586 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004587 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004588 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004589 .context("test_insert_and_load_full_keyentry_domain_app")?
4590 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004591 let (_key_guard, key_entry) = db
4592 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004593 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004594 domain: Domain::APP,
4595 nspace: 0,
4596 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4597 blob: None,
4598 },
4599 KeyType::Client,
4600 KeyEntryLoadBits::BOTH,
4601 33,
4602 |_k, _av| Ok(()),
4603 )
4604 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004605 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004606 let state = Arc::new(AtomicU8::new(1));
4607 let state2 = state.clone();
4608
4609 // Spawning a second thread that attempts to acquire the key id lock
4610 // for the same key as the primary thread. The primary thread then
4611 // waits, thereby forcing the secondary thread into the second stage
4612 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4613 // The test succeeds if the secondary thread observes the transition
4614 // of `state` from 1 to 2, despite having a whole second to overtake
4615 // the primary thread.
4616 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004617 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004618 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004619 assert!(db
4620 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004621 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004622 domain: Domain::APP,
4623 nspace: 0,
4624 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4625 blob: None,
4626 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004627 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004628 KeyEntryLoadBits::BOTH,
4629 33,
4630 |_k, _av| Ok(()),
4631 )
4632 .is_ok());
4633 // We should only see a 2 here because we can only return
4634 // from load_key_entry when the `_key_guard` expires,
4635 // which happens at the end of the scope.
4636 assert_eq!(2, state2.load(Ordering::Relaxed));
4637 });
4638
4639 thread::sleep(std::time::Duration::from_millis(1000));
4640
4641 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4642
4643 // Return the handle from this scope so we can join with the
4644 // secondary thread after the key id lock has expired.
4645 handle
4646 // This is where the `_key_guard` goes out of scope,
4647 // which is the reason for concurrent load_key_entry on the same key
4648 // to unblock.
4649 };
4650 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4651 // main test thread. We will not see failing asserts in secondary threads otherwise.
4652 handle.join().unwrap();
4653 Ok(())
4654 }
4655
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004656 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004657 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004658 let temp_dir =
4659 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4660
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004661 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4662 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004663
4664 let _tx1 = db1
4665 .conn
4666 .transaction_with_behavior(TransactionBehavior::Immediate)
4667 .expect("Failed to create first transaction.");
4668
4669 let error = db2
4670 .conn
4671 .transaction_with_behavior(TransactionBehavior::Immediate)
4672 .context("Transaction begin failed.")
4673 .expect_err("This should fail.");
4674 let root_cause = error.root_cause();
4675 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4676 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4677 {
4678 return;
4679 }
4680 panic!(
4681 "Unexpected error {:?} \n{:?} \n{:?}",
4682 error,
4683 root_cause,
4684 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4685 )
4686 }
4687
4688 #[cfg(disabled)]
4689 #[test]
4690 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4691 let temp_dir = Arc::new(
4692 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4693 .expect("Failed to create temp dir."),
4694 );
4695
4696 let test_begin = Instant::now();
4697
4698 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4699 const KEY_COUNT: u32 = 500u32;
4700 const OPEN_DB_COUNT: u32 = 50u32;
4701
4702 let mut actual_key_count = KEY_COUNT;
4703 // First insert KEY_COUNT keys.
4704 for count in 0..KEY_COUNT {
4705 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4706 actual_key_count = count;
4707 break;
4708 }
4709 let alias = format!("test_alias_{}", count);
4710 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4711 .expect("Failed to make key entry.");
4712 }
4713
4714 // Insert more keys from a different thread and into a different namespace.
4715 let temp_dir1 = temp_dir.clone();
4716 let handle1 = thread::spawn(move || {
4717 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4718
4719 for count in 0..actual_key_count {
4720 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4721 return;
4722 }
4723 let alias = format!("test_alias_{}", count);
4724 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4725 .expect("Failed to make key entry.");
4726 }
4727
4728 // then unbind them again.
4729 for count in 0..actual_key_count {
4730 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4731 return;
4732 }
4733 let key = KeyDescriptor {
4734 domain: Domain::APP,
4735 nspace: -1,
4736 alias: Some(format!("test_alias_{}", count)),
4737 blob: None,
4738 };
4739 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4740 }
4741 });
4742
4743 // And start unbinding the first set of keys.
4744 let temp_dir2 = temp_dir.clone();
4745 let handle2 = thread::spawn(move || {
4746 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4747
4748 for count in 0..actual_key_count {
4749 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4750 return;
4751 }
4752 let key = KeyDescriptor {
4753 domain: Domain::APP,
4754 nspace: -1,
4755 alias: Some(format!("test_alias_{}", count)),
4756 blob: None,
4757 };
4758 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4759 }
4760 });
4761
4762 let stop_deleting = Arc::new(AtomicU8::new(0));
4763 let stop_deleting2 = stop_deleting.clone();
4764
4765 // And delete anything that is unreferenced keys.
4766 let temp_dir3 = temp_dir.clone();
4767 let handle3 = thread::spawn(move || {
4768 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4769
4770 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4771 while let Some((key_guard, _key)) =
4772 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4773 {
4774 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4775 return;
4776 }
4777 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4778 }
4779 std::thread::sleep(std::time::Duration::from_millis(100));
4780 }
4781 });
4782
4783 // While a lot of inserting and deleting is going on we have to open database connections
4784 // successfully and use them.
4785 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4786 // out of scope.
4787 #[allow(clippy::redundant_clone)]
4788 let temp_dir4 = temp_dir.clone();
4789 let handle4 = thread::spawn(move || {
4790 for count in 0..OPEN_DB_COUNT {
4791 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4792 return;
4793 }
4794 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4795
4796 let alias = format!("test_alias_{}", count);
4797 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4798 .expect("Failed to make key entry.");
4799 let key = KeyDescriptor {
4800 domain: Domain::APP,
4801 nspace: -1,
4802 alias: Some(alias),
4803 blob: None,
4804 };
4805 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4806 }
4807 });
4808
4809 handle1.join().expect("Thread 1 panicked.");
4810 handle2.join().expect("Thread 2 panicked.");
4811 handle4.join().expect("Thread 4 panicked.");
4812
4813 stop_deleting.store(1, Ordering::Relaxed);
4814 handle3.join().expect("Thread 3 panicked.");
4815
4816 Ok(())
4817 }
4818
4819 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004820 fn list() -> Result<()> {
4821 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004822 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004823 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4824 (Domain::APP, 1, "test1"),
4825 (Domain::APP, 1, "test2"),
4826 (Domain::APP, 1, "test3"),
4827 (Domain::APP, 1, "test4"),
4828 (Domain::APP, 1, "test5"),
4829 (Domain::APP, 1, "test6"),
4830 (Domain::APP, 1, "test7"),
4831 (Domain::APP, 2, "test1"),
4832 (Domain::APP, 2, "test2"),
4833 (Domain::APP, 2, "test3"),
4834 (Domain::APP, 2, "test4"),
4835 (Domain::APP, 2, "test5"),
4836 (Domain::APP, 2, "test6"),
4837 (Domain::APP, 2, "test8"),
4838 (Domain::SELINUX, 100, "test1"),
4839 (Domain::SELINUX, 100, "test2"),
4840 (Domain::SELINUX, 100, "test3"),
4841 (Domain::SELINUX, 100, "test4"),
4842 (Domain::SELINUX, 100, "test5"),
4843 (Domain::SELINUX, 100, "test6"),
4844 (Domain::SELINUX, 100, "test9"),
4845 ];
4846
4847 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4848 .iter()
4849 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004850 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4851 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004852 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4853 });
4854 (entry.id(), *ns)
4855 })
4856 .collect();
4857
4858 for (domain, namespace) in
4859 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4860 {
4861 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4862 .iter()
4863 .filter_map(|(domain, ns, alias)| match ns {
4864 ns if *ns == *namespace => Some(KeyDescriptor {
4865 domain: *domain,
4866 nspace: *ns,
4867 alias: Some(alias.to_string()),
4868 blob: None,
4869 }),
4870 _ => None,
4871 })
4872 .collect();
4873 list_o_descriptors.sort();
4874 let mut list_result = db.list(*domain, *namespace)?;
4875 list_result.sort();
4876 assert_eq!(list_o_descriptors, list_result);
4877
4878 let mut list_o_ids: Vec<i64> = list_o_descriptors
4879 .into_iter()
4880 .map(|d| {
4881 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004882 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004883 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004884 KeyType::Client,
4885 KeyEntryLoadBits::NONE,
4886 *namespace as u32,
4887 |_, _| Ok(()),
4888 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004889 .unwrap();
4890 entry.id()
4891 })
4892 .collect();
4893 list_o_ids.sort_unstable();
4894 let mut loaded_entries: Vec<i64> = list_o_keys
4895 .iter()
4896 .filter_map(|(id, ns)| match ns {
4897 ns if *ns == *namespace => Some(*id),
4898 _ => None,
4899 })
4900 .collect();
4901 loaded_entries.sort_unstable();
4902 assert_eq!(list_o_ids, loaded_entries);
4903 }
4904 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4905
4906 Ok(())
4907 }
4908
Joel Galenson0891bc12020-07-20 10:37:03 -07004909 // Helpers
4910
4911 // Checks that the given result is an error containing the given string.
4912 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4913 let error_str = format!(
4914 "{:#?}",
4915 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4916 );
4917 assert!(
4918 error_str.contains(target),
4919 "The string \"{}\" should contain \"{}\"",
4920 error_str,
4921 target
4922 );
4923 }
4924
Joel Galenson2aab4432020-07-22 15:27:57 -07004925 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004926 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004927 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004928 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004929 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004930 namespace: Option<i64>,
4931 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004932 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004933 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004934 }
4935
4936 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4937 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004938 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004939 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004940 Ok(KeyEntryRow {
4941 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004942 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004943 domain: match row.get(2)? {
4944 Some(i) => Some(Domain(i)),
4945 None => None,
4946 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004947 namespace: row.get(3)?,
4948 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004949 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004950 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004951 })
4952 })?
4953 .map(|r| r.context("Could not read keyentry row."))
4954 .collect::<Result<Vec<_>>>()
4955 }
4956
Max Biresb2e1d032021-02-08 21:35:05 -08004957 struct RemoteProvValues {
4958 cert_chain: Vec<u8>,
4959 priv_key: Vec<u8>,
4960 batch_cert: Vec<u8>,
4961 }
4962
Max Bires2b2e6562020-09-22 11:22:36 -07004963 fn load_attestation_key_pool(
4964 db: &mut KeystoreDB,
4965 expiration_date: i64,
4966 namespace: i64,
4967 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004968 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004969 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4970 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4971 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4972 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004973 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004974 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4975 db.store_signed_attestation_certificate_chain(
4976 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004977 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004978 &cert_chain,
4979 expiration_date,
4980 &KEYSTORE_UUID,
4981 )?;
4982 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004983 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004984 }
4985
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004986 // Note: The parameters and SecurityLevel associations are nonsensical. This
4987 // collection is only used to check if the parameters are preserved as expected by the
4988 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004989 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4990 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004991 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4992 KeyParameter::new(
4993 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4994 SecurityLevel::TRUSTED_ENVIRONMENT,
4995 ),
4996 KeyParameter::new(
4997 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4998 SecurityLevel::TRUSTED_ENVIRONMENT,
4999 ),
5000 KeyParameter::new(
5001 KeyParameterValue::Algorithm(Algorithm::RSA),
5002 SecurityLevel::TRUSTED_ENVIRONMENT,
5003 ),
5004 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5005 KeyParameter::new(
5006 KeyParameterValue::BlockMode(BlockMode::ECB),
5007 SecurityLevel::TRUSTED_ENVIRONMENT,
5008 ),
5009 KeyParameter::new(
5010 KeyParameterValue::BlockMode(BlockMode::GCM),
5011 SecurityLevel::TRUSTED_ENVIRONMENT,
5012 ),
5013 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5014 KeyParameter::new(
5015 KeyParameterValue::Digest(Digest::MD5),
5016 SecurityLevel::TRUSTED_ENVIRONMENT,
5017 ),
5018 KeyParameter::new(
5019 KeyParameterValue::Digest(Digest::SHA_2_224),
5020 SecurityLevel::TRUSTED_ENVIRONMENT,
5021 ),
5022 KeyParameter::new(
5023 KeyParameterValue::Digest(Digest::SHA_2_256),
5024 SecurityLevel::STRONGBOX,
5025 ),
5026 KeyParameter::new(
5027 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5028 SecurityLevel::TRUSTED_ENVIRONMENT,
5029 ),
5030 KeyParameter::new(
5031 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5032 SecurityLevel::TRUSTED_ENVIRONMENT,
5033 ),
5034 KeyParameter::new(
5035 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5036 SecurityLevel::STRONGBOX,
5037 ),
5038 KeyParameter::new(
5039 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5040 SecurityLevel::TRUSTED_ENVIRONMENT,
5041 ),
5042 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5043 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5044 KeyParameter::new(
5045 KeyParameterValue::EcCurve(EcCurve::P_224),
5046 SecurityLevel::TRUSTED_ENVIRONMENT,
5047 ),
5048 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5049 KeyParameter::new(
5050 KeyParameterValue::EcCurve(EcCurve::P_384),
5051 SecurityLevel::TRUSTED_ENVIRONMENT,
5052 ),
5053 KeyParameter::new(
5054 KeyParameterValue::EcCurve(EcCurve::P_521),
5055 SecurityLevel::TRUSTED_ENVIRONMENT,
5056 ),
5057 KeyParameter::new(
5058 KeyParameterValue::RSAPublicExponent(3),
5059 SecurityLevel::TRUSTED_ENVIRONMENT,
5060 ),
5061 KeyParameter::new(
5062 KeyParameterValue::IncludeUniqueID,
5063 SecurityLevel::TRUSTED_ENVIRONMENT,
5064 ),
5065 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5066 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5067 KeyParameter::new(
5068 KeyParameterValue::ActiveDateTime(1234567890),
5069 SecurityLevel::STRONGBOX,
5070 ),
5071 KeyParameter::new(
5072 KeyParameterValue::OriginationExpireDateTime(1234567890),
5073 SecurityLevel::TRUSTED_ENVIRONMENT,
5074 ),
5075 KeyParameter::new(
5076 KeyParameterValue::UsageExpireDateTime(1234567890),
5077 SecurityLevel::TRUSTED_ENVIRONMENT,
5078 ),
5079 KeyParameter::new(
5080 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5081 SecurityLevel::TRUSTED_ENVIRONMENT,
5082 ),
5083 KeyParameter::new(
5084 KeyParameterValue::MaxUsesPerBoot(1234567890),
5085 SecurityLevel::TRUSTED_ENVIRONMENT,
5086 ),
5087 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5088 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5089 KeyParameter::new(
5090 KeyParameterValue::NoAuthRequired,
5091 SecurityLevel::TRUSTED_ENVIRONMENT,
5092 ),
5093 KeyParameter::new(
5094 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5095 SecurityLevel::TRUSTED_ENVIRONMENT,
5096 ),
5097 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5098 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5099 KeyParameter::new(
5100 KeyParameterValue::TrustedUserPresenceRequired,
5101 SecurityLevel::TRUSTED_ENVIRONMENT,
5102 ),
5103 KeyParameter::new(
5104 KeyParameterValue::TrustedConfirmationRequired,
5105 SecurityLevel::TRUSTED_ENVIRONMENT,
5106 ),
5107 KeyParameter::new(
5108 KeyParameterValue::UnlockedDeviceRequired,
5109 SecurityLevel::TRUSTED_ENVIRONMENT,
5110 ),
5111 KeyParameter::new(
5112 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5113 SecurityLevel::SOFTWARE,
5114 ),
5115 KeyParameter::new(
5116 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5117 SecurityLevel::SOFTWARE,
5118 ),
5119 KeyParameter::new(
5120 KeyParameterValue::CreationDateTime(12345677890),
5121 SecurityLevel::SOFTWARE,
5122 ),
5123 KeyParameter::new(
5124 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5125 SecurityLevel::TRUSTED_ENVIRONMENT,
5126 ),
5127 KeyParameter::new(
5128 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5129 SecurityLevel::TRUSTED_ENVIRONMENT,
5130 ),
5131 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5132 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5133 KeyParameter::new(
5134 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5135 SecurityLevel::SOFTWARE,
5136 ),
5137 KeyParameter::new(
5138 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5139 SecurityLevel::TRUSTED_ENVIRONMENT,
5140 ),
5141 KeyParameter::new(
5142 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5143 SecurityLevel::TRUSTED_ENVIRONMENT,
5144 ),
5145 KeyParameter::new(
5146 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5147 SecurityLevel::TRUSTED_ENVIRONMENT,
5148 ),
5149 KeyParameter::new(
5150 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5151 SecurityLevel::TRUSTED_ENVIRONMENT,
5152 ),
5153 KeyParameter::new(
5154 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5155 SecurityLevel::TRUSTED_ENVIRONMENT,
5156 ),
5157 KeyParameter::new(
5158 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5159 SecurityLevel::TRUSTED_ENVIRONMENT,
5160 ),
5161 KeyParameter::new(
5162 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5163 SecurityLevel::TRUSTED_ENVIRONMENT,
5164 ),
5165 KeyParameter::new(
5166 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5167 SecurityLevel::TRUSTED_ENVIRONMENT,
5168 ),
5169 KeyParameter::new(
5170 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5171 SecurityLevel::TRUSTED_ENVIRONMENT,
5172 ),
5173 KeyParameter::new(
5174 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5175 SecurityLevel::TRUSTED_ENVIRONMENT,
5176 ),
5177 KeyParameter::new(
5178 KeyParameterValue::VendorPatchLevel(3),
5179 SecurityLevel::TRUSTED_ENVIRONMENT,
5180 ),
5181 KeyParameter::new(
5182 KeyParameterValue::BootPatchLevel(4),
5183 SecurityLevel::TRUSTED_ENVIRONMENT,
5184 ),
5185 KeyParameter::new(
5186 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5187 SecurityLevel::TRUSTED_ENVIRONMENT,
5188 ),
5189 KeyParameter::new(
5190 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5191 SecurityLevel::TRUSTED_ENVIRONMENT,
5192 ),
5193 KeyParameter::new(
5194 KeyParameterValue::MacLength(256),
5195 SecurityLevel::TRUSTED_ENVIRONMENT,
5196 ),
5197 KeyParameter::new(
5198 KeyParameterValue::ResetSinceIdRotation,
5199 SecurityLevel::TRUSTED_ENVIRONMENT,
5200 ),
5201 KeyParameter::new(
5202 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5203 SecurityLevel::TRUSTED_ENVIRONMENT,
5204 ),
Qi Wub9433b52020-12-01 14:52:46 +08005205 ];
5206 if let Some(value) = max_usage_count {
5207 params.push(KeyParameter::new(
5208 KeyParameterValue::UsageCountLimit(value),
5209 SecurityLevel::SOFTWARE,
5210 ));
5211 }
5212 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005213 }
5214
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005215 fn make_test_key_entry(
5216 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005217 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005218 namespace: i64,
5219 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005220 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005221 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005222 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005223 let mut blob_metadata = BlobMetaData::new();
5224 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5225 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5226 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5227 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5228 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5229
5230 db.set_blob(
5231 &key_id,
5232 SubComponentType::KEY_BLOB,
5233 Some(TEST_KEY_BLOB),
5234 Some(&blob_metadata),
5235 )?;
5236 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5237 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005238
5239 let params = make_test_params(max_usage_count);
5240 db.insert_keyparameter(&key_id, &params)?;
5241
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005242 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005243 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005244 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005245 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005246 Ok(key_id)
5247 }
5248
Qi Wub9433b52020-12-01 14:52:46 +08005249 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5250 let params = make_test_params(max_usage_count);
5251
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005252 let mut blob_metadata = BlobMetaData::new();
5253 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5254 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5255 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5256 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5257 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5258
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005259 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005260 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005261
5262 KeyEntry {
5263 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005264 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005265 cert: Some(TEST_CERT_BLOB.to_vec()),
5266 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005267 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005268 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005269 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005270 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005271 }
5272 }
5273
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005274 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005275 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005276 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005277 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005278 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005279 NO_PARAMS,
5280 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005281 Ok((
5282 row.get(0)?,
5283 row.get(1)?,
5284 row.get(2)?,
5285 row.get(3)?,
5286 row.get(4)?,
5287 row.get(5)?,
5288 row.get(6)?,
5289 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005290 },
5291 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005292
5293 println!("Key entry table rows:");
5294 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005295 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005296 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005297 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5298 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005299 );
5300 }
5301 Ok(())
5302 }
5303
5304 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005305 let mut stmt = db
5306 .conn
5307 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005308 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5309 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5310 })?;
5311
5312 println!("Grant table rows:");
5313 for r in rows {
5314 let (id, gt, ki, av) = r.unwrap();
5315 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5316 }
5317 Ok(())
5318 }
5319
Joel Galenson0891bc12020-07-20 10:37:03 -07005320 // Use a custom random number generator that repeats each number once.
5321 // This allows us to test repeated elements.
5322
5323 thread_local! {
5324 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5325 }
5326
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005327 fn reset_random() {
5328 RANDOM_COUNTER.with(|counter| {
5329 *counter.borrow_mut() = 0;
5330 })
5331 }
5332
Joel Galenson0891bc12020-07-20 10:37:03 -07005333 pub fn random() -> i64 {
5334 RANDOM_COUNTER.with(|counter| {
5335 let result = *counter.borrow() / 2;
5336 *counter.borrow_mut() += 1;
5337 result
5338 })
5339 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005340
5341 #[test]
5342 fn test_last_off_body() -> Result<()> {
5343 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005344 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005345 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5346 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5347 tx.commit()?;
5348 let one_second = Duration::from_secs(1);
5349 thread::sleep(one_second);
5350 db.update_last_off_body(MonotonicRawTime::now())?;
5351 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5352 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5353 tx2.commit()?;
5354 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5355 Ok(())
5356 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005357
5358 #[test]
5359 fn test_unbind_keys_for_user() -> Result<()> {
5360 let mut db = new_test_db()?;
5361 db.unbind_keys_for_user(1, false)?;
5362
5363 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5364 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5365 db.unbind_keys_for_user(2, false)?;
5366
5367 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5368 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5369
5370 db.unbind_keys_for_user(1, true)?;
5371 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5372
5373 Ok(())
5374 }
5375
5376 #[test]
5377 fn test_store_super_key() -> Result<()> {
5378 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005379 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005380 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005381 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005382 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005383 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005384
5385 let (encrypted_super_key, metadata) =
5386 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005387 db.store_super_key(
5388 1,
5389 &USER_SUPER_KEY,
5390 &encrypted_super_key,
5391 &metadata,
5392 &KeyMetaData::new(),
5393 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005394
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005395 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005396 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005397
Paul Crowley7a658392021-03-18 17:08:20 -07005398 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005399 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5400 USER_SUPER_KEY.algorithm,
5401 key_entry,
5402 &pw,
5403 None,
5404 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005405
Paul Crowley7a658392021-03-18 17:08:20 -07005406 let decrypted_secret_bytes =
5407 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5408 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005409 Ok(())
5410 }
Seth Moore78c091f2021-04-09 21:38:30 +00005411
5412 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5413 vec![
5414 StatsdStorageType::KeyEntry,
5415 StatsdStorageType::KeyEntryIdIndex,
5416 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5417 StatsdStorageType::BlobEntry,
5418 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5419 StatsdStorageType::KeyParameter,
5420 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5421 StatsdStorageType::KeyMetadata,
5422 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5423 StatsdStorageType::Grant,
5424 StatsdStorageType::AuthToken,
5425 StatsdStorageType::BlobMetadata,
5426 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5427 ]
5428 }
5429
5430 /// Perform a simple check to ensure that we can query all the storage types
5431 /// that are supported by the DB. Check for reasonable values.
5432 #[test]
5433 fn test_query_all_valid_table_sizes() -> Result<()> {
5434 const PAGE_SIZE: i64 = 4096;
5435
5436 let mut db = new_test_db()?;
5437
5438 for t in get_valid_statsd_storage_types() {
5439 let stat = db.get_storage_stat(t)?;
5440 assert!(stat.size >= PAGE_SIZE);
5441 assert!(stat.size >= stat.unused_size);
5442 }
5443
5444 Ok(())
5445 }
5446
5447 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5448 get_valid_statsd_storage_types()
5449 .into_iter()
5450 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5451 .collect()
5452 }
5453
5454 fn assert_storage_increased(
5455 db: &mut KeystoreDB,
5456 increased_storage_types: Vec<StatsdStorageType>,
5457 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5458 ) {
5459 for storage in increased_storage_types {
5460 // Verify the expected storage increased.
5461 let new = db.get_storage_stat(storage).unwrap();
5462 let storage = storage as i32;
5463 let old = &baseline[&storage];
5464 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5465 assert!(
5466 new.unused_size <= old.unused_size,
5467 "{}: {} <= {}",
5468 storage,
5469 new.unused_size,
5470 old.unused_size
5471 );
5472
5473 // Update the baseline with the new value so that it succeeds in the
5474 // later comparison.
5475 baseline.insert(storage, new);
5476 }
5477
5478 // Get an updated map of the storage and verify there were no unexpected changes.
5479 let updated_stats = get_storage_stats_map(db);
5480 assert_eq!(updated_stats.len(), baseline.len());
5481
5482 for &k in baseline.keys() {
5483 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5484 let mut s = String::new();
5485 for &k in map.keys() {
5486 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5487 .expect("string concat failed");
5488 }
5489 s
5490 };
5491
5492 assert!(
5493 updated_stats[&k].size == baseline[&k].size
5494 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5495 "updated_stats:\n{}\nbaseline:\n{}",
5496 stringify(&updated_stats),
5497 stringify(&baseline)
5498 );
5499 }
5500 }
5501
5502 #[test]
5503 fn test_verify_key_table_size_reporting() -> Result<()> {
5504 let mut db = new_test_db()?;
5505 let mut working_stats = get_storage_stats_map(&mut db);
5506
5507 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5508 assert_storage_increased(
5509 &mut db,
5510 vec![
5511 StatsdStorageType::KeyEntry,
5512 StatsdStorageType::KeyEntryIdIndex,
5513 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5514 ],
5515 &mut working_stats,
5516 );
5517
5518 let mut blob_metadata = BlobMetaData::new();
5519 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5520 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5521 assert_storage_increased(
5522 &mut db,
5523 vec![
5524 StatsdStorageType::BlobEntry,
5525 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5526 StatsdStorageType::BlobMetadata,
5527 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5528 ],
5529 &mut working_stats,
5530 );
5531
5532 let params = make_test_params(None);
5533 db.insert_keyparameter(&key_id, &params)?;
5534 assert_storage_increased(
5535 &mut db,
5536 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5537 &mut working_stats,
5538 );
5539
5540 let mut metadata = KeyMetaData::new();
5541 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5542 db.insert_key_metadata(&key_id, &metadata)?;
5543 assert_storage_increased(
5544 &mut db,
5545 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5546 &mut working_stats,
5547 );
5548
5549 let mut sum = 0;
5550 for stat in working_stats.values() {
5551 sum += stat.size;
5552 }
5553 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5554 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5555
5556 Ok(())
5557 }
5558
5559 #[test]
5560 fn test_verify_auth_table_size_reporting() -> Result<()> {
5561 let mut db = new_test_db()?;
5562 let mut working_stats = get_storage_stats_map(&mut db);
5563 db.insert_auth_token(&HardwareAuthToken {
5564 challenge: 123,
5565 userId: 456,
5566 authenticatorId: 789,
5567 authenticatorType: kmhw_authenticator_type::ANY,
5568 timestamp: Timestamp { milliSeconds: 10 },
5569 mac: b"mac".to_vec(),
5570 })?;
5571 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5572 Ok(())
5573 }
5574
5575 #[test]
5576 fn test_verify_grant_table_size_reporting() -> Result<()> {
5577 const OWNER: i64 = 1;
5578 let mut db = new_test_db()?;
5579 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5580
5581 let mut working_stats = get_storage_stats_map(&mut db);
5582 db.grant(
5583 &KeyDescriptor {
5584 domain: Domain::APP,
5585 nspace: 0,
5586 alias: Some(TEST_ALIAS.to_string()),
5587 blob: None,
5588 },
5589 OWNER as u32,
5590 123,
5591 key_perm_set![KeyPerm::use_()],
5592 |_, _| Ok(()),
5593 )?;
5594
5595 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5596
5597 Ok(())
5598 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005599}