blob: 1e54ec186b7709b64ab3f3a8710c810836a953f8 [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Janis Danisevskisb42fc182020-12-15 08:41:27 -080044use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080045use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070046use crate::permission::KeyPermSet;
Janis Danisevskis850d4862021-05-05 08:41:14 -070047use crate::utils::{get_current_time_in_seconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080048use crate::{
49 db_utils::{self, SqlField},
50 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070051 super_key::USER_SUPER_KEY,
52};
53use crate::{
54 error::{Error as KsError, ErrorCode, ResponseCode},
55 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080056};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080057use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080058use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070059
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000060use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080061 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000062 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080063};
64use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000065 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000066};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070067use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070068 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070069};
Max Bires2b2e6562020-09-22 11:22:36 -070070use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
71 AttestationPoolStatus::AttestationPoolStatus,
72};
Seth Moore78c091f2021-04-09 21:38:30 +000073use statslog_rust::keystore2_storage_stats::{
74 Keystore2StorageStats, StorageType as StatsdStorageType,
75};
Max Bires2b2e6562020-09-22 11:22:36 -070076
77use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080078use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000079use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070080#[cfg(not(test))]
81use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070082use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080083 params,
84 types::FromSql,
85 types::FromSqlResult,
86 types::ToSqlOutput,
87 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080088 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070089};
Max Bires2b2e6562020-09-22 11:22:36 -070090
Janis Danisevskisaec14592020-11-12 09:41:49 -080091use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080093 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070094 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080095 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080096};
Max Bires2b2e6562020-09-22 11:22:36 -070097
Joel Galenson0891bc12020-07-20 10:37:03 -070098#[cfg(test)]
99use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -0700100
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800101impl_metadata!(
102 /// A set of metadata for key entries.
103 #[derive(Debug, Default, Eq, PartialEq)]
104 pub struct KeyMetaData;
105 /// A metadata entry for key entries.
106 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
107 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800108 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800109 CreationDate(DateTime) with accessor creation_date,
110 /// Expiration date for attestation keys.
111 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700112 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
113 /// provisioning
114 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
115 /// Vector representing the raw public key so results from the server can be matched
116 /// to the right entry
117 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700118 /// SEC1 public key for ECDH encryption
119 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800120 // --- ADD NEW META DATA FIELDS HERE ---
121 // For backwards compatibility add new entries only to
122 // end of this list and above this comment.
123 };
124);
125
126impl KeyMetaData {
127 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
128 let mut stmt = tx
129 .prepare(
130 "SELECT tag, data from persistent.keymetadata
131 WHERE keyentryid = ?;",
132 )
133 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
134
135 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
136
137 let mut rows =
138 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
139 db_utils::with_rows_extract_all(&mut rows, |row| {
140 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
141 metadata.insert(
142 db_tag,
143 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
144 .context("Failed to read KeyMetaEntry.")?,
145 );
146 Ok(())
147 })
148 .context("In KeyMetaData::load_from_db.")?;
149
150 Ok(Self { data: metadata })
151 }
152
153 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
154 let mut stmt = tx
155 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000156 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800157 VALUES (?, ?, ?);",
158 )
159 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
160
161 let iter = self.data.iter();
162 for (tag, entry) in iter {
163 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
164 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
165 })?;
166 }
167 Ok(())
168 }
169}
170
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800171impl_metadata!(
172 /// A set of metadata for key blobs.
173 #[derive(Debug, Default, Eq, PartialEq)]
174 pub struct BlobMetaData;
175 /// A metadata entry for key blobs.
176 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
177 pub enum BlobMetaEntry {
178 /// If present, indicates that the blob is encrypted with another key or a key derived
179 /// from a password.
180 EncryptedBy(EncryptedBy) with accessor encrypted_by,
181 /// If the blob is password encrypted this field is set to the
182 /// salt used for the key derivation.
183 Salt(Vec<u8>) with accessor salt,
184 /// If the blob is encrypted, this field is set to the initialization vector.
185 Iv(Vec<u8>) with accessor iv,
186 /// If the blob is encrypted, this field holds the AEAD TAG.
187 AeadTag(Vec<u8>) with accessor aead_tag,
188 /// The uuid of the owning KeyMint instance.
189 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700190 /// If the key is ECDH encrypted, this is the ephemeral public key
191 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000192 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
193 /// of that key
194 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800195 // --- ADD NEW META DATA FIELDS HERE ---
196 // For backwards compatibility add new entries only to
197 // end of this list and above this comment.
198 };
199);
200
201impl BlobMetaData {
202 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
203 let mut stmt = tx
204 .prepare(
205 "SELECT tag, data from persistent.blobmetadata
206 WHERE blobentryid = ?;",
207 )
208 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
209
210 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
211
212 let mut rows =
213 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
214 db_utils::with_rows_extract_all(&mut rows, |row| {
215 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
216 metadata.insert(
217 db_tag,
218 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
219 .context("Failed to read BlobMetaEntry.")?,
220 );
221 Ok(())
222 })
223 .context("In BlobMetaData::load_from_db.")?;
224
225 Ok(Self { data: metadata })
226 }
227
228 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
229 let mut stmt = tx
230 .prepare(
231 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
232 VALUES (?, ?, ?);",
233 )
234 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
235
236 let iter = self.data.iter();
237 for (tag, entry) in iter {
238 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
239 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
240 })?;
241 }
242 Ok(())
243 }
244}
245
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800246/// Indicates the type of the keyentry.
247#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
248pub enum KeyType {
249 /// This is a client key type. These keys are created or imported through the Keystore 2.0
250 /// AIDL interface android.system.keystore2.
251 Client,
252 /// This is a super key type. These keys are created by keystore itself and used to encrypt
253 /// other key blobs to provide LSKF binding.
254 Super,
255 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
256 Attestation,
257}
258
259impl ToSql for KeyType {
260 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
261 Ok(ToSqlOutput::Owned(Value::Integer(match self {
262 KeyType::Client => 0,
263 KeyType::Super => 1,
264 KeyType::Attestation => 2,
265 })))
266 }
267}
268
269impl FromSql for KeyType {
270 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
271 match i64::column_result(value)? {
272 0 => Ok(KeyType::Client),
273 1 => Ok(KeyType::Super),
274 2 => Ok(KeyType::Attestation),
275 v => Err(FromSqlError::OutOfRange(v)),
276 }
277 }
278}
279
Max Bires8e93d2b2021-01-14 13:17:59 -0800280/// Uuid representation that can be stored in the database.
281/// Right now it can only be initialized from SecurityLevel.
282/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
284pub struct Uuid([u8; 16]);
285
286impl Deref for Uuid {
287 type Target = [u8; 16];
288
289 fn deref(&self) -> &Self::Target {
290 &self.0
291 }
292}
293
294impl From<SecurityLevel> for Uuid {
295 fn from(sec_level: SecurityLevel) -> Self {
296 Self((sec_level.0 as u128).to_be_bytes())
297 }
298}
299
300impl ToSql for Uuid {
301 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
302 self.0.to_sql()
303 }
304}
305
306impl FromSql for Uuid {
307 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
308 let blob = Vec::<u8>::column_result(value)?;
309 if blob.len() != 16 {
310 return Err(FromSqlError::OutOfRange(blob.len() as i64));
311 }
312 let mut arr = [0u8; 16];
313 arr.copy_from_slice(&blob);
314 Ok(Self(arr))
315 }
316}
317
318/// Key entries that are not associated with any KeyMint instance, such as pure certificate
319/// entries are associated with this UUID.
320pub static KEYSTORE_UUID: Uuid = Uuid([
321 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
322]);
323
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800324/// Indicates how the sensitive part of this key blob is encrypted.
325#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
326pub enum EncryptedBy {
327 /// The keyblob is encrypted by a user password.
328 /// In the database this variant is represented as NULL.
329 Password,
330 /// The keyblob is encrypted by another key with wrapped key id.
331 /// In the database this variant is represented as non NULL value
332 /// that is convertible to i64, typically NUMERIC.
333 KeyId(i64),
334}
335
336impl ToSql for EncryptedBy {
337 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
338 match self {
339 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
340 Self::KeyId(id) => id.to_sql(),
341 }
342 }
343}
344
345impl FromSql for EncryptedBy {
346 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
347 match value {
348 ValueRef::Null => Ok(Self::Password),
349 _ => Ok(Self::KeyId(i64::column_result(value)?)),
350 }
351 }
352}
353
354/// A database representation of wall clock time. DateTime stores unix epoch time as
355/// i64 in milliseconds.
356#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
357pub struct DateTime(i64);
358
359/// Error type returned when creating DateTime or converting it from and to
360/// SystemTime.
361#[derive(thiserror::Error, Debug)]
362pub enum DateTimeError {
363 /// This is returned when SystemTime and Duration computations fail.
364 #[error(transparent)]
365 SystemTimeError(#[from] SystemTimeError),
366
367 /// This is returned when type conversions fail.
368 #[error(transparent)]
369 TypeConversion(#[from] std::num::TryFromIntError),
370
371 /// This is returned when checked time arithmetic failed.
372 #[error("Time arithmetic failed.")]
373 TimeArithmetic,
374}
375
376impl DateTime {
377 /// Constructs a new DateTime object denoting the current time. This may fail during
378 /// conversion to unix epoch time and during conversion to the internal i64 representation.
379 pub fn now() -> Result<Self, DateTimeError> {
380 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
381 }
382
383 /// Constructs a new DateTime object from milliseconds.
384 pub fn from_millis_epoch(millis: i64) -> Self {
385 Self(millis)
386 }
387
388 /// Returns unix epoch time in milliseconds.
389 pub fn to_millis_epoch(&self) -> i64 {
390 self.0
391 }
392
393 /// Returns unix epoch time in seconds.
394 pub fn to_secs_epoch(&self) -> i64 {
395 self.0 / 1000
396 }
397}
398
399impl ToSql for DateTime {
400 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
401 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
402 }
403}
404
405impl FromSql for DateTime {
406 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
407 Ok(Self(i64::column_result(value)?))
408 }
409}
410
411impl TryInto<SystemTime> for DateTime {
412 type Error = DateTimeError;
413
414 fn try_into(self) -> Result<SystemTime, Self::Error> {
415 // We want to construct a SystemTime representation equivalent to self, denoting
416 // a point in time THEN, but we cannot set the time directly. We can only construct
417 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
418 // and between EPOCH and THEN. With this common reference we can construct the
419 // duration between NOW and THEN which we can add to our SystemTime representation
420 // of NOW to get a SystemTime representation of THEN.
421 // Durations can only be positive, thus the if statement below.
422 let now = SystemTime::now();
423 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
424 let then_epoch = Duration::from_millis(self.0.try_into()?);
425 Ok(if now_epoch > then_epoch {
426 // then = now - (now_epoch - then_epoch)
427 now_epoch
428 .checked_sub(then_epoch)
429 .and_then(|d| now.checked_sub(d))
430 .ok_or(DateTimeError::TimeArithmetic)?
431 } else {
432 // then = now + (then_epoch - now_epoch)
433 then_epoch
434 .checked_sub(now_epoch)
435 .and_then(|d| now.checked_add(d))
436 .ok_or(DateTimeError::TimeArithmetic)?
437 })
438 }
439}
440
441impl TryFrom<SystemTime> for DateTime {
442 type Error = DateTimeError;
443
444 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
445 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
446 }
447}
448
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800449#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
450enum KeyLifeCycle {
451 /// Existing keys have a key ID but are not fully populated yet.
452 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
453 /// them to Unreferenced for garbage collection.
454 Existing,
455 /// A live key is fully populated and usable by clients.
456 Live,
457 /// An unreferenced key is scheduled for garbage collection.
458 Unreferenced,
459}
460
461impl ToSql for KeyLifeCycle {
462 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
463 match self {
464 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
465 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
466 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
467 }
468 }
469}
470
471impl FromSql for KeyLifeCycle {
472 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
473 match i64::column_result(value)? {
474 0 => Ok(KeyLifeCycle::Existing),
475 1 => Ok(KeyLifeCycle::Live),
476 2 => Ok(KeyLifeCycle::Unreferenced),
477 v => Err(FromSqlError::OutOfRange(v)),
478 }
479 }
480}
481
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700482/// Keys have a KeyMint blob component and optional public certificate and
483/// certificate chain components.
484/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
485/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800486#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700487pub struct KeyEntryLoadBits(u32);
488
489impl KeyEntryLoadBits {
490 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
491 pub const NONE: KeyEntryLoadBits = Self(0);
492 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
493 pub const KM: KeyEntryLoadBits = Self(1);
494 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
495 pub const PUBLIC: KeyEntryLoadBits = Self(2);
496 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
497 pub const BOTH: KeyEntryLoadBits = Self(3);
498
499 /// Returns true if this object indicates that the public components shall be loaded.
500 pub const fn load_public(&self) -> bool {
501 self.0 & Self::PUBLIC.0 != 0
502 }
503
504 /// Returns true if the object indicates that the KeyMint component shall be loaded.
505 pub const fn load_km(&self) -> bool {
506 self.0 & Self::KM.0 != 0
507 }
508}
509
Janis Danisevskisaec14592020-11-12 09:41:49 -0800510lazy_static! {
511 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
512}
513
514struct KeyIdLockDb {
515 locked_keys: Mutex<HashSet<i64>>,
516 cond_var: Condvar,
517}
518
519/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
520/// from the database a second time. Most functions manipulating the key blob database
521/// require a KeyIdGuard.
522#[derive(Debug)]
523pub struct KeyIdGuard(i64);
524
525impl KeyIdLockDb {
526 fn new() -> Self {
527 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
528 }
529
530 /// This function blocks until an exclusive lock for the given key entry id can
531 /// be acquired. It returns a guard object, that represents the lifecycle of the
532 /// acquired lock.
533 pub fn get(&self, key_id: i64) -> KeyIdGuard {
534 let mut locked_keys = self.locked_keys.lock().unwrap();
535 while locked_keys.contains(&key_id) {
536 locked_keys = self.cond_var.wait(locked_keys).unwrap();
537 }
538 locked_keys.insert(key_id);
539 KeyIdGuard(key_id)
540 }
541
542 /// This function attempts to acquire an exclusive lock on a given key id. If the
543 /// given key id is already taken the function returns None immediately. If a lock
544 /// can be acquired this function returns a guard object, that represents the
545 /// lifecycle of the acquired lock.
546 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
547 let mut locked_keys = self.locked_keys.lock().unwrap();
548 if locked_keys.insert(key_id) {
549 Some(KeyIdGuard(key_id))
550 } else {
551 None
552 }
553 }
554}
555
556impl KeyIdGuard {
557 /// Get the numeric key id of the locked key.
558 pub fn id(&self) -> i64 {
559 self.0
560 }
561}
562
563impl Drop for KeyIdGuard {
564 fn drop(&mut self) {
565 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
566 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800567 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800568 KEY_ID_LOCK.cond_var.notify_all();
569 }
570}
571
Max Bires8e93d2b2021-01-14 13:17:59 -0800572/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700573#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800574pub struct CertificateInfo {
575 cert: Option<Vec<u8>>,
576 cert_chain: Option<Vec<u8>>,
577}
578
579impl CertificateInfo {
580 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
581 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
582 Self { cert, cert_chain }
583 }
584
585 /// Take the cert
586 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
587 self.cert.take()
588 }
589
590 /// Take the cert chain
591 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
592 self.cert_chain.take()
593 }
594}
595
Max Bires2b2e6562020-09-22 11:22:36 -0700596/// This type represents a certificate chain with a private key corresponding to the leaf
597/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
Max Bires2b2e6562020-09-22 11:22:36 -0700598pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800599 /// A KM key blob
600 pub private_key: ZVec,
601 /// A batch cert for private_key
602 pub batch_cert: Vec<u8>,
603 /// A full certificate chain from root signing authority to private_key, including batch_cert
604 /// for convenience.
605 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700606}
607
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700608/// This type represents a Keystore 2.0 key entry.
609/// An entry has a unique `id` by which it can be found in the database.
610/// It has a security level field, key parameters, and three optional fields
611/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800612#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700613pub struct KeyEntry {
614 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800615 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700616 cert: Option<Vec<u8>>,
617 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800618 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700619 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800620 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800621 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700622}
623
624impl KeyEntry {
625 /// Returns the unique id of the Key entry.
626 pub fn id(&self) -> i64 {
627 self.id
628 }
629 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800630 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
631 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700632 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800633 /// Extracts the Optional KeyMint blob including its metadata.
634 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
635 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700636 }
637 /// Exposes the optional public certificate.
638 pub fn cert(&self) -> &Option<Vec<u8>> {
639 &self.cert
640 }
641 /// Extracts the optional public certificate.
642 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
643 self.cert.take()
644 }
645 /// Exposes the optional public certificate chain.
646 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
647 &self.cert_chain
648 }
649 /// Extracts the optional public certificate_chain.
650 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
651 self.cert_chain.take()
652 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800653 /// Returns the uuid of the owning KeyMint instance.
654 pub fn km_uuid(&self) -> &Uuid {
655 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700656 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700657 /// Exposes the key parameters of this key entry.
658 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
659 &self.parameters
660 }
661 /// Consumes this key entry and extracts the keyparameters from it.
662 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
663 self.parameters
664 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800665 /// Exposes the key metadata of this key entry.
666 pub fn metadata(&self) -> &KeyMetaData {
667 &self.metadata
668 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800669 /// This returns true if the entry is a pure certificate entry with no
670 /// private key component.
671 pub fn pure_cert(&self) -> bool {
672 self.pure_cert
673 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000674 /// Consumes this key entry and extracts the keyparameters and metadata from it.
675 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
676 (self.parameters, self.metadata)
677 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700678}
679
680/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800681#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700682pub struct SubComponentType(u32);
683impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800684 /// Persistent identifier for a key blob.
685 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700686 /// Persistent identifier for a certificate blob.
687 pub const CERT: SubComponentType = Self(1);
688 /// Persistent identifier for a certificate chain blob.
689 pub const CERT_CHAIN: SubComponentType = Self(2);
690}
691
692impl ToSql for SubComponentType {
693 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
694 self.0.to_sql()
695 }
696}
697
698impl FromSql for SubComponentType {
699 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
700 Ok(Self(u32::column_result(value)?))
701 }
702}
703
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800704/// This trait is private to the database module. It is used to convey whether or not the garbage
705/// collector shall be invoked after a database access. All closures passed to
706/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
707/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
708/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
709/// `.need_gc()`.
710trait DoGc<T> {
711 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
712
713 fn no_gc(self) -> Result<(bool, T)>;
714
715 fn need_gc(self) -> Result<(bool, T)>;
716}
717
718impl<T> DoGc<T> for Result<T> {
719 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
720 self.map(|r| (need_gc, r))
721 }
722
723 fn no_gc(self) -> Result<(bool, T)> {
724 self.do_gc(false)
725 }
726
727 fn need_gc(self) -> Result<(bool, T)> {
728 self.do_gc(true)
729 }
730}
731
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700732/// KeystoreDB wraps a connection to an SQLite database and tracks its
733/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700734pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700735 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700736 gc: Option<Arc<Gc>>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700737}
738
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000739/// Database representation of the monotonic time retrieved from the system call clock_gettime with
740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
741#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
742pub struct MonotonicRawTime(i64);
743
744impl MonotonicRawTime {
745 /// Constructs a new MonotonicRawTime
746 pub fn now() -> Self {
747 Self(get_current_time_in_seconds())
748 }
749
David Drysdale0e45a612021-02-25 17:24:36 +0000750 /// Constructs a new MonotonicRawTime from a given number of seconds.
751 pub fn from_secs(val: i64) -> Self {
752 Self(val)
753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
757 self.0
758 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800759
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000760 /// Returns the value of MonotonicRawTime in milli seconds as i64
761 pub fn milli_seconds(&self) -> i64 {
762 self.0 * 1000
763 }
764
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800765 /// Like i64::checked_sub.
766 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
767 self.0.checked_sub(other.0).map(Self)
768 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000769}
770
771impl ToSql for MonotonicRawTime {
772 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
773 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
774 }
775}
776
777impl FromSql for MonotonicRawTime {
778 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
779 Ok(Self(i64::column_result(value)?))
780 }
781}
782
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000783/// This struct encapsulates the information to be stored in the database about the auth tokens
784/// received by keystore.
785pub struct AuthTokenEntry {
786 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000787 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000788}
789
790impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000791 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000792 AuthTokenEntry { auth_token, time_received }
793 }
794
795 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800796 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
799 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 })
801 }
802
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000803 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800804 pub fn auth_token(&self) -> &HardwareAuthToken {
805 &self.auth_token
806 }
807
808 /// Returns the auth token wrapped by the AuthTokenEntry
809 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000810 self.auth_token
811 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800812
813 /// Returns the time that this auth token was received.
814 pub fn time_received(&self) -> MonotonicRawTime {
815 self.time_received
816 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000817
818 /// Returns the challenge value of the auth token.
819 pub fn challenge(&self) -> i64 {
820 self.auth_token.challenge
821 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822}
823
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800824/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
825/// This object does not allow access to the database connection. But it keeps a database
826/// connection alive in order to keep the in memory per boot database alive.
827pub struct PerBootDbKeepAlive(Connection);
828
Joel Galenson26f4d012020-07-17 14:57:21 -0700829impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800830 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800831 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
832
Seth Moore78c091f2021-04-09 21:38:30 +0000833 /// Name of the file that holds the cross-boot persistent database.
834 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
835
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800836 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
837 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
838 let conn = Connection::open_in_memory()
839 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
840
841 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
842 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
843 Ok(PerBootDbKeepAlive(conn))
844 }
845
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700846 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800847 /// files persistent.sqlite and perboot.sqlite in the given directory.
848 /// It also attempts to initialize all of the tables.
849 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700850 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700851 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700852 let _wp = wd::watch_millis("KeystoreDB::new", 500);
853
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800855 let mut persistent_path = db_root.to_path_buf();
Seth Moore78c091f2021-04-09 21:38:30 +0000856 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700857
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800858 // Now convert them to strings prefixed with "file:"
859 let mut persistent_path_str = "file:".to_owned();
860 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800861
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800862 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800863
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
865 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
866
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800867 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800868 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800869 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 })?;
871 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700872 }
873
Janis Danisevskis66784c42021-01-27 08:40:25 -0800874 fn init_tables(tx: &Transaction) -> Result<()> {
875 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700876 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700877 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800878 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700879 domain INTEGER,
880 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800881 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800882 state INTEGER,
883 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700884 NO_PARAMS,
885 )
886 .context("Failed to initialize \"keyentry\" table.")?;
887
Janis Danisevskis66784c42021-01-27 08:40:25 -0800888 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800889 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
890 ON keyentry(id);",
891 NO_PARAMS,
892 )
893 .context("Failed to create index keyentry_id_index.")?;
894
895 tx.execute(
896 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
897 ON keyentry(domain, namespace, alias);",
898 NO_PARAMS,
899 )
900 .context("Failed to create index keyentry_domain_namespace_index.")?;
901
902 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700903 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
904 id INTEGER PRIMARY KEY,
905 subcomponent_type INTEGER,
906 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800907 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700908 NO_PARAMS,
909 )
910 .context("Failed to initialize \"blobentry\" table.")?;
911
Janis Danisevskis66784c42021-01-27 08:40:25 -0800912 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800913 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
914 ON blobentry(keyentryid);",
915 NO_PARAMS,
916 )
917 .context("Failed to create index blobentry_keyentryid_index.")?;
918
919 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800920 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
921 id INTEGER PRIMARY KEY,
922 blobentryid INTEGER,
923 tag INTEGER,
924 data ANY,
925 UNIQUE (blobentryid, tag));",
926 NO_PARAMS,
927 )
928 .context("Failed to initialize \"blobmetadata\" table.")?;
929
930 tx.execute(
931 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
932 ON blobmetadata(blobentryid);",
933 NO_PARAMS,
934 )
935 .context("Failed to create index blobmetadata_blobentryid_index.")?;
936
937 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700938 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000939 keyentryid INTEGER,
940 tag INTEGER,
941 data ANY,
942 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700943 NO_PARAMS,
944 )
945 .context("Failed to initialize \"keyparameter\" table.")?;
946
Janis Danisevskis66784c42021-01-27 08:40:25 -0800947 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800948 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
949 ON keyparameter(keyentryid);",
950 NO_PARAMS,
951 )
952 .context("Failed to create index keyparameter_keyentryid_index.")?;
953
954 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800955 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
956 keyentryid INTEGER,
957 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000958 data ANY,
959 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800960 NO_PARAMS,
961 )
962 .context("Failed to initialize \"keymetadata\" table.")?;
963
Janis Danisevskis66784c42021-01-27 08:40:25 -0800964 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800965 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
966 ON keymetadata(keyentryid);",
967 NO_PARAMS,
968 )
969 .context("Failed to create index keymetadata_keyentryid_index.")?;
970
971 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800972 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700973 id INTEGER UNIQUE,
974 grantee INTEGER,
975 keyentryid INTEGER,
976 access_vector INTEGER);",
977 NO_PARAMS,
978 )
979 .context("Failed to initialize \"grant\" table.")?;
980
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000981 //TODO: only drop the following two perboot tables if this is the first start up
982 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800983 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000984 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800985 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000986 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
987 id INTEGER PRIMARY KEY,
988 challenge INTEGER,
989 user_id INTEGER,
990 auth_id INTEGER,
991 authenticator_type INTEGER,
992 timestamp INTEGER,
993 mac BLOB,
994 time_received INTEGER,
995 UNIQUE(user_id, auth_id, authenticator_type));",
996 NO_PARAMS,
997 )
998 .context("Failed to initialize \"authtoken\" table.")?;
999
Janis Danisevskis66784c42021-01-27 08:40:25 -08001000 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001001 // .context("Failed to drop perboot.metadata table")?;
1002 // metadata table stores certain miscellaneous information required for keystore functioning
1003 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001004 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001005 "CREATE TABLE IF NOT EXISTS perboot.metadata (
1006 key TEXT,
1007 value BLOB,
1008 UNIQUE(key));",
1009 NO_PARAMS,
1010 )
1011 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -07001012 Ok(())
1013 }
1014
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001015 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
1016 let conn =
1017 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1018
Janis Danisevskis66784c42021-01-27 08:40:25 -08001019 loop {
1020 if let Err(e) = conn
1021 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1022 .context("Failed to attach database persistent.")
1023 {
1024 if Self::is_locked_error(&e) {
1025 std::thread::sleep(std::time::Duration::from_micros(500));
1026 continue;
1027 } else {
1028 return Err(e);
1029 }
1030 }
1031 break;
1032 }
1033 loop {
1034 if let Err(e) = conn
1035 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1036 .context("Failed to attach database perboot.")
1037 {
1038 if Self::is_locked_error(&e) {
1039 std::thread::sleep(std::time::Duration::from_micros(500));
1040 continue;
1041 } else {
1042 return Err(e);
1043 }
1044 }
1045 break;
1046 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047
1048 Ok(conn)
1049 }
1050
Seth Moore78c091f2021-04-09 21:38:30 +00001051 fn do_table_size_query(
1052 &mut self,
1053 storage_type: StatsdStorageType,
1054 query: &str,
1055 params: &[&str],
1056 ) -> Result<Keystore2StorageStats> {
1057 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1058 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1059 .with_context(|| {
1060 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1061 })
1062 .no_gc()
1063 })?;
1064 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1065 }
1066
1067 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1068 self.do_table_size_query(
1069 StatsdStorageType::Database,
1070 "SELECT page_count * page_size, freelist_count * page_size
1071 FROM pragma_page_count('persistent'),
1072 pragma_page_size('persistent'),
1073 persistent.pragma_freelist_count();",
1074 &[],
1075 )
1076 }
1077
1078 fn get_table_size(
1079 &mut self,
1080 storage_type: StatsdStorageType,
1081 schema: &str,
1082 table: &str,
1083 ) -> Result<Keystore2StorageStats> {
1084 self.do_table_size_query(
1085 storage_type,
1086 "SELECT pgsize,unused FROM dbstat(?1)
1087 WHERE name=?2 AND aggregate=TRUE;",
1088 &[schema, table],
1089 )
1090 }
1091
1092 /// Fetches a storage statisitics atom for a given storage type. For storage
1093 /// types that map to a table, information about the table's storage is
1094 /// returned. Requests for storage types that are not DB tables return None.
1095 pub fn get_storage_stat(
1096 &mut self,
1097 storage_type: StatsdStorageType,
1098 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001099 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1100
Seth Moore78c091f2021-04-09 21:38:30 +00001101 match storage_type {
1102 StatsdStorageType::Database => self.get_total_size(),
1103 StatsdStorageType::KeyEntry => {
1104 self.get_table_size(storage_type, "persistent", "keyentry")
1105 }
1106 StatsdStorageType::KeyEntryIdIndex => {
1107 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1108 }
1109 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1110 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1111 }
1112 StatsdStorageType::BlobEntry => {
1113 self.get_table_size(storage_type, "persistent", "blobentry")
1114 }
1115 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1116 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1117 }
1118 StatsdStorageType::KeyParameter => {
1119 self.get_table_size(storage_type, "persistent", "keyparameter")
1120 }
1121 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1122 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1123 }
1124 StatsdStorageType::KeyMetadata => {
1125 self.get_table_size(storage_type, "persistent", "keymetadata")
1126 }
1127 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1128 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1129 }
1130 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1131 StatsdStorageType::AuthToken => {
1132 self.get_table_size(storage_type, "perboot", "authtoken")
1133 }
1134 StatsdStorageType::BlobMetadata => {
1135 self.get_table_size(storage_type, "persistent", "blobmetadata")
1136 }
1137 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1138 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1139 }
1140 _ => Err(anyhow::Error::msg(format!(
1141 "Unsupported storage type: {}",
1142 storage_type as i32
1143 ))),
1144 }
1145 }
1146
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001147 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001148 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1149 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001150 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1151 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001152 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 blob_ids_to_delete: &[i64],
1155 max_blobs: usize,
1156 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001157 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001158 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001159 // Delete the given blobs.
1160 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161 tx.execute(
1162 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001163 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001164 )
1165 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001166 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1167 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001168 }
Janis Danisevskis3395f862021-05-06 10:54:17 -07001169 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1170 let result: Vec<(i64, Vec<u8>)> = {
1171 let mut stmt = tx
1172 .prepare(
1173 "SELECT id, blob FROM persistent.blobentry
1174 WHERE subcomponent_type = ?
1175 AND (
1176 id NOT IN (
1177 SELECT MAX(id) FROM persistent.blobentry
1178 WHERE subcomponent_type = ?
1179 GROUP BY keyentryid, subcomponent_type
1180 )
1181 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1182 ) LIMIT ?;",
1183 )
1184 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001185
Janis Danisevskis3395f862021-05-06 10:54:17 -07001186 let rows = stmt
1187 .query_map(
1188 params![
1189 SubComponentType::KEY_BLOB,
1190 SubComponentType::KEY_BLOB,
1191 max_blobs as i64,
1192 ],
1193 |row| Ok((row.get(0)?, row.get(1)?)),
1194 )
1195 .context("Trying to query superseded blob.")?;
1196
1197 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1198 .context("Trying to extract superseded blobs.")?
1199 };
1200
1201 let result = result
1202 .into_iter()
1203 .map(|(blob_id, blob)| {
1204 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1205 })
1206 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1207 .context("Trying to load blob metadata.")?;
1208 if !result.is_empty() {
1209 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001210 }
1211
1212 // We did not find any superseded key blob, so let's remove other superseded blob in
1213 // one transaction.
1214 tx.execute(
1215 "DELETE FROM persistent.blobentry
1216 WHERE NOT subcomponent_type = ?
1217 AND (
1218 id NOT IN (
1219 SELECT MAX(id) FROM persistent.blobentry
1220 WHERE NOT subcomponent_type = ?
1221 GROUP BY keyentryid, subcomponent_type
1222 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1223 );",
1224 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1225 )
1226 .context("Trying to purge superseded blobs.")?;
1227
Janis Danisevskis3395f862021-05-06 10:54:17 -07001228 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001229 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001230 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001231 }
1232
1233 /// This maintenance function should be called only once before the database is used for the
1234 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1235 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1236 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1237 /// Keystore crashed at some point during key generation. Callers may want to log such
1238 /// occurrences.
1239 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1240 /// it to `KeyLifeCycle::Live` may have grants.
1241 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001242 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1243
Janis Danisevskis66784c42021-01-27 08:40:25 -08001244 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1245 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001246 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1247 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1248 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001249 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001250 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001251 })
1252 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001253 }
1254
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001255 /// Checks if a key exists with given key type and key descriptor properties.
1256 pub fn key_exists(
1257 &mut self,
1258 domain: Domain,
1259 nspace: i64,
1260 alias: &str,
1261 key_type: KeyType,
1262 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001263 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1264
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001265 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1266 let key_descriptor =
1267 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1268 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1269 match result {
1270 Ok(_) => Ok(true),
1271 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1272 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1273 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1274 },
1275 }
1276 .no_gc()
1277 })
1278 .context("In key_exists.")
1279 }
1280
Hasini Gunasingheda895552021-01-27 19:34:37 +00001281 /// Stores a super key in the database.
1282 pub fn store_super_key(
1283 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001284 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001285 key_type: &SuperKeyType,
1286 blob: &[u8],
1287 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001288 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001289 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001290 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1291
Hasini Gunasingheda895552021-01-27 19:34:37 +00001292 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1293 let key_id = Self::insert_with_retry(|id| {
1294 tx.execute(
1295 "INSERT into persistent.keyentry
1296 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001297 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 params![
1299 id,
1300 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001301 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001302 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001303 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001304 KeyLifeCycle::Live,
1305 &KEYSTORE_UUID,
1306 ],
1307 )
1308 })
1309 .context("Failed to insert into keyentry table.")?;
1310
Paul Crowley8d5b2532021-03-19 10:53:07 -07001311 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1312
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 Self::set_blob_internal(
1314 &tx,
1315 key_id,
1316 SubComponentType::KEY_BLOB,
1317 Some(blob),
1318 Some(blob_metadata),
1319 )
1320 .context("Failed to store key blob.")?;
1321
1322 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1323 .context("Trying to load key components.")
1324 .no_gc()
1325 })
1326 .context("In store_super_key.")
1327 }
1328
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001329 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001330 pub fn load_super_key(
1331 &mut self,
1332 key_type: &SuperKeyType,
1333 user_id: u32,
1334 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001335 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1336
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001337 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1338 let key_descriptor = KeyDescriptor {
1339 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001340 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001341 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001342 blob: None,
1343 };
1344 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1345 match id {
1346 Ok(id) => {
1347 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1348 .context("In load_super_key. Failed to load key entry.")?;
1349 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1350 }
1351 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1352 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1353 _ => Err(error).context("In load_super_key."),
1354 },
1355 }
1356 .no_gc()
1357 })
1358 .context("In load_super_key.")
1359 }
1360
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001361 /// Atomically loads a key entry and associated metadata or creates it using the
1362 /// callback create_new_key callback. The callback is called during a database
1363 /// transaction. This means that implementers should be mindful about using
1364 /// blocking operations such as IPC or grabbing mutexes.
1365 pub fn get_or_create_key_with<F>(
1366 &mut self,
1367 domain: Domain,
1368 namespace: i64,
1369 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001370 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001371 create_new_key: F,
1372 ) -> Result<(KeyIdGuard, KeyEntry)>
1373 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001374 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001375 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001376 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1377
Janis Danisevskis66784c42021-01-27 08:40:25 -08001378 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1379 let id = {
1380 let mut stmt = tx
1381 .prepare(
1382 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001383 WHERE
1384 key_type = ?
1385 AND domain = ?
1386 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001387 AND alias = ?
1388 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001389 )
1390 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1391 let mut rows = stmt
1392 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1393 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001394
Janis Danisevskis66784c42021-01-27 08:40:25 -08001395 db_utils::with_rows_extract_one(&mut rows, |row| {
1396 Ok(match row {
1397 Some(r) => r.get(0).context("Failed to unpack id.")?,
1398 None => None,
1399 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001400 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001401 .context("In get_or_create_key_with.")?
1402 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 let (id, entry) = match id {
1405 Some(id) => (
1406 id,
1407 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1408 .context("In get_or_create_key_with.")?,
1409 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001410
Janis Danisevskis66784c42021-01-27 08:40:25 -08001411 None => {
1412 let id = Self::insert_with_retry(|id| {
1413 tx.execute(
1414 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001415 (id, key_type, domain, namespace, alias, state, km_uuid)
1416 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 params![
1418 id,
1419 KeyType::Super,
1420 domain.0,
1421 namespace,
1422 alias,
1423 KeyLifeCycle::Live,
1424 km_uuid,
1425 ],
1426 )
1427 })
1428 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001429
Janis Danisevskis66784c42021-01-27 08:40:25 -08001430 let (blob, metadata) =
1431 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001432 Self::set_blob_internal(
1433 &tx,
1434 id,
1435 SubComponentType::KEY_BLOB,
1436 Some(&blob),
1437 Some(&metadata),
1438 )
Paul Crowley7a658392021-03-18 17:08:20 -07001439 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001440 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001441 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001442 KeyEntry {
1443 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001444 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001445 pure_cert: false,
1446 ..Default::default()
1447 },
1448 )
1449 }
1450 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001451 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001452 })
1453 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001454 }
1455
Janis Danisevskis66784c42021-01-27 08:40:25 -08001456 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1457 /// waiting for the database file to become available. This makes it
1458 /// impossible to successfully recover from a locked database when the
1459 /// transaction holding the device busy is in the same process on a
1460 /// different connection. As a result the busy handler has to time out and
1461 /// fail in order to make progress.
1462 ///
1463 /// Instead, we set the busy handler to None (return immediately). And catch
1464 /// Busy and Locked errors (the latter occur on in memory databases with
1465 /// shared cache, e.g., the per-boot database.) and restart the transaction
1466 /// after a grace period of half a millisecond.
1467 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001468 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001469 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1470 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001471 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1472 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001473 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001474 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001475 loop {
1476 match self
1477 .conn
1478 .transaction_with_behavior(behavior)
1479 .context("In with_transaction.")
1480 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1481 .and_then(|(result, tx)| {
1482 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1483 Ok(result)
1484 }) {
1485 Ok(result) => break Ok(result),
1486 Err(e) => {
1487 if Self::is_locked_error(&e) {
1488 std::thread::sleep(std::time::Duration::from_micros(500));
1489 continue;
1490 } else {
1491 return Err(e).context("In with_transaction.");
1492 }
1493 }
1494 }
1495 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001496 .map(|(need_gc, result)| {
1497 if need_gc {
1498 if let Some(ref gc) = self.gc {
1499 gc.notify_gc();
1500 }
1501 }
1502 result
1503 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001504 }
1505
1506 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001507 matches!(
1508 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1509 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1510 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1511 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001512 }
1513
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001514 /// Creates a new key entry and allocates a new randomized id for the new key.
1515 /// The key id gets associated with a domain and namespace but not with an alias.
1516 /// To complete key generation `rebind_alias` should be called after all of the
1517 /// key artifacts, i.e., blobs and parameters have been associated with the new
1518 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1519 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001520 pub fn create_key_entry(
1521 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001522 domain: &Domain,
1523 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001524 km_uuid: &Uuid,
1525 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001526 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1527
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001529 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001530 })
1531 .context("In create_key_entry.")
1532 }
1533
1534 fn create_key_entry_internal(
1535 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001536 domain: &Domain,
1537 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001538 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001539 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001540 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001541 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001542 _ => {
1543 return Err(KsError::sys())
1544 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1545 }
1546 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001547 Ok(KEY_ID_LOCK.get(
1548 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001549 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001550 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001551 (id, key_type, domain, namespace, alias, state, km_uuid)
1552 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001553 params![
1554 id,
1555 KeyType::Client,
1556 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001557 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001558 KeyLifeCycle::Existing,
1559 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001560 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001561 )
1562 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001563 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001564 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001565 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001566
Max Bires2b2e6562020-09-22 11:22:36 -07001567 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1568 /// The key id gets associated with a domain and namespace later but not with an alias. The
1569 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1570 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1571 /// a key.
1572 pub fn create_attestation_key_entry(
1573 &mut self,
1574 maced_public_key: &[u8],
1575 raw_public_key: &[u8],
1576 private_key: &[u8],
1577 km_uuid: &Uuid,
1578 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001579 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1580
Max Bires2b2e6562020-09-22 11:22:36 -07001581 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1582 let key_id = KEY_ID_LOCK.get(
1583 Self::insert_with_retry(|id| {
1584 tx.execute(
1585 "INSERT into persistent.keyentry
1586 (id, key_type, domain, namespace, alias, state, km_uuid)
1587 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1588 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1589 )
1590 })
1591 .context("In create_key_entry")?,
1592 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001593 Self::set_blob_internal(
1594 &tx,
1595 key_id.0,
1596 SubComponentType::KEY_BLOB,
1597 Some(private_key),
1598 None,
1599 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001600 let mut metadata = KeyMetaData::new();
1601 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1602 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1603 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001604 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001605 })
1606 .context("In create_attestation_key_entry")
1607 }
1608
Janis Danisevskis377d1002021-01-27 19:07:48 -08001609 /// Set a new blob and associates it with the given key id. Each blob
1610 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001611 /// Each key can have one of each sub component type associated. If more
1612 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001613 /// will get garbage collected.
1614 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1615 /// removed by setting blob to None.
1616 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001617 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001618 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001619 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001620 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001621 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001622 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001623 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1624
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001625 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001626 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001627 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001628 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001629 }
1630
Janis Danisevskiseed69842021-02-18 20:04:10 -08001631 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1632 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1633 /// We use this to insert key blobs into the database which can then be garbage collected
1634 /// lazily by the key garbage collector.
1635 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001636 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1637
Janis Danisevskiseed69842021-02-18 20:04:10 -08001638 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1639 Self::set_blob_internal(
1640 &tx,
1641 Self::UNASSIGNED_KEY_ID,
1642 SubComponentType::KEY_BLOB,
1643 Some(blob),
1644 Some(blob_metadata),
1645 )
1646 .need_gc()
1647 })
1648 .context("In set_deleted_blob.")
1649 }
1650
Janis Danisevskis377d1002021-01-27 19:07:48 -08001651 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001652 tx: &Transaction,
1653 key_id: i64,
1654 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001655 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001656 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001657 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001658 match (blob, sc_type) {
1659 (Some(blob), _) => {
1660 tx.execute(
1661 "INSERT INTO persistent.blobentry
1662 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1663 params![sc_type, key_id, blob],
1664 )
1665 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001666 if let Some(blob_metadata) = blob_metadata {
1667 let blob_id = tx
1668 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1669 row.get(0)
1670 })
1671 .context("In set_blob_internal: Failed to get new blob id.")?;
1672 blob_metadata
1673 .store_in_db(blob_id, tx)
1674 .context("In set_blob_internal: Trying to store blob metadata.")?;
1675 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001676 }
1677 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1678 tx.execute(
1679 "DELETE FROM persistent.blobentry
1680 WHERE subcomponent_type = ? AND keyentryid = ?;",
1681 params![sc_type, key_id],
1682 )
1683 .context("In set_blob_internal: Failed to delete blob.")?;
1684 }
1685 (None, _) => {
1686 return Err(KsError::sys())
1687 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1688 }
1689 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001690 Ok(())
1691 }
1692
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001693 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1694 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001695 #[cfg(test)]
1696 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001697 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001698 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001699 })
1700 .context("In insert_keyparameter.")
1701 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001702
Janis Danisevskis66784c42021-01-27 08:40:25 -08001703 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001704 tx: &Transaction,
1705 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001706 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001707 ) -> Result<()> {
1708 let mut stmt = tx
1709 .prepare(
1710 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1711 VALUES (?, ?, ?, ?);",
1712 )
1713 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1714
Janis Danisevskis66784c42021-01-27 08:40:25 -08001715 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001716 stmt.insert(params![
1717 key_id.0,
1718 p.get_tag().0,
1719 p.key_parameter_value(),
1720 p.security_level().0
1721 ])
1722 .with_context(|| {
1723 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1724 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001725 }
1726 Ok(())
1727 }
1728
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001729 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001730 #[cfg(test)]
1731 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001732 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001733 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001734 })
1735 .context("In insert_key_metadata.")
1736 }
1737
Max Bires2b2e6562020-09-22 11:22:36 -07001738 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1739 /// on the public key.
1740 pub fn store_signed_attestation_certificate_chain(
1741 &mut self,
1742 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001743 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001744 cert_chain: &[u8],
1745 expiration_date: i64,
1746 km_uuid: &Uuid,
1747 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001748 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1749
Max Bires2b2e6562020-09-22 11:22:36 -07001750 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1751 let mut stmt = tx
1752 .prepare(
1753 "SELECT keyentryid
1754 FROM persistent.keymetadata
1755 WHERE tag = ? AND data = ? AND keyentryid IN
1756 (SELECT id
1757 FROM persistent.keyentry
1758 WHERE
1759 alias IS NULL AND
1760 domain IS NULL AND
1761 namespace IS NULL AND
1762 key_type = ? AND
1763 km_uuid = ?);",
1764 )
1765 .context("Failed to store attestation certificate chain.")?;
1766 let mut rows = stmt
1767 .query(params![
1768 KeyMetaData::AttestationRawPubKey,
1769 raw_public_key,
1770 KeyType::Attestation,
1771 km_uuid
1772 ])
1773 .context("Failed to fetch keyid")?;
1774 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1775 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1776 .get(0)
1777 .context("Failed to unpack id.")
1778 })
1779 .context("Failed to get key_id.")?;
1780 let num_updated = tx
1781 .execute(
1782 "UPDATE persistent.keyentry
1783 SET alias = ?
1784 WHERE id = ?;",
1785 params!["signed", key_id],
1786 )
1787 .context("Failed to update alias.")?;
1788 if num_updated != 1 {
1789 return Err(KsError::sys()).context("Alias not updated for the key.");
1790 }
1791 let mut metadata = KeyMetaData::new();
1792 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1793 expiration_date,
1794 )));
1795 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001796 Self::set_blob_internal(
1797 &tx,
1798 key_id,
1799 SubComponentType::CERT_CHAIN,
1800 Some(cert_chain),
1801 None,
1802 )
1803 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001804 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1805 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001806 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001807 })
1808 .context("In store_signed_attestation_certificate_chain: ")
1809 }
1810
1811 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1812 /// currently have a key assigned to it.
1813 pub fn assign_attestation_key(
1814 &mut self,
1815 domain: Domain,
1816 namespace: i64,
1817 km_uuid: &Uuid,
1818 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001819 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1820
Max Bires2b2e6562020-09-22 11:22:36 -07001821 match domain {
1822 Domain::APP | Domain::SELINUX => {}
1823 _ => {
1824 return Err(KsError::sys()).context(format!(
1825 concat!(
1826 "In assign_attestation_key: Domain {:?} ",
1827 "must be either App or SELinux.",
1828 ),
1829 domain
1830 ));
1831 }
1832 }
1833 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1834 let result = tx
1835 .execute(
1836 "UPDATE persistent.keyentry
1837 SET domain=?1, namespace=?2
1838 WHERE
1839 id =
1840 (SELECT MIN(id)
1841 FROM persistent.keyentry
1842 WHERE ALIAS IS NOT NULL
1843 AND domain IS NULL
1844 AND key_type IS ?3
1845 AND state IS ?4
1846 AND km_uuid IS ?5)
1847 AND
1848 (SELECT COUNT(*)
1849 FROM persistent.keyentry
1850 WHERE domain=?1
1851 AND namespace=?2
1852 AND key_type IS ?3
1853 AND state IS ?4
1854 AND km_uuid IS ?5) = 0;",
1855 params![
1856 domain.0 as u32,
1857 namespace,
1858 KeyType::Attestation,
1859 KeyLifeCycle::Live,
1860 km_uuid,
1861 ],
1862 )
1863 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001864 if result == 0 {
1865 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1866 } else if result > 1 {
1867 return Err(KsError::sys())
1868 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001869 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001870 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001871 })
1872 .context("In assign_attestation_key: ")
1873 }
1874
1875 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1876 /// provisioning server, or the maximum number available if there are not num_keys number of
1877 /// entries in the table.
1878 pub fn fetch_unsigned_attestation_keys(
1879 &mut self,
1880 num_keys: i32,
1881 km_uuid: &Uuid,
1882 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001883 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1884
Max Bires2b2e6562020-09-22 11:22:36 -07001885 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1886 let mut stmt = tx
1887 .prepare(
1888 "SELECT data
1889 FROM persistent.keymetadata
1890 WHERE tag = ? AND keyentryid IN
1891 (SELECT id
1892 FROM persistent.keyentry
1893 WHERE
1894 alias IS NULL AND
1895 domain IS NULL AND
1896 namespace IS NULL AND
1897 key_type = ? AND
1898 km_uuid = ?
1899 LIMIT ?);",
1900 )
1901 .context("Failed to prepare statement")?;
1902 let rows = stmt
1903 .query_map(
1904 params![
1905 KeyMetaData::AttestationMacedPublicKey,
1906 KeyType::Attestation,
1907 km_uuid,
1908 num_keys
1909 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001910 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001911 )?
1912 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1913 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001914 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001915 })
1916 .context("In fetch_unsigned_attestation_keys")
1917 }
1918
1919 /// Removes any keys that have expired as of the current time. Returns the number of keys
1920 /// marked unreferenced that are bound to be garbage collected.
1921 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001922 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1923
Max Bires2b2e6562020-09-22 11:22:36 -07001924 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1925 let mut stmt = tx
1926 .prepare(
1927 "SELECT keyentryid, data
1928 FROM persistent.keymetadata
1929 WHERE tag = ? AND keyentryid IN
1930 (SELECT id
1931 FROM persistent.keyentry
1932 WHERE key_type = ?);",
1933 )
1934 .context("Failed to prepare query")?;
1935 let key_ids_to_check = stmt
1936 .query_map(
1937 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1938 |row| Ok((row.get(0)?, row.get(1)?)),
1939 )?
1940 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1941 .context("Failed to get date metadata")?;
1942 let curr_time = DateTime::from_millis_epoch(
1943 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1944 );
1945 let mut num_deleted = 0;
1946 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1947 if Self::mark_unreferenced(&tx, id)? {
1948 num_deleted += 1;
1949 }
1950 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001951 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001952 })
1953 .context("In delete_expired_attestation_keys: ")
1954 }
1955
Max Bires60d7ed12021-03-05 15:59:22 -08001956 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1957 /// they are in. This is useful primarily as a testing mechanism.
1958 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001959 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1960
Max Bires60d7ed12021-03-05 15:59:22 -08001961 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1962 let mut stmt = tx
1963 .prepare(
1964 "SELECT id FROM persistent.keyentry
1965 WHERE key_type IS ?;",
1966 )
1967 .context("Failed to prepare statement")?;
1968 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001969 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001970 .collect::<rusqlite::Result<Vec<i64>>>()
1971 .context("Failed to execute statement")?;
1972 let num_deleted = keys_to_delete
1973 .iter()
1974 .map(|id| Self::mark_unreferenced(&tx, *id))
1975 .collect::<Result<Vec<bool>>>()
1976 .context("Failed to execute mark_unreferenced on a keyid")?
1977 .into_iter()
1978 .filter(|result| *result)
1979 .count() as i64;
1980 Ok(num_deleted).do_gc(num_deleted != 0)
1981 })
1982 .context("In delete_all_attestation_keys: ")
1983 }
1984
Max Bires2b2e6562020-09-22 11:22:36 -07001985 /// Counts the number of keys that will expire by the provided epoch date and the number of
1986 /// keys not currently assigned to a domain.
1987 pub fn get_attestation_pool_status(
1988 &mut self,
1989 date: i64,
1990 km_uuid: &Uuid,
1991 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001992 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1993
Max Bires2b2e6562020-09-22 11:22:36 -07001994 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1995 let mut stmt = tx.prepare(
1996 "SELECT data
1997 FROM persistent.keymetadata
1998 WHERE tag = ? AND keyentryid IN
1999 (SELECT id
2000 FROM persistent.keyentry
2001 WHERE alias IS NOT NULL
2002 AND key_type = ?
2003 AND km_uuid = ?
2004 AND state = ?);",
2005 )?;
2006 let times = stmt
2007 .query_map(
2008 params![
2009 KeyMetaData::AttestationExpirationDate,
2010 KeyType::Attestation,
2011 km_uuid,
2012 KeyLifeCycle::Live
2013 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002014 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002015 )?
2016 .collect::<rusqlite::Result<Vec<DateTime>>>()
2017 .context("Failed to execute metadata statement")?;
2018 let expiring =
2019 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2020 as i32;
2021 stmt = tx.prepare(
2022 "SELECT alias, domain
2023 FROM persistent.keyentry
2024 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2025 )?;
2026 let rows = stmt
2027 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2028 Ok((row.get(0)?, row.get(1)?))
2029 })?
2030 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2031 .context("Failed to execute keyentry statement")?;
2032 let mut unassigned = 0i32;
2033 let mut attested = 0i32;
2034 let total = rows.len() as i32;
2035 for (alias, domain) in rows {
2036 match (alias, domain) {
2037 (Some(_alias), None) => {
2038 attested += 1;
2039 unassigned += 1;
2040 }
2041 (Some(_alias), Some(_domain)) => {
2042 attested += 1;
2043 }
2044 _ => {}
2045 }
2046 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002047 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002048 })
2049 .context("In get_attestation_pool_status: ")
2050 }
2051
2052 /// Fetches the private key and corresponding certificate chain assigned to a
2053 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2054 /// not assigned, or one CertificateChain.
2055 pub fn retrieve_attestation_key_and_cert_chain(
2056 &mut self,
2057 domain: Domain,
2058 namespace: i64,
2059 km_uuid: &Uuid,
2060 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002061 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2062
Max Bires2b2e6562020-09-22 11:22:36 -07002063 match domain {
2064 Domain::APP | Domain::SELINUX => {}
2065 _ => {
2066 return Err(KsError::sys())
2067 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2068 }
2069 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002070 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2071 let mut stmt = tx.prepare(
2072 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002073 FROM persistent.blobentry
2074 WHERE keyentryid IN
2075 (SELECT id
2076 FROM persistent.keyentry
2077 WHERE key_type = ?
2078 AND domain = ?
2079 AND namespace = ?
2080 AND state = ?
2081 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 )?;
2083 let rows = stmt
2084 .query_map(
2085 params![
2086 KeyType::Attestation,
2087 domain.0 as u32,
2088 namespace,
2089 KeyLifeCycle::Live,
2090 km_uuid
2091 ],
2092 |row| Ok((row.get(0)?, row.get(1)?)),
2093 )?
2094 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002095 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002096 if rows.is_empty() {
2097 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002098 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002099 return Err(KsError::sys()).context(format!(
2100 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002101 "Expected to get a single attestation",
2102 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2103 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002104 rows.len()
2105 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002106 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002107 let mut km_blob: Vec<u8> = Vec::new();
2108 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002109 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002110 for row in rows {
2111 let sub_type: SubComponentType = row.0;
2112 match sub_type {
2113 SubComponentType::KEY_BLOB => {
2114 km_blob = row.1;
2115 }
2116 SubComponentType::CERT_CHAIN => {
2117 cert_chain_blob = row.1;
2118 }
Max Biresb2e1d032021-02-08 21:35:05 -08002119 SubComponentType::CERT => {
2120 batch_cert_blob = row.1;
2121 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002122 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2123 }
2124 }
2125 Ok(Some(CertificateChain {
2126 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002127 batch_cert: batch_cert_blob,
2128 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002129 }))
2130 .no_gc()
2131 })
Max Biresb2e1d032021-02-08 21:35:05 -08002132 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002133 }
2134
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002135 /// Updates the alias column of the given key id `newid` with the given alias,
2136 /// and atomically, removes the alias, domain, and namespace from another row
2137 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002138 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2139 /// collector.
2140 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002141 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002142 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002143 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002144 domain: &Domain,
2145 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002146 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002147 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002148 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002149 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002150 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002151 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002152 domain
2153 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002154 }
2155 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002156 let updated = tx
2157 .execute(
2158 "UPDATE persistent.keyentry
2159 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002160 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002161 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2162 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002163 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002164 let result = tx
2165 .execute(
2166 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002167 SET alias = ?, state = ?
2168 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2169 params![
2170 alias,
2171 KeyLifeCycle::Live,
2172 newid.0,
2173 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002174 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002175 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002176 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002177 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002178 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002179 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002180 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002181 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002182 result
2183 ));
2184 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002185 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002186 }
2187
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002188 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2189 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2190 pub fn migrate_key_namespace(
2191 &mut self,
2192 key_id_guard: KeyIdGuard,
2193 destination: &KeyDescriptor,
2194 caller_uid: u32,
2195 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2196 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002197 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2198
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002199 let destination = match destination.domain {
2200 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2201 Domain::SELINUX => (*destination).clone(),
2202 domain => {
2203 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2204 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2205 }
2206 };
2207
2208 // Security critical: Must return immediately on failure. Do not remove the '?';
2209 check_permission(&destination)
2210 .context("In migrate_key_namespace: Trying to check permission.")?;
2211
2212 let alias = destination
2213 .alias
2214 .as_ref()
2215 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2216 .context("In migrate_key_namespace: Alias must be specified.")?;
2217
2218 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2219 // Query the destination location. If there is a key, the migration request fails.
2220 if tx
2221 .query_row(
2222 "SELECT id FROM persistent.keyentry
2223 WHERE alias = ? AND domain = ? AND namespace = ?;",
2224 params![alias, destination.domain.0, destination.nspace],
2225 |_| Ok(()),
2226 )
2227 .optional()
2228 .context("Failed to query destination.")?
2229 .is_some()
2230 {
2231 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2232 .context("Target already exists.");
2233 }
2234
2235 let updated = tx
2236 .execute(
2237 "UPDATE persistent.keyentry
2238 SET alias = ?, domain = ?, namespace = ?
2239 WHERE id = ?;",
2240 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2241 )
2242 .context("Failed to update key entry.")?;
2243
2244 if updated != 1 {
2245 return Err(KsError::sys())
2246 .context(format!("Update succeeded, but {} rows were updated.", updated));
2247 }
2248 Ok(()).no_gc()
2249 })
2250 .context("In migrate_key_namespace:")
2251 }
2252
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002253 /// Store a new key in a single transaction.
2254 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2255 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002256 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2257 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002258 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002259 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002260 key: &KeyDescriptor,
2261 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002262 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002263 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002264 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002265 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002266 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002267 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2268
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002269 let (alias, domain, namespace) = match key {
2270 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2271 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2272 (alias, key.domain, nspace)
2273 }
2274 _ => {
2275 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2276 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2277 }
2278 };
2279 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002280 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002281 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002282 let (blob, blob_metadata) = *blob_info;
2283 Self::set_blob_internal(
2284 tx,
2285 key_id.id(),
2286 SubComponentType::KEY_BLOB,
2287 Some(blob),
2288 Some(&blob_metadata),
2289 )
2290 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002291 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002292 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002293 .context("Trying to insert the certificate.")?;
2294 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002295 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002296 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002297 tx,
2298 key_id.id(),
2299 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002300 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002301 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002302 )
2303 .context("Trying to insert the certificate chain.")?;
2304 }
2305 Self::insert_keyparameter_internal(tx, &key_id, params)
2306 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002307 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002308 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002309 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002310 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002311 })
2312 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002313 }
2314
Janis Danisevskis377d1002021-01-27 19:07:48 -08002315 /// Store a new certificate
2316 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2317 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002318 pub fn store_new_certificate(
2319 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002320 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002321 cert: &[u8],
2322 km_uuid: &Uuid,
2323 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002324 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2325
Janis Danisevskis377d1002021-01-27 19:07:48 -08002326 let (alias, domain, namespace) = match key {
2327 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2328 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2329 (alias, key.domain, nspace)
2330 }
2331 _ => {
2332 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2333 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2334 )
2335 }
2336 };
2337 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002338 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002339 .context("Trying to create new key entry.")?;
2340
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002341 Self::set_blob_internal(
2342 tx,
2343 key_id.id(),
2344 SubComponentType::CERT_CHAIN,
2345 Some(cert),
2346 None,
2347 )
2348 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002349
2350 let mut metadata = KeyMetaData::new();
2351 metadata.add(KeyMetaEntry::CreationDate(
2352 DateTime::now().context("Trying to make creation time.")?,
2353 ));
2354
2355 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2356
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002357 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002358 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002359 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002360 })
2361 .context("In store_new_certificate.")
2362 }
2363
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002364 // Helper function loading the key_id given the key descriptor
2365 // tuple comprising domain, namespace, and alias.
2366 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002367 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002368 let alias = key
2369 .alias
2370 .as_ref()
2371 .map_or_else(|| Err(KsError::sys()), Ok)
2372 .context("In load_key_entry_id: Alias must be specified.")?;
2373 let mut stmt = tx
2374 .prepare(
2375 "SELECT id FROM persistent.keyentry
2376 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002377 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002378 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002379 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002380 AND alias = ?
2381 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002382 )
2383 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2384 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002385 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002386 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002387 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002388 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002389 .get(0)
2390 .context("Failed to unpack id.")
2391 })
2392 .context("In load_key_entry_id.")
2393 }
2394
2395 /// This helper function completes the access tuple of a key, which is required
2396 /// to perform access control. The strategy depends on the `domain` field in the
2397 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002398 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002399 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002400 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002401 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002402 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002403 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002404 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002405 /// `namespace`.
2406 /// In each case the information returned is sufficient to perform the access
2407 /// check and the key id can be used to load further key artifacts.
2408 fn load_access_tuple(
2409 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002410 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002411 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002412 caller_uid: u32,
2413 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2414 match key.domain {
2415 // Domain App or SELinux. In this case we load the key_id from
2416 // the keyentry database for further loading of key components.
2417 // We already have the full access tuple to perform access control.
2418 // The only distinction is that we use the caller_uid instead
2419 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002420 // Domain::APP.
2421 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002422 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002423 if access_key.domain == Domain::APP {
2424 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002425 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002426 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002427 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002428
2429 Ok((key_id, access_key, None))
2430 }
2431
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002432 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002433 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002434 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002435 let mut stmt = tx
2436 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002437 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 WHERE grantee = ? AND id = ?;",
2439 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002440 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002441 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002442 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002443 .context("Domain:Grant: query failed.")?;
2444 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002445 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002446 let r =
2447 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002448 Ok((
2449 r.get(0).context("Failed to unpack key_id.")?,
2450 r.get(1).context("Failed to unpack access_vector.")?,
2451 ))
2452 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002453 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002454 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002455 }
2456
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002457 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002458 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002459 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002460 let (domain, namespace): (Domain, i64) = {
2461 let mut stmt = tx
2462 .prepare(
2463 "SELECT domain, namespace FROM persistent.keyentry
2464 WHERE
2465 id = ?
2466 AND state = ?;",
2467 )
2468 .context("Domain::KEY_ID: prepare statement failed")?;
2469 let mut rows = stmt
2470 .query(params![key.nspace, KeyLifeCycle::Live])
2471 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002472 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002473 let r =
2474 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002475 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002476 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002477 r.get(1).context("Failed to unpack namespace.")?,
2478 ))
2479 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002480 .context("Domain::KEY_ID.")?
2481 };
2482
2483 // We may use a key by id after loading it by grant.
2484 // In this case we have to check if the caller has a grant for this particular
2485 // key. We can skip this if we already know that the caller is the owner.
2486 // But we cannot know this if domain is anything but App. E.g. in the case
2487 // of Domain::SELINUX we have to speculatively check for grants because we have to
2488 // consult the SEPolicy before we know if the caller is the owner.
2489 let access_vector: Option<KeyPermSet> =
2490 if domain != Domain::APP || namespace != caller_uid as i64 {
2491 let access_vector: Option<i32> = tx
2492 .query_row(
2493 "SELECT access_vector FROM persistent.grant
2494 WHERE grantee = ? AND keyentryid = ?;",
2495 params![caller_uid as i64, key.nspace],
2496 |row| row.get(0),
2497 )
2498 .optional()
2499 .context("Domain::KEY_ID: query grant failed.")?;
2500 access_vector.map(|p| p.into())
2501 } else {
2502 None
2503 };
2504
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002505 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002506 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002507 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002508 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002509
Janis Danisevskis45760022021-01-19 16:34:10 -08002510 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002511 }
2512 _ => Err(anyhow!(KsError::sys())),
2513 }
2514 }
2515
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002516 fn load_blob_components(
2517 key_id: i64,
2518 load_bits: KeyEntryLoadBits,
2519 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002520 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002521 let mut stmt = tx
2522 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002523 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002524 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2525 )
2526 .context("In load_blob_components: prepare statement failed.")?;
2527
2528 let mut rows =
2529 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2530
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002531 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002532 let mut cert_blob: Option<Vec<u8>> = None;
2533 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002534 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002535 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002536 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002537 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002538 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002539 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2540 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002541 key_blob = Some((
2542 row.get(0).context("Failed to extract key blob id.")?,
2543 row.get(2).context("Failed to extract key blob.")?,
2544 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002545 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002546 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002547 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002548 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002549 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002550 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002551 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002552 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002553 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002554 (SubComponentType::CERT, _, _)
2555 | (SubComponentType::CERT_CHAIN, _, _)
2556 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002557 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2558 }
2559 Ok(())
2560 })
2561 .context("In load_blob_components.")?;
2562
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002563 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2564 Ok(Some((
2565 blob,
2566 BlobMetaData::load_from_db(blob_id, tx)
2567 .context("In load_blob_components: Trying to load blob_metadata.")?,
2568 )))
2569 })?;
2570
2571 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002572 }
2573
2574 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2575 let mut stmt = tx
2576 .prepare(
2577 "SELECT tag, data, security_level from persistent.keyparameter
2578 WHERE keyentryid = ?;",
2579 )
2580 .context("In load_key_parameters: prepare statement failed.")?;
2581
2582 let mut parameters: Vec<KeyParameter> = Vec::new();
2583
2584 let mut rows =
2585 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002586 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002587 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2588 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002589 parameters.push(
2590 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2591 .context("Failed to read KeyParameter.")?,
2592 );
2593 Ok(())
2594 })
2595 .context("In load_key_parameters.")?;
2596
2597 Ok(parameters)
2598 }
2599
Qi Wub9433b52020-12-01 14:52:46 +08002600 /// Decrements the usage count of a limited use key. This function first checks whether the
2601 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2602 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2603 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002604 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002605 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2606
Qi Wub9433b52020-12-01 14:52:46 +08002607 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2608 let limit: Option<i32> = tx
2609 .query_row(
2610 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2611 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2612 |row| row.get(0),
2613 )
2614 .optional()
2615 .context("Trying to load usage count")?;
2616
2617 let limit = limit
2618 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2619 .context("The Key no longer exists. Key is exhausted.")?;
2620
2621 tx.execute(
2622 "UPDATE persistent.keyparameter
2623 SET data = data - 1
2624 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2625 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2626 )
2627 .context("Failed to update key usage count.")?;
2628
2629 match limit {
2630 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002631 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002632 .context("Trying to mark limited use key for deletion."),
2633 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002634 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002635 }
2636 })
2637 .context("In check_and_update_key_usage_count.")
2638 }
2639
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002640 /// Load a key entry by the given key descriptor.
2641 /// It uses the `check_permission` callback to verify if the access is allowed
2642 /// given the key access tuple read from the database using `load_access_tuple`.
2643 /// With `load_bits` the caller may specify which blobs shall be loaded from
2644 /// the blob database.
2645 pub fn load_key_entry(
2646 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002647 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002648 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002649 load_bits: KeyEntryLoadBits,
2650 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002651 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2652 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002653 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2654
Janis Danisevskis66784c42021-01-27 08:40:25 -08002655 loop {
2656 match self.load_key_entry_internal(
2657 key,
2658 key_type,
2659 load_bits,
2660 caller_uid,
2661 &check_permission,
2662 ) {
2663 Ok(result) => break Ok(result),
2664 Err(e) => {
2665 if Self::is_locked_error(&e) {
2666 std::thread::sleep(std::time::Duration::from_micros(500));
2667 continue;
2668 } else {
2669 return Err(e).context("In load_key_entry.");
2670 }
2671 }
2672 }
2673 }
2674 }
2675
2676 fn load_key_entry_internal(
2677 &mut self,
2678 key: &KeyDescriptor,
2679 key_type: KeyType,
2680 load_bits: KeyEntryLoadBits,
2681 caller_uid: u32,
2682 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002683 ) -> Result<(KeyIdGuard, KeyEntry)> {
2684 // KEY ID LOCK 1/2
2685 // If we got a key descriptor with a key id we can get the lock right away.
2686 // Otherwise we have to defer it until we know the key id.
2687 let key_id_guard = match key.domain {
2688 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2689 _ => None,
2690 };
2691
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002692 let tx = self
2693 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002694 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002695 .context("In load_key_entry: Failed to initialize transaction.")?;
2696
2697 // Load the key_id and complete the access control tuple.
2698 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002699 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2700 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002701
2702 // Perform access control. It is vital that we return here if the permission is denied.
2703 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002704 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002705
Janis Danisevskisaec14592020-11-12 09:41:49 -08002706 // KEY ID LOCK 2/2
2707 // If we did not get a key id lock by now, it was because we got a key descriptor
2708 // without a key id. At this point we got the key id, so we can try and get a lock.
2709 // However, we cannot block here, because we are in the middle of the transaction.
2710 // So first we try to get the lock non blocking. If that fails, we roll back the
2711 // transaction and block until we get the lock. After we successfully got the lock,
2712 // we start a new transaction and load the access tuple again.
2713 //
2714 // We don't need to perform access control again, because we already established
2715 // that the caller had access to the given key. But we need to make sure that the
2716 // key id still exists. So we have to load the key entry by key id this time.
2717 let (key_id_guard, tx) = match key_id_guard {
2718 None => match KEY_ID_LOCK.try_get(key_id) {
2719 None => {
2720 // Roll back the transaction.
2721 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002722
Janis Danisevskisaec14592020-11-12 09:41:49 -08002723 // Block until we have a key id lock.
2724 let key_id_guard = KEY_ID_LOCK.get(key_id);
2725
2726 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002727 let tx = self
2728 .conn
2729 .unchecked_transaction()
2730 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002731
2732 Self::load_access_tuple(
2733 &tx,
2734 // This time we have to load the key by the retrieved key id, because the
2735 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002736 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002737 domain: Domain::KEY_ID,
2738 nspace: key_id,
2739 ..Default::default()
2740 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002741 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002742 caller_uid,
2743 )
2744 .context("In load_key_entry. (deferred key lock)")?;
2745 (key_id_guard, tx)
2746 }
2747 Some(l) => (l, tx),
2748 },
2749 Some(key_id_guard) => (key_id_guard, tx),
2750 };
2751
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002752 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2753 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002754
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002755 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2756
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002757 Ok((key_id_guard, key_entry))
2758 }
2759
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002760 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002761 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002762 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2763 .context("Trying to delete keyentry.")?;
2764 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2765 .context("Trying to delete keymetadata.")?;
2766 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2767 .context("Trying to delete keyparameters.")?;
2768 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2769 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002770 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002771 }
2772
2773 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002774 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002775 pub fn unbind_key(
2776 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002777 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002778 key_type: KeyType,
2779 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002780 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002781 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002782 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2783
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002784 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2785 let (key_id, access_key_descriptor, access_vector) =
2786 Self::load_access_tuple(tx, key, key_type, caller_uid)
2787 .context("Trying to get access tuple.")?;
2788
2789 // Perform access control. It is vital that we return here if the permission is denied.
2790 // So do not touch that '?' at the end.
2791 check_permission(&access_key_descriptor, access_vector)
2792 .context("While checking permission.")?;
2793
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002794 Self::mark_unreferenced(tx, key_id)
2795 .map(|need_gc| (need_gc, ()))
2796 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002797 })
2798 .context("In unbind_key.")
2799 }
2800
Max Bires8e93d2b2021-01-14 13:17:59 -08002801 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2802 tx.query_row(
2803 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2804 params![key_id],
2805 |row| row.get(0),
2806 )
2807 .context("In get_key_km_uuid.")
2808 }
2809
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002810 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2811 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2812 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002813 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2814
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002815 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2816 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2817 .context("In unbind_keys_for_namespace.");
2818 }
2819 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2820 tx.execute(
2821 "DELETE FROM persistent.keymetadata
2822 WHERE keyentryid IN (
2823 SELECT id FROM persistent.keyentry
2824 WHERE domain = ? AND namespace = ?
2825 );",
2826 params![domain.0, namespace],
2827 )
2828 .context("Trying to delete keymetadata.")?;
2829 tx.execute(
2830 "DELETE FROM persistent.keyparameter
2831 WHERE keyentryid IN (
2832 SELECT id FROM persistent.keyentry
2833 WHERE domain = ? AND namespace = ?
2834 );",
2835 params![domain.0, namespace],
2836 )
2837 .context("Trying to delete keyparameters.")?;
2838 tx.execute(
2839 "DELETE FROM persistent.grant
2840 WHERE keyentryid IN (
2841 SELECT id FROM persistent.keyentry
2842 WHERE domain = ? AND namespace = ?
2843 );",
2844 params![domain.0, namespace],
2845 )
2846 .context("Trying to delete grants.")?;
2847 tx.execute(
2848 "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;",
2849 params![domain.0, namespace],
2850 )
2851 .context("Trying to delete keyentry.")?;
2852 Ok(()).need_gc()
2853 })
2854 .context("In unbind_keys_for_namespace")
2855 }
2856
Hasini Gunasingheda895552021-01-27 19:34:37 +00002857 /// Delete the keys created on behalf of the user, denoted by the user id.
2858 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2859 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2860 /// The caller of this function should notify the gc if the returned value is true.
2861 pub fn unbind_keys_for_user(
2862 &mut self,
2863 user_id: u32,
2864 keep_non_super_encrypted_keys: bool,
2865 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002866 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2867
Hasini Gunasingheda895552021-01-27 19:34:37 +00002868 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2869 let mut stmt = tx
2870 .prepare(&format!(
2871 "SELECT id from persistent.keyentry
2872 WHERE (
2873 key_type = ?
2874 AND domain = ?
2875 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2876 AND state = ?
2877 ) OR (
2878 key_type = ?
2879 AND namespace = ?
2880 AND alias = ?
2881 AND state = ?
2882 );",
2883 aid_user_offset = AID_USER_OFFSET
2884 ))
2885 .context(concat!(
2886 "In unbind_keys_for_user. ",
2887 "Failed to prepare the query to find the keys created by apps."
2888 ))?;
2889
2890 let mut rows = stmt
2891 .query(params![
2892 // WHERE client key:
2893 KeyType::Client,
2894 Domain::APP.0 as u32,
2895 user_id,
2896 KeyLifeCycle::Live,
2897 // OR super key:
2898 KeyType::Super,
2899 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002900 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002901 KeyLifeCycle::Live
2902 ])
2903 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2904
2905 let mut key_ids: Vec<i64> = Vec::new();
2906 db_utils::with_rows_extract_all(&mut rows, |row| {
2907 key_ids
2908 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2909 Ok(())
2910 })
2911 .context("In unbind_keys_for_user.")?;
2912
2913 let mut notify_gc = false;
2914 for key_id in key_ids {
2915 if keep_non_super_encrypted_keys {
2916 // Load metadata and filter out non-super-encrypted keys.
2917 if let (_, Some((_, blob_metadata)), _, _) =
2918 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2919 .context("In unbind_keys_for_user: Trying to load blob info.")?
2920 {
2921 if blob_metadata.encrypted_by().is_none() {
2922 continue;
2923 }
2924 }
2925 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002926 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002927 .context("In unbind_keys_for_user.")?
2928 || notify_gc;
2929 }
2930 Ok(()).do_gc(notify_gc)
2931 })
2932 .context("In unbind_keys_for_user.")
2933 }
2934
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002935 fn load_key_components(
2936 tx: &Transaction,
2937 load_bits: KeyEntryLoadBits,
2938 key_id: i64,
2939 ) -> Result<KeyEntry> {
2940 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2941
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002942 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002943 Self::load_blob_components(key_id, load_bits, &tx)
2944 .context("In load_key_components.")?;
2945
Max Bires8e93d2b2021-01-14 13:17:59 -08002946 let parameters = Self::load_key_parameters(key_id, &tx)
2947 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002948
Max Bires8e93d2b2021-01-14 13:17:59 -08002949 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2950 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002951
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002952 Ok(KeyEntry {
2953 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002954 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002955 cert: cert_blob,
2956 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002957 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002958 parameters,
2959 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002960 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002961 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002962 }
2963
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002964 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2965 /// The key descriptors will have the domain, nspace, and alias field set.
2966 /// Domain must be APP or SELINUX, the caller must make sure of that.
2967 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002968 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2969
Janis Danisevskis66784c42021-01-27 08:40:25 -08002970 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2971 let mut stmt = tx
2972 .prepare(
2973 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002974 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002975 )
2976 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002977
Janis Danisevskis66784c42021-01-27 08:40:25 -08002978 let mut rows = stmt
2979 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2980 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002981
Janis Danisevskis66784c42021-01-27 08:40:25 -08002982 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2983 db_utils::with_rows_extract_all(&mut rows, |row| {
2984 descriptors.push(KeyDescriptor {
2985 domain,
2986 nspace: namespace,
2987 alias: Some(row.get(0).context("Trying to extract alias.")?),
2988 blob: None,
2989 });
2990 Ok(())
2991 })
2992 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002993 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002994 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002995 }
2996
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002997 /// Adds a grant to the grant table.
2998 /// Like `load_key_entry` this function loads the access tuple before
2999 /// it uses the callback for a permission check. Upon success,
3000 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3001 /// grant table. The new row will have a randomized id, which is used as
3002 /// grant id in the namespace field of the resulting KeyDescriptor.
3003 pub fn grant(
3004 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003005 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003006 caller_uid: u32,
3007 grantee_uid: u32,
3008 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003009 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003010 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003011 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3012
Janis Danisevskis66784c42021-01-27 08:40:25 -08003013 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3014 // Load the key_id and complete the access control tuple.
3015 // We ignore the access vector here because grants cannot be granted.
3016 // The access vector returned here expresses the permissions the
3017 // grantee has if key.domain == Domain::GRANT. But this vector
3018 // cannot include the grant permission by design, so there is no way the
3019 // subsequent permission check can pass.
3020 // We could check key.domain == Domain::GRANT and fail early.
3021 // But even if we load the access tuple by grant here, the permission
3022 // check denies the attempt to create a grant by grant descriptor.
3023 let (key_id, access_key_descriptor, _) =
3024 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3025 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003026
Janis Danisevskis66784c42021-01-27 08:40:25 -08003027 // Perform access control. It is vital that we return here if the permission
3028 // was denied. So do not touch that '?' at the end of the line.
3029 // This permission check checks if the caller has the grant permission
3030 // for the given key and in addition to all of the permissions
3031 // expressed in `access_vector`.
3032 check_permission(&access_key_descriptor, &access_vector)
3033 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003034
Janis Danisevskis66784c42021-01-27 08:40:25 -08003035 let grant_id = if let Some(grant_id) = tx
3036 .query_row(
3037 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003038 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003039 params![key_id, grantee_uid],
3040 |row| row.get(0),
3041 )
3042 .optional()
3043 .context("In grant: Failed get optional existing grant id.")?
3044 {
3045 tx.execute(
3046 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003047 SET access_vector = ?
3048 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003049 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003050 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003051 .context("In grant: Failed to update existing grant.")?;
3052 grant_id
3053 } else {
3054 Self::insert_with_retry(|id| {
3055 tx.execute(
3056 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3057 VALUES (?, ?, ?, ?);",
3058 params![id, grantee_uid, key_id, i32::from(access_vector)],
3059 )
3060 })
3061 .context("In grant")?
3062 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003063
Janis Danisevskis66784c42021-01-27 08:40:25 -08003064 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003065 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003066 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003067 }
3068
3069 /// This function checks permissions like `grant` and `load_key_entry`
3070 /// before removing a grant from the grant table.
3071 pub fn ungrant(
3072 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003073 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003074 caller_uid: u32,
3075 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003076 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003077 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003078 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3079
Janis Danisevskis66784c42021-01-27 08:40:25 -08003080 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3081 // Load the key_id and complete the access control tuple.
3082 // We ignore the access vector here because grants cannot be granted.
3083 let (key_id, access_key_descriptor, _) =
3084 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3085 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003086
Janis Danisevskis66784c42021-01-27 08:40:25 -08003087 // Perform access control. We must return here if the permission
3088 // was denied. So do not touch the '?' at the end of this line.
3089 check_permission(&access_key_descriptor)
3090 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003091
Janis Danisevskis66784c42021-01-27 08:40:25 -08003092 tx.execute(
3093 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003094 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 params![key_id, grantee_uid],
3096 )
3097 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003098
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003099 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003100 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101 }
3102
Joel Galenson845f74b2020-09-09 14:11:55 -07003103 // Generates a random id and passes it to the given function, which will
3104 // try to insert it into a database. If that insertion fails, retry;
3105 // otherwise return the id.
3106 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3107 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003108 let newid: i64 = match random() {
3109 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3110 i => i,
3111 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003112 match inserter(newid) {
3113 // If the id already existed, try again.
3114 Err(rusqlite::Error::SqliteFailure(
3115 libsqlite3_sys::Error {
3116 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3117 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3118 },
3119 _,
3120 )) => (),
3121 Err(e) => {
3122 return Err(e).context("In insert_with_retry: failed to insert into database.")
3123 }
3124 _ => return Ok(newid),
3125 }
3126 }
3127 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003128
3129 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
3130 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003131 let _wp = wd::watch_millis("KeystoreDB::insert_auth_token", 500);
3132
Janis Danisevskis66784c42021-01-27 08:40:25 -08003133 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3134 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003135 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
3136 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
3137 params![
3138 auth_token.challenge,
3139 auth_token.userId,
3140 auth_token.authenticatorId,
3141 auth_token.authenticatorType.0 as i32,
3142 auth_token.timestamp.milliSeconds as i64,
3143 auth_token.mac,
3144 MonotonicRawTime::now(),
3145 ],
3146 )
3147 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003148 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003149 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003150 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003151
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003152 /// Find the newest auth token matching the given predicate.
3153 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003154 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003155 p: F,
3156 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
3157 where
3158 F: Fn(&AuthTokenEntry) -> bool,
3159 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003160 let _wp = wd::watch_millis("KeystoreDB::find_auth_token_entry", 500);
3161
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003162 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3163 let mut stmt = tx
3164 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
3165 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003166
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003167 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003168
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003169 while let Some(row) = rows.next().context("Failed to get next row.")? {
3170 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003171 HardwareAuthToken {
3172 challenge: row.get(1)?,
3173 userId: row.get(2)?,
3174 authenticatorId: row.get(3)?,
3175 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3176 timestamp: Timestamp { milliSeconds: row.get(5)? },
3177 mac: row.get(6)?,
3178 },
3179 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003180 );
3181 if p(&entry) {
3182 return Ok(Some((
3183 entry,
3184 Self::get_last_off_body(tx)
3185 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003186 )))
3187 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003188 }
3189 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003190 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003191 })
3192 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003193 }
3194
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003195 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003196 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003197 let _wp = wd::watch_millis("KeystoreDB::insert_last_off_body", 500);
3198
Janis Danisevskis66784c42021-01-27 08:40:25 -08003199 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3200 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003201 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3202 params!["last_off_body", last_off_body],
3203 )
3204 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003205 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003206 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003207 }
3208
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003209 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003210 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003211 let _wp = wd::watch_millis("KeystoreDB::update_last_off_body", 500);
3212
Janis Danisevskis66784c42021-01-27 08:40:25 -08003213 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3214 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003215 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3216 params![last_off_body, "last_off_body"],
3217 )
3218 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003219 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003220 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003221 }
3222
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003223 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003224 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003225 let _wp = wd::watch_millis("KeystoreDB::get_last_off_body", 500);
3226
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003227 tx.query_row(
3228 "SELECT value from perboot.metadata WHERE key = ?;",
3229 params!["last_off_body"],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07003230 |row| row.get(0),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003231 )
3232 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003233 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003234}
3235
3236#[cfg(test)]
3237mod tests {
3238
3239 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003240 use crate::key_parameter::{
3241 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3242 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3243 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003244 use crate::key_perm_set;
3245 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003246 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003247 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003248 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3249 HardwareAuthToken::HardwareAuthToken,
3250 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003251 };
3252 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003253 Timestamp::Timestamp,
3254 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003255 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003256 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003257 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003258 use std::collections::BTreeMap;
3259 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003260 use std::sync::atomic::{AtomicU8, Ordering};
3261 use std::sync::Arc;
3262 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003263 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003264 #[cfg(disabled)]
3265 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003266
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003267 fn new_test_db() -> Result<KeystoreDB> {
3268 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3269
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003270 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003271 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003272 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003273 })?;
3274 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003275 }
3276
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003277 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3278 where
3279 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3280 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003281 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003282
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003283 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003284 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003285
Janis Danisevskis3395f862021-05-06 10:54:17 -07003286 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003287 }
3288
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003289 fn rebind_alias(
3290 db: &mut KeystoreDB,
3291 newid: &KeyIdGuard,
3292 alias: &str,
3293 domain: Domain,
3294 namespace: i64,
3295 ) -> Result<bool> {
3296 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003297 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003298 })
3299 .context("In rebind_alias.")
3300 }
3301
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003302 #[test]
3303 fn datetime() -> Result<()> {
3304 let conn = Connection::open_in_memory()?;
3305 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3306 let now = SystemTime::now();
3307 let duration = Duration::from_secs(1000);
3308 let then = now.checked_sub(duration).unwrap();
3309 let soon = now.checked_add(duration).unwrap();
3310 conn.execute(
3311 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3312 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3313 )?;
3314 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3315 let mut rows = stmt.query(NO_PARAMS)?;
3316 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3317 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3318 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3319 assert!(rows.next()?.is_none());
3320 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3321 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3322 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3323 Ok(())
3324 }
3325
Joel Galenson0891bc12020-07-20 10:37:03 -07003326 // Ensure that we're using the "injected" random function, not the real one.
3327 #[test]
3328 fn test_mocked_random() {
3329 let rand1 = random();
3330 let rand2 = random();
3331 let rand3 = random();
3332 if rand1 == rand2 {
3333 assert_eq!(rand2 + 1, rand3);
3334 } else {
3335 assert_eq!(rand1 + 1, rand2);
3336 assert_eq!(rand2, rand3);
3337 }
3338 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003339
Joel Galenson26f4d012020-07-17 14:57:21 -07003340 // Test that we have the correct tables.
3341 #[test]
3342 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003343 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003344 let tables = db
3345 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003346 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003347 .query_map(params![], |row| row.get(0))?
3348 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003349 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003350 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003351 assert_eq!(tables[1], "blobmetadata");
3352 assert_eq!(tables[2], "grant");
3353 assert_eq!(tables[3], "keyentry");
3354 assert_eq!(tables[4], "keymetadata");
3355 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003356 let tables = db
3357 .conn
3358 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3359 .query_map(params![], |row| row.get(0))?
3360 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003361
3362 assert_eq!(tables.len(), 2);
3363 assert_eq!(tables[0], "authtoken");
3364 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003365 Ok(())
3366 }
3367
3368 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003369 fn test_auth_token_table_invariant() -> Result<()> {
3370 let mut db = new_test_db()?;
3371 let auth_token1 = HardwareAuthToken {
3372 challenge: i64::MAX,
3373 userId: 200,
3374 authenticatorId: 200,
3375 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3376 timestamp: Timestamp { milliSeconds: 500 },
3377 mac: String::from("mac").into_bytes(),
3378 };
3379 db.insert_auth_token(&auth_token1)?;
3380 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3381 assert_eq!(auth_tokens_returned.len(), 1);
3382
3383 // insert another auth token with the same values for the columns in the UNIQUE constraint
3384 // of the auth token table and different value for timestamp
3385 let auth_token2 = HardwareAuthToken {
3386 challenge: i64::MAX,
3387 userId: 200,
3388 authenticatorId: 200,
3389 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3390 timestamp: Timestamp { milliSeconds: 600 },
3391 mac: String::from("mac").into_bytes(),
3392 };
3393
3394 db.insert_auth_token(&auth_token2)?;
3395 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3396 assert_eq!(auth_tokens_returned.len(), 1);
3397
3398 if let Some(auth_token) = auth_tokens_returned.pop() {
3399 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3400 }
3401
3402 // insert another auth token with the different values for the columns in the UNIQUE
3403 // constraint of the auth token table
3404 let auth_token3 = HardwareAuthToken {
3405 challenge: i64::MAX,
3406 userId: 201,
3407 authenticatorId: 200,
3408 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3409 timestamp: Timestamp { milliSeconds: 600 },
3410 mac: String::from("mac").into_bytes(),
3411 };
3412
3413 db.insert_auth_token(&auth_token3)?;
3414 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3415 assert_eq!(auth_tokens_returned.len(), 2);
3416
3417 Ok(())
3418 }
3419
3420 // utility function for test_auth_token_table_invariant()
3421 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3422 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3423
3424 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3425 .query_map(NO_PARAMS, |row| {
3426 Ok(AuthTokenEntry::new(
3427 HardwareAuthToken {
3428 challenge: row.get(1)?,
3429 userId: row.get(2)?,
3430 authenticatorId: row.get(3)?,
3431 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3432 timestamp: Timestamp { milliSeconds: row.get(5)? },
3433 mac: row.get(6)?,
3434 },
3435 row.get(7)?,
3436 ))
3437 })?
3438 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3439 Ok(auth_token_entries)
3440 }
3441
3442 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003443 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003444 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003445 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003446
Janis Danisevskis66784c42021-01-27 08:40:25 -08003447 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003448 let entries = get_keyentry(&db)?;
3449 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003450
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003451 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003452
3453 let entries_new = get_keyentry(&db)?;
3454 assert_eq!(entries, entries_new);
3455 Ok(())
3456 }
3457
3458 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003459 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003460 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3461 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003462 }
3463
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003464 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003465
Janis Danisevskis66784c42021-01-27 08:40:25 -08003466 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3467 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003468
3469 let entries = get_keyentry(&db)?;
3470 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003471 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3472 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003473
3474 // Test that we must pass in a valid Domain.
3475 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003476 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003477 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003478 );
3479 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003480 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003481 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003482 );
3483 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003484 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003485 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003486 );
3487
3488 Ok(())
3489 }
3490
Joel Galenson33c04ad2020-08-03 11:04:38 -07003491 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003492 fn test_add_unsigned_key() -> Result<()> {
3493 let mut db = new_test_db()?;
3494 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3495 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3496 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3497 db.create_attestation_key_entry(
3498 &public_key,
3499 &raw_public_key,
3500 &private_key,
3501 &KEYSTORE_UUID,
3502 )?;
3503 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3504 assert_eq!(keys.len(), 1);
3505 assert_eq!(keys[0], public_key);
3506 Ok(())
3507 }
3508
3509 #[test]
3510 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3511 let mut db = new_test_db()?;
3512 let expiration_date: i64 = 20;
3513 let namespace: i64 = 30;
3514 let base_byte: u8 = 1;
3515 let loaded_values =
3516 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3517 let chain =
3518 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3519 assert_eq!(true, chain.is_some());
3520 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003521 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003522 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3523 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003524 Ok(())
3525 }
3526
3527 #[test]
3528 fn test_get_attestation_pool_status() -> Result<()> {
3529 let mut db = new_test_db()?;
3530 let namespace: i64 = 30;
3531 load_attestation_key_pool(
3532 &mut db, 10, /* expiration */
3533 namespace, 0x01, /* base_byte */
3534 )?;
3535 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3536 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3537 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3538 assert_eq!(status.expiring, 0);
3539 assert_eq!(status.attested, 3);
3540 assert_eq!(status.unassigned, 0);
3541 assert_eq!(status.total, 3);
3542 assert_eq!(
3543 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3544 1
3545 );
3546 assert_eq!(
3547 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3548 2
3549 );
3550 assert_eq!(
3551 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3552 3
3553 );
3554 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3555 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3556 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3557 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003558 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003559 db.create_attestation_key_entry(
3560 &public_key,
3561 &raw_public_key,
3562 &private_key,
3563 &KEYSTORE_UUID,
3564 )?;
3565 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3566 assert_eq!(status.attested, 3);
3567 assert_eq!(status.unassigned, 0);
3568 assert_eq!(status.total, 4);
3569 db.store_signed_attestation_certificate_chain(
3570 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003571 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003572 &cert_chain,
3573 20,
3574 &KEYSTORE_UUID,
3575 )?;
3576 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3577 assert_eq!(status.attested, 4);
3578 assert_eq!(status.unassigned, 1);
3579 assert_eq!(status.total, 4);
3580 Ok(())
3581 }
3582
3583 #[test]
3584 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003585 let temp_dir =
3586 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3587 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003588 let expiration_date: i64 =
3589 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3590 let namespace: i64 = 30;
3591 let namespace_del1: i64 = 45;
3592 let namespace_del2: i64 = 60;
3593 let entry_values = load_attestation_key_pool(
3594 &mut db,
3595 expiration_date,
3596 namespace,
3597 0x01, /* base_byte */
3598 )?;
3599 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3600 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003601
3602 let blob_entry_row_count: u32 = db
3603 .conn
3604 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3605 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003606 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3607 // one key, one certificate chain, and one certificate.
3608 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003609
Max Bires2b2e6562020-09-22 11:22:36 -07003610 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3611
3612 let mut cert_chain =
3613 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003614 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003615 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003616 assert_eq!(entry_values.batch_cert, value.batch_cert);
3617 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003618 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003619
3620 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3621 Domain::APP,
3622 namespace_del1,
3623 &KEYSTORE_UUID,
3624 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003625 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003626 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3627 Domain::APP,
3628 namespace_del2,
3629 &KEYSTORE_UUID,
3630 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003631 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003632
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003633 // Give the garbage collector half a second to catch up.
3634 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003635
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003636 let blob_entry_row_count: u32 = db
3637 .conn
3638 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3639 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003640 // There shound be 3 blob entries left, because we deleted two of the attestation
3641 // key entries with three blobs each.
3642 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003643
Max Bires2b2e6562020-09-22 11:22:36 -07003644 Ok(())
3645 }
3646
3647 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003648 fn test_delete_all_attestation_keys() -> Result<()> {
3649 let mut db = new_test_db()?;
3650 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3651 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3652 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3653 let result = db.delete_all_attestation_keys()?;
3654
3655 // Give the garbage collector half a second to catch up.
3656 std::thread::sleep(Duration::from_millis(500));
3657
3658 // Attestation keys should be deleted, and the regular key should remain.
3659 assert_eq!(result, 2);
3660
3661 Ok(())
3662 }
3663
3664 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003665 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003666 fn extractor(
3667 ke: &KeyEntryRow,
3668 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3669 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003670 }
3671
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003672 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003673 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3674 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003675 let entries = get_keyentry(&db)?;
3676 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003677 assert_eq!(
3678 extractor(&entries[0]),
3679 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3680 );
3681 assert_eq!(
3682 extractor(&entries[1]),
3683 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3684 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003685
3686 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003687 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003688 let entries = get_keyentry(&db)?;
3689 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003690 assert_eq!(
3691 extractor(&entries[0]),
3692 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3693 );
3694 assert_eq!(
3695 extractor(&entries[1]),
3696 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3697 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003698
3699 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003700 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003701 let entries = get_keyentry(&db)?;
3702 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003703 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3704 assert_eq!(
3705 extractor(&entries[1]),
3706 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3707 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003708
3709 // Test that we must pass in a valid Domain.
3710 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003711 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003712 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003713 );
3714 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003715 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003716 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003717 );
3718 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003719 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003720 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003721 );
3722
3723 // Test that we correctly handle setting an alias for something that does not exist.
3724 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003725 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003726 "Expected to update a single entry but instead updated 0",
3727 );
3728 // Test that we correctly abort the transaction in this case.
3729 let entries = get_keyentry(&db)?;
3730 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003731 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3732 assert_eq!(
3733 extractor(&entries[1]),
3734 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3735 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003736
3737 Ok(())
3738 }
3739
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003740 #[test]
3741 fn test_grant_ungrant() -> Result<()> {
3742 const CALLER_UID: u32 = 15;
3743 const GRANTEE_UID: u32 = 12;
3744 const SELINUX_NAMESPACE: i64 = 7;
3745
3746 let mut db = new_test_db()?;
3747 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003748 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3749 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3750 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003751 )?;
3752 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003753 domain: super::Domain::APP,
3754 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755 alias: Some("key".to_string()),
3756 blob: None,
3757 };
3758 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3759 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3760
3761 // Reset totally predictable random number generator in case we
3762 // are not the first test running on this thread.
3763 reset_random();
3764 let next_random = 0i64;
3765
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003766 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003767 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003768 assert_eq!(*a, PVEC1);
3769 assert_eq!(
3770 *k,
3771 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003772 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003773 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003774 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775 alias: Some("key".to_string()),
3776 blob: None,
3777 }
3778 );
3779 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003780 })
3781 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003782
3783 assert_eq!(
3784 app_granted_key,
3785 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003786 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003787 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003788 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003789 alias: None,
3790 blob: None,
3791 }
3792 );
3793
3794 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003795 domain: super::Domain::SELINUX,
3796 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003797 alias: Some("yek".to_string()),
3798 blob: None,
3799 };
3800
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003801 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003802 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003803 assert_eq!(*a, PVEC1);
3804 assert_eq!(
3805 *k,
3806 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003807 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003808 // namespace must be the supplied SELinux
3809 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003810 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003811 alias: Some("yek".to_string()),
3812 blob: None,
3813 }
3814 );
3815 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003816 })
3817 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003818
3819 assert_eq!(
3820 selinux_granted_key,
3821 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003822 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003823 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003824 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003825 alias: None,
3826 blob: None,
3827 }
3828 );
3829
3830 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003831 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003832 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003833 assert_eq!(*a, PVEC2);
3834 assert_eq!(
3835 *k,
3836 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003837 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003838 // namespace must be the supplied SELinux
3839 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003840 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003841 alias: Some("yek".to_string()),
3842 blob: None,
3843 }
3844 );
3845 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003846 })
3847 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003848
3849 assert_eq!(
3850 selinux_granted_key,
3851 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003852 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003853 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003854 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003855 alias: None,
3856 blob: None,
3857 }
3858 );
3859
3860 {
3861 // Limiting scope of stmt, because it borrows db.
3862 let mut stmt = db
3863 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003864 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003865 let mut rows =
3866 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3867 Ok((
3868 row.get(0)?,
3869 row.get(1)?,
3870 row.get(2)?,
3871 KeyPermSet::from(row.get::<_, i32>(3)?),
3872 ))
3873 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003874
3875 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003876 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003877 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003878 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003879 assert!(rows.next().is_none());
3880 }
3881
3882 debug_dump_keyentry_table(&mut db)?;
3883 println!("app_key {:?}", app_key);
3884 println!("selinux_key {:?}", selinux_key);
3885
Janis Danisevskis66784c42021-01-27 08:40:25 -08003886 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3887 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003888
3889 Ok(())
3890 }
3891
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003892 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003893 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3894 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3895
3896 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003897 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003898 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003899 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003900 let mut blob_metadata = BlobMetaData::new();
3901 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3902 db.set_blob(
3903 &key_id,
3904 SubComponentType::KEY_BLOB,
3905 Some(TEST_KEY_BLOB),
3906 Some(&blob_metadata),
3907 )?;
3908 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3909 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003910 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003911
3912 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003913 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003914 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003915 )?;
3916 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003917 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3918 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003919 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003920 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003921 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003922 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003923 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003924 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003925 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003926
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003927 drop(rows);
3928 drop(stmt);
3929
3930 assert_eq!(
3931 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3932 BlobMetaData::load_from_db(id, tx).no_gc()
3933 })
3934 .expect("Should find blob metadata."),
3935 blob_metadata
3936 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003937 Ok(())
3938 }
3939
3940 static TEST_ALIAS: &str = "my super duper key";
3941
3942 #[test]
3943 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3944 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003945 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003946 .context("test_insert_and_load_full_keyentry_domain_app")?
3947 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003948 let (_key_guard, key_entry) = db
3949 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003950 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003951 domain: Domain::APP,
3952 nspace: 0,
3953 alias: Some(TEST_ALIAS.to_string()),
3954 blob: None,
3955 },
3956 KeyType::Client,
3957 KeyEntryLoadBits::BOTH,
3958 1,
3959 |_k, _av| Ok(()),
3960 )
3961 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003962 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003963
3964 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003965 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003966 domain: Domain::APP,
3967 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003968 alias: Some(TEST_ALIAS.to_string()),
3969 blob: None,
3970 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003971 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003972 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003973 |_, _| Ok(()),
3974 )
3975 .unwrap();
3976
3977 assert_eq!(
3978 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3979 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003980 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003981 domain: Domain::APP,
3982 nspace: 0,
3983 alias: Some(TEST_ALIAS.to_string()),
3984 blob: None,
3985 },
3986 KeyType::Client,
3987 KeyEntryLoadBits::NONE,
3988 1,
3989 |_k, _av| Ok(()),
3990 )
3991 .unwrap_err()
3992 .root_cause()
3993 .downcast_ref::<KsError>()
3994 );
3995
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003996 Ok(())
3997 }
3998
3999 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004000 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4001 let mut db = new_test_db()?;
4002
4003 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004004 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004005 domain: Domain::APP,
4006 nspace: 1,
4007 alias: Some(TEST_ALIAS.to_string()),
4008 blob: None,
4009 },
4010 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004011 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004012 )
4013 .expect("Trying to insert cert.");
4014
4015 let (_key_guard, mut key_entry) = db
4016 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004017 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004018 domain: Domain::APP,
4019 nspace: 1,
4020 alias: Some(TEST_ALIAS.to_string()),
4021 blob: None,
4022 },
4023 KeyType::Client,
4024 KeyEntryLoadBits::PUBLIC,
4025 1,
4026 |_k, _av| Ok(()),
4027 )
4028 .expect("Trying to read certificate entry.");
4029
4030 assert!(key_entry.pure_cert());
4031 assert!(key_entry.cert().is_none());
4032 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4033
4034 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004035 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004036 domain: Domain::APP,
4037 nspace: 1,
4038 alias: Some(TEST_ALIAS.to_string()),
4039 blob: None,
4040 },
4041 KeyType::Client,
4042 1,
4043 |_, _| Ok(()),
4044 )
4045 .unwrap();
4046
4047 assert_eq!(
4048 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4049 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004050 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004051 domain: Domain::APP,
4052 nspace: 1,
4053 alias: Some(TEST_ALIAS.to_string()),
4054 blob: None,
4055 },
4056 KeyType::Client,
4057 KeyEntryLoadBits::NONE,
4058 1,
4059 |_k, _av| Ok(()),
4060 )
4061 .unwrap_err()
4062 .root_cause()
4063 .downcast_ref::<KsError>()
4064 );
4065
4066 Ok(())
4067 }
4068
4069 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004070 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4071 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004072 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004073 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4074 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004075 let (_key_guard, key_entry) = db
4076 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004077 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004078 domain: Domain::SELINUX,
4079 nspace: 1,
4080 alias: Some(TEST_ALIAS.to_string()),
4081 blob: None,
4082 },
4083 KeyType::Client,
4084 KeyEntryLoadBits::BOTH,
4085 1,
4086 |_k, _av| Ok(()),
4087 )
4088 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004089 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004090
4091 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004092 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004093 domain: Domain::SELINUX,
4094 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004095 alias: Some(TEST_ALIAS.to_string()),
4096 blob: None,
4097 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004098 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004099 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004100 |_, _| Ok(()),
4101 )
4102 .unwrap();
4103
4104 assert_eq!(
4105 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4106 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004107 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004108 domain: Domain::SELINUX,
4109 nspace: 1,
4110 alias: Some(TEST_ALIAS.to_string()),
4111 blob: None,
4112 },
4113 KeyType::Client,
4114 KeyEntryLoadBits::NONE,
4115 1,
4116 |_k, _av| Ok(()),
4117 )
4118 .unwrap_err()
4119 .root_cause()
4120 .downcast_ref::<KsError>()
4121 );
4122
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004123 Ok(())
4124 }
4125
4126 #[test]
4127 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4128 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004129 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004130 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4131 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004132 let (_, key_entry) = db
4133 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004134 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004135 KeyType::Client,
4136 KeyEntryLoadBits::BOTH,
4137 1,
4138 |_k, _av| Ok(()),
4139 )
4140 .unwrap();
4141
Qi Wub9433b52020-12-01 14:52:46 +08004142 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004143
4144 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004145 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004146 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004147 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004148 |_, _| Ok(()),
4149 )
4150 .unwrap();
4151
4152 assert_eq!(
4153 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4154 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004155 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004156 KeyType::Client,
4157 KeyEntryLoadBits::NONE,
4158 1,
4159 |_k, _av| Ok(()),
4160 )
4161 .unwrap_err()
4162 .root_cause()
4163 .downcast_ref::<KsError>()
4164 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004165
4166 Ok(())
4167 }
4168
4169 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004170 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4171 let mut db = new_test_db()?;
4172 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4173 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4174 .0;
4175 // Update the usage count of the limited use key.
4176 db.check_and_update_key_usage_count(key_id)?;
4177
4178 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004179 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004180 KeyType::Client,
4181 KeyEntryLoadBits::BOTH,
4182 1,
4183 |_k, _av| Ok(()),
4184 )?;
4185
4186 // The usage count is decremented now.
4187 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4188
4189 Ok(())
4190 }
4191
4192 #[test]
4193 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4194 let mut db = new_test_db()?;
4195 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4196 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4197 .0;
4198 // Update the usage count of the limited use key.
4199 db.check_and_update_key_usage_count(key_id).expect(concat!(
4200 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4201 "This should succeed."
4202 ));
4203
4204 // Try to update the exhausted limited use key.
4205 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4206 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4207 "This should fail."
4208 ));
4209 assert_eq!(
4210 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4211 e.root_cause().downcast_ref::<KsError>().unwrap()
4212 );
4213
4214 Ok(())
4215 }
4216
4217 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004218 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4219 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004220 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004221 .context("test_insert_and_load_full_keyentry_from_grant")?
4222 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004223
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004224 let granted_key = db
4225 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004226 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004227 domain: Domain::APP,
4228 nspace: 0,
4229 alias: Some(TEST_ALIAS.to_string()),
4230 blob: None,
4231 },
4232 1,
4233 2,
4234 key_perm_set![KeyPerm::use_()],
4235 |_k, _av| Ok(()),
4236 )
4237 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004238
4239 debug_dump_grant_table(&mut db)?;
4240
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004241 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004242 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4243 assert_eq!(Domain::GRANT, k.domain);
4244 assert!(av.unwrap().includes(KeyPerm::use_()));
4245 Ok(())
4246 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004247 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004248
Qi Wub9433b52020-12-01 14:52:46 +08004249 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004250
Janis Danisevskis66784c42021-01-27 08:40:25 -08004251 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004252
4253 assert_eq!(
4254 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4255 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004256 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004257 KeyType::Client,
4258 KeyEntryLoadBits::NONE,
4259 2,
4260 |_k, _av| Ok(()),
4261 )
4262 .unwrap_err()
4263 .root_cause()
4264 .downcast_ref::<KsError>()
4265 );
4266
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004267 Ok(())
4268 }
4269
Janis Danisevskis45760022021-01-19 16:34:10 -08004270 // This test attempts to load a key by key id while the caller is not the owner
4271 // but a grant exists for the given key and the caller.
4272 #[test]
4273 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4274 let mut db = new_test_db()?;
4275 const OWNER_UID: u32 = 1u32;
4276 const GRANTEE_UID: u32 = 2u32;
4277 const SOMEONE_ELSE_UID: u32 = 3u32;
4278 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4279 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4280 .0;
4281
4282 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004283 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004284 domain: Domain::APP,
4285 nspace: 0,
4286 alias: Some(TEST_ALIAS.to_string()),
4287 blob: None,
4288 },
4289 OWNER_UID,
4290 GRANTEE_UID,
4291 key_perm_set![KeyPerm::use_()],
4292 |_k, _av| Ok(()),
4293 )
4294 .unwrap();
4295
4296 debug_dump_grant_table(&mut db)?;
4297
4298 let id_descriptor =
4299 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4300
4301 let (_, key_entry) = db
4302 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004303 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004304 KeyType::Client,
4305 KeyEntryLoadBits::BOTH,
4306 GRANTEE_UID,
4307 |k, av| {
4308 assert_eq!(Domain::APP, k.domain);
4309 assert_eq!(OWNER_UID as i64, k.nspace);
4310 assert!(av.unwrap().includes(KeyPerm::use_()));
4311 Ok(())
4312 },
4313 )
4314 .unwrap();
4315
4316 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4317
4318 let (_, key_entry) = db
4319 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004320 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004321 KeyType::Client,
4322 KeyEntryLoadBits::BOTH,
4323 SOMEONE_ELSE_UID,
4324 |k, av| {
4325 assert_eq!(Domain::APP, k.domain);
4326 assert_eq!(OWNER_UID as i64, k.nspace);
4327 assert!(av.is_none());
4328 Ok(())
4329 },
4330 )
4331 .unwrap();
4332
4333 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4334
Janis Danisevskis66784c42021-01-27 08:40:25 -08004335 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004336
4337 assert_eq!(
4338 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4339 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004340 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004341 KeyType::Client,
4342 KeyEntryLoadBits::NONE,
4343 GRANTEE_UID,
4344 |_k, _av| Ok(()),
4345 )
4346 .unwrap_err()
4347 .root_cause()
4348 .downcast_ref::<KsError>()
4349 );
4350
4351 Ok(())
4352 }
4353
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004354 // Creates a key migrates it to a different location and then tries to access it by the old
4355 // and new location.
4356 #[test]
4357 fn test_migrate_key_app_to_app() -> Result<()> {
4358 let mut db = new_test_db()?;
4359 const SOURCE_UID: u32 = 1u32;
4360 const DESTINATION_UID: u32 = 2u32;
4361 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4362 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4363 let key_id_guard =
4364 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4365 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4366
4367 let source_descriptor: KeyDescriptor = KeyDescriptor {
4368 domain: Domain::APP,
4369 nspace: -1,
4370 alias: Some(SOURCE_ALIAS.to_string()),
4371 blob: None,
4372 };
4373
4374 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4375 domain: Domain::APP,
4376 nspace: -1,
4377 alias: Some(DESTINATION_ALIAS.to_string()),
4378 blob: None,
4379 };
4380
4381 let key_id = key_id_guard.id();
4382
4383 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4384 Ok(())
4385 })
4386 .unwrap();
4387
4388 let (_, key_entry) = db
4389 .load_key_entry(
4390 &destination_descriptor,
4391 KeyType::Client,
4392 KeyEntryLoadBits::BOTH,
4393 DESTINATION_UID,
4394 |k, av| {
4395 assert_eq!(Domain::APP, k.domain);
4396 assert_eq!(DESTINATION_UID as i64, k.nspace);
4397 assert!(av.is_none());
4398 Ok(())
4399 },
4400 )
4401 .unwrap();
4402
4403 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4404
4405 assert_eq!(
4406 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4407 db.load_key_entry(
4408 &source_descriptor,
4409 KeyType::Client,
4410 KeyEntryLoadBits::NONE,
4411 SOURCE_UID,
4412 |_k, _av| Ok(()),
4413 )
4414 .unwrap_err()
4415 .root_cause()
4416 .downcast_ref::<KsError>()
4417 );
4418
4419 Ok(())
4420 }
4421
4422 // Creates a key migrates it to a different location and then tries to access it by the old
4423 // and new location.
4424 #[test]
4425 fn test_migrate_key_app_to_selinux() -> Result<()> {
4426 let mut db = new_test_db()?;
4427 const SOURCE_UID: u32 = 1u32;
4428 const DESTINATION_UID: u32 = 2u32;
4429 const DESTINATION_NAMESPACE: i64 = 1000i64;
4430 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4431 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4432 let key_id_guard =
4433 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4434 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4435
4436 let source_descriptor: KeyDescriptor = KeyDescriptor {
4437 domain: Domain::APP,
4438 nspace: -1,
4439 alias: Some(SOURCE_ALIAS.to_string()),
4440 blob: None,
4441 };
4442
4443 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4444 domain: Domain::SELINUX,
4445 nspace: DESTINATION_NAMESPACE,
4446 alias: Some(DESTINATION_ALIAS.to_string()),
4447 blob: None,
4448 };
4449
4450 let key_id = key_id_guard.id();
4451
4452 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4453 Ok(())
4454 })
4455 .unwrap();
4456
4457 let (_, key_entry) = db
4458 .load_key_entry(
4459 &destination_descriptor,
4460 KeyType::Client,
4461 KeyEntryLoadBits::BOTH,
4462 DESTINATION_UID,
4463 |k, av| {
4464 assert_eq!(Domain::SELINUX, k.domain);
4465 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4466 assert!(av.is_none());
4467 Ok(())
4468 },
4469 )
4470 .unwrap();
4471
4472 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4473
4474 assert_eq!(
4475 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4476 db.load_key_entry(
4477 &source_descriptor,
4478 KeyType::Client,
4479 KeyEntryLoadBits::NONE,
4480 SOURCE_UID,
4481 |_k, _av| Ok(()),
4482 )
4483 .unwrap_err()
4484 .root_cause()
4485 .downcast_ref::<KsError>()
4486 );
4487
4488 Ok(())
4489 }
4490
4491 // Creates two keys and tries to migrate the first to the location of the second which
4492 // is expected to fail.
4493 #[test]
4494 fn test_migrate_key_destination_occupied() -> Result<()> {
4495 let mut db = new_test_db()?;
4496 const SOURCE_UID: u32 = 1u32;
4497 const DESTINATION_UID: u32 = 2u32;
4498 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4499 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4500 let key_id_guard =
4501 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4502 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4503 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4504 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4505
4506 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4507 domain: Domain::APP,
4508 nspace: -1,
4509 alias: Some(DESTINATION_ALIAS.to_string()),
4510 blob: None,
4511 };
4512
4513 assert_eq!(
4514 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4515 db.migrate_key_namespace(
4516 key_id_guard,
4517 &destination_descriptor,
4518 DESTINATION_UID,
4519 |_k| Ok(())
4520 )
4521 .unwrap_err()
4522 .root_cause()
4523 .downcast_ref::<KsError>()
4524 );
4525
4526 Ok(())
4527 }
4528
Janis Danisevskisaec14592020-11-12 09:41:49 -08004529 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4530
Janis Danisevskisaec14592020-11-12 09:41:49 -08004531 #[test]
4532 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4533 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004534 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4535 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004536 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004537 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004538 .context("test_insert_and_load_full_keyentry_domain_app")?
4539 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004540 let (_key_guard, key_entry) = db
4541 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004542 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004543 domain: Domain::APP,
4544 nspace: 0,
4545 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4546 blob: None,
4547 },
4548 KeyType::Client,
4549 KeyEntryLoadBits::BOTH,
4550 33,
4551 |_k, _av| Ok(()),
4552 )
4553 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004554 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004555 let state = Arc::new(AtomicU8::new(1));
4556 let state2 = state.clone();
4557
4558 // Spawning a second thread that attempts to acquire the key id lock
4559 // for the same key as the primary thread. The primary thread then
4560 // waits, thereby forcing the secondary thread into the second stage
4561 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4562 // The test succeeds if the secondary thread observes the transition
4563 // of `state` from 1 to 2, despite having a whole second to overtake
4564 // the primary thread.
4565 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004566 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004567 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004568 assert!(db
4569 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004570 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004571 domain: Domain::APP,
4572 nspace: 0,
4573 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4574 blob: None,
4575 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004576 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004577 KeyEntryLoadBits::BOTH,
4578 33,
4579 |_k, _av| Ok(()),
4580 )
4581 .is_ok());
4582 // We should only see a 2 here because we can only return
4583 // from load_key_entry when the `_key_guard` expires,
4584 // which happens at the end of the scope.
4585 assert_eq!(2, state2.load(Ordering::Relaxed));
4586 });
4587
4588 thread::sleep(std::time::Duration::from_millis(1000));
4589
4590 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4591
4592 // Return the handle from this scope so we can join with the
4593 // secondary thread after the key id lock has expired.
4594 handle
4595 // This is where the `_key_guard` goes out of scope,
4596 // which is the reason for concurrent load_key_entry on the same key
4597 // to unblock.
4598 };
4599 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4600 // main test thread. We will not see failing asserts in secondary threads otherwise.
4601 handle.join().unwrap();
4602 Ok(())
4603 }
4604
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004605 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004606 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004607 let temp_dir =
4608 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4609
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004610 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4611 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004612
4613 let _tx1 = db1
4614 .conn
4615 .transaction_with_behavior(TransactionBehavior::Immediate)
4616 .expect("Failed to create first transaction.");
4617
4618 let error = db2
4619 .conn
4620 .transaction_with_behavior(TransactionBehavior::Immediate)
4621 .context("Transaction begin failed.")
4622 .expect_err("This should fail.");
4623 let root_cause = error.root_cause();
4624 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4625 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4626 {
4627 return;
4628 }
4629 panic!(
4630 "Unexpected error {:?} \n{:?} \n{:?}",
4631 error,
4632 root_cause,
4633 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4634 )
4635 }
4636
4637 #[cfg(disabled)]
4638 #[test]
4639 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4640 let temp_dir = Arc::new(
4641 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4642 .expect("Failed to create temp dir."),
4643 );
4644
4645 let test_begin = Instant::now();
4646
4647 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4648 const KEY_COUNT: u32 = 500u32;
4649 const OPEN_DB_COUNT: u32 = 50u32;
4650
4651 let mut actual_key_count = KEY_COUNT;
4652 // First insert KEY_COUNT keys.
4653 for count in 0..KEY_COUNT {
4654 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4655 actual_key_count = count;
4656 break;
4657 }
4658 let alias = format!("test_alias_{}", count);
4659 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4660 .expect("Failed to make key entry.");
4661 }
4662
4663 // Insert more keys from a different thread and into a different namespace.
4664 let temp_dir1 = temp_dir.clone();
4665 let handle1 = thread::spawn(move || {
4666 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4667
4668 for count in 0..actual_key_count {
4669 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4670 return;
4671 }
4672 let alias = format!("test_alias_{}", count);
4673 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4674 .expect("Failed to make key entry.");
4675 }
4676
4677 // then unbind them again.
4678 for count in 0..actual_key_count {
4679 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4680 return;
4681 }
4682 let key = KeyDescriptor {
4683 domain: Domain::APP,
4684 nspace: -1,
4685 alias: Some(format!("test_alias_{}", count)),
4686 blob: None,
4687 };
4688 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4689 }
4690 });
4691
4692 // And start unbinding the first set of keys.
4693 let temp_dir2 = temp_dir.clone();
4694 let handle2 = thread::spawn(move || {
4695 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4696
4697 for count in 0..actual_key_count {
4698 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4699 return;
4700 }
4701 let key = KeyDescriptor {
4702 domain: Domain::APP,
4703 nspace: -1,
4704 alias: Some(format!("test_alias_{}", count)),
4705 blob: None,
4706 };
4707 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4708 }
4709 });
4710
4711 let stop_deleting = Arc::new(AtomicU8::new(0));
4712 let stop_deleting2 = stop_deleting.clone();
4713
4714 // And delete anything that is unreferenced keys.
4715 let temp_dir3 = temp_dir.clone();
4716 let handle3 = thread::spawn(move || {
4717 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4718
4719 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4720 while let Some((key_guard, _key)) =
4721 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4722 {
4723 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4724 return;
4725 }
4726 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4727 }
4728 std::thread::sleep(std::time::Duration::from_millis(100));
4729 }
4730 });
4731
4732 // While a lot of inserting and deleting is going on we have to open database connections
4733 // successfully and use them.
4734 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4735 // out of scope.
4736 #[allow(clippy::redundant_clone)]
4737 let temp_dir4 = temp_dir.clone();
4738 let handle4 = thread::spawn(move || {
4739 for count in 0..OPEN_DB_COUNT {
4740 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4741 return;
4742 }
4743 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4744
4745 let alias = format!("test_alias_{}", count);
4746 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4747 .expect("Failed to make key entry.");
4748 let key = KeyDescriptor {
4749 domain: Domain::APP,
4750 nspace: -1,
4751 alias: Some(alias),
4752 blob: None,
4753 };
4754 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4755 }
4756 });
4757
4758 handle1.join().expect("Thread 1 panicked.");
4759 handle2.join().expect("Thread 2 panicked.");
4760 handle4.join().expect("Thread 4 panicked.");
4761
4762 stop_deleting.store(1, Ordering::Relaxed);
4763 handle3.join().expect("Thread 3 panicked.");
4764
4765 Ok(())
4766 }
4767
4768 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004769 fn list() -> Result<()> {
4770 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004771 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004772 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4773 (Domain::APP, 1, "test1"),
4774 (Domain::APP, 1, "test2"),
4775 (Domain::APP, 1, "test3"),
4776 (Domain::APP, 1, "test4"),
4777 (Domain::APP, 1, "test5"),
4778 (Domain::APP, 1, "test6"),
4779 (Domain::APP, 1, "test7"),
4780 (Domain::APP, 2, "test1"),
4781 (Domain::APP, 2, "test2"),
4782 (Domain::APP, 2, "test3"),
4783 (Domain::APP, 2, "test4"),
4784 (Domain::APP, 2, "test5"),
4785 (Domain::APP, 2, "test6"),
4786 (Domain::APP, 2, "test8"),
4787 (Domain::SELINUX, 100, "test1"),
4788 (Domain::SELINUX, 100, "test2"),
4789 (Domain::SELINUX, 100, "test3"),
4790 (Domain::SELINUX, 100, "test4"),
4791 (Domain::SELINUX, 100, "test5"),
4792 (Domain::SELINUX, 100, "test6"),
4793 (Domain::SELINUX, 100, "test9"),
4794 ];
4795
4796 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4797 .iter()
4798 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004799 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4800 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004801 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4802 });
4803 (entry.id(), *ns)
4804 })
4805 .collect();
4806
4807 for (domain, namespace) in
4808 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4809 {
4810 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4811 .iter()
4812 .filter_map(|(domain, ns, alias)| match ns {
4813 ns if *ns == *namespace => Some(KeyDescriptor {
4814 domain: *domain,
4815 nspace: *ns,
4816 alias: Some(alias.to_string()),
4817 blob: None,
4818 }),
4819 _ => None,
4820 })
4821 .collect();
4822 list_o_descriptors.sort();
4823 let mut list_result = db.list(*domain, *namespace)?;
4824 list_result.sort();
4825 assert_eq!(list_o_descriptors, list_result);
4826
4827 let mut list_o_ids: Vec<i64> = list_o_descriptors
4828 .into_iter()
4829 .map(|d| {
4830 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004831 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004832 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004833 KeyType::Client,
4834 KeyEntryLoadBits::NONE,
4835 *namespace as u32,
4836 |_, _| Ok(()),
4837 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004838 .unwrap();
4839 entry.id()
4840 })
4841 .collect();
4842 list_o_ids.sort_unstable();
4843 let mut loaded_entries: Vec<i64> = list_o_keys
4844 .iter()
4845 .filter_map(|(id, ns)| match ns {
4846 ns if *ns == *namespace => Some(*id),
4847 _ => None,
4848 })
4849 .collect();
4850 loaded_entries.sort_unstable();
4851 assert_eq!(list_o_ids, loaded_entries);
4852 }
4853 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4854
4855 Ok(())
4856 }
4857
Joel Galenson0891bc12020-07-20 10:37:03 -07004858 // Helpers
4859
4860 // Checks that the given result is an error containing the given string.
4861 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4862 let error_str = format!(
4863 "{:#?}",
4864 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4865 );
4866 assert!(
4867 error_str.contains(target),
4868 "The string \"{}\" should contain \"{}\"",
4869 error_str,
4870 target
4871 );
4872 }
4873
Joel Galenson2aab4432020-07-22 15:27:57 -07004874 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004875 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004876 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004877 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004878 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004879 namespace: Option<i64>,
4880 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004881 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004882 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004883 }
4884
4885 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4886 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004887 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004888 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004889 Ok(KeyEntryRow {
4890 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004891 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004892 domain: match row.get(2)? {
4893 Some(i) => Some(Domain(i)),
4894 None => None,
4895 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004896 namespace: row.get(3)?,
4897 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004898 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004899 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004900 })
4901 })?
4902 .map(|r| r.context("Could not read keyentry row."))
4903 .collect::<Result<Vec<_>>>()
4904 }
4905
Max Biresb2e1d032021-02-08 21:35:05 -08004906 struct RemoteProvValues {
4907 cert_chain: Vec<u8>,
4908 priv_key: Vec<u8>,
4909 batch_cert: Vec<u8>,
4910 }
4911
Max Bires2b2e6562020-09-22 11:22:36 -07004912 fn load_attestation_key_pool(
4913 db: &mut KeystoreDB,
4914 expiration_date: i64,
4915 namespace: i64,
4916 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004917 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004918 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4919 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4920 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4921 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004922 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004923 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4924 db.store_signed_attestation_certificate_chain(
4925 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004926 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004927 &cert_chain,
4928 expiration_date,
4929 &KEYSTORE_UUID,
4930 )?;
4931 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004932 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004933 }
4934
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004935 // Note: The parameters and SecurityLevel associations are nonsensical. This
4936 // collection is only used to check if the parameters are preserved as expected by the
4937 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004938 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4939 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004940 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4941 KeyParameter::new(
4942 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4943 SecurityLevel::TRUSTED_ENVIRONMENT,
4944 ),
4945 KeyParameter::new(
4946 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4947 SecurityLevel::TRUSTED_ENVIRONMENT,
4948 ),
4949 KeyParameter::new(
4950 KeyParameterValue::Algorithm(Algorithm::RSA),
4951 SecurityLevel::TRUSTED_ENVIRONMENT,
4952 ),
4953 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4954 KeyParameter::new(
4955 KeyParameterValue::BlockMode(BlockMode::ECB),
4956 SecurityLevel::TRUSTED_ENVIRONMENT,
4957 ),
4958 KeyParameter::new(
4959 KeyParameterValue::BlockMode(BlockMode::GCM),
4960 SecurityLevel::TRUSTED_ENVIRONMENT,
4961 ),
4962 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4963 KeyParameter::new(
4964 KeyParameterValue::Digest(Digest::MD5),
4965 SecurityLevel::TRUSTED_ENVIRONMENT,
4966 ),
4967 KeyParameter::new(
4968 KeyParameterValue::Digest(Digest::SHA_2_224),
4969 SecurityLevel::TRUSTED_ENVIRONMENT,
4970 ),
4971 KeyParameter::new(
4972 KeyParameterValue::Digest(Digest::SHA_2_256),
4973 SecurityLevel::STRONGBOX,
4974 ),
4975 KeyParameter::new(
4976 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4977 SecurityLevel::TRUSTED_ENVIRONMENT,
4978 ),
4979 KeyParameter::new(
4980 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4981 SecurityLevel::TRUSTED_ENVIRONMENT,
4982 ),
4983 KeyParameter::new(
4984 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4985 SecurityLevel::STRONGBOX,
4986 ),
4987 KeyParameter::new(
4988 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4989 SecurityLevel::TRUSTED_ENVIRONMENT,
4990 ),
4991 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4992 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4993 KeyParameter::new(
4994 KeyParameterValue::EcCurve(EcCurve::P_224),
4995 SecurityLevel::TRUSTED_ENVIRONMENT,
4996 ),
4997 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4998 KeyParameter::new(
4999 KeyParameterValue::EcCurve(EcCurve::P_384),
5000 SecurityLevel::TRUSTED_ENVIRONMENT,
5001 ),
5002 KeyParameter::new(
5003 KeyParameterValue::EcCurve(EcCurve::P_521),
5004 SecurityLevel::TRUSTED_ENVIRONMENT,
5005 ),
5006 KeyParameter::new(
5007 KeyParameterValue::RSAPublicExponent(3),
5008 SecurityLevel::TRUSTED_ENVIRONMENT,
5009 ),
5010 KeyParameter::new(
5011 KeyParameterValue::IncludeUniqueID,
5012 SecurityLevel::TRUSTED_ENVIRONMENT,
5013 ),
5014 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5015 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5016 KeyParameter::new(
5017 KeyParameterValue::ActiveDateTime(1234567890),
5018 SecurityLevel::STRONGBOX,
5019 ),
5020 KeyParameter::new(
5021 KeyParameterValue::OriginationExpireDateTime(1234567890),
5022 SecurityLevel::TRUSTED_ENVIRONMENT,
5023 ),
5024 KeyParameter::new(
5025 KeyParameterValue::UsageExpireDateTime(1234567890),
5026 SecurityLevel::TRUSTED_ENVIRONMENT,
5027 ),
5028 KeyParameter::new(
5029 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5030 SecurityLevel::TRUSTED_ENVIRONMENT,
5031 ),
5032 KeyParameter::new(
5033 KeyParameterValue::MaxUsesPerBoot(1234567890),
5034 SecurityLevel::TRUSTED_ENVIRONMENT,
5035 ),
5036 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5037 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5038 KeyParameter::new(
5039 KeyParameterValue::NoAuthRequired,
5040 SecurityLevel::TRUSTED_ENVIRONMENT,
5041 ),
5042 KeyParameter::new(
5043 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5044 SecurityLevel::TRUSTED_ENVIRONMENT,
5045 ),
5046 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5047 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5048 KeyParameter::new(
5049 KeyParameterValue::TrustedUserPresenceRequired,
5050 SecurityLevel::TRUSTED_ENVIRONMENT,
5051 ),
5052 KeyParameter::new(
5053 KeyParameterValue::TrustedConfirmationRequired,
5054 SecurityLevel::TRUSTED_ENVIRONMENT,
5055 ),
5056 KeyParameter::new(
5057 KeyParameterValue::UnlockedDeviceRequired,
5058 SecurityLevel::TRUSTED_ENVIRONMENT,
5059 ),
5060 KeyParameter::new(
5061 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5062 SecurityLevel::SOFTWARE,
5063 ),
5064 KeyParameter::new(
5065 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5066 SecurityLevel::SOFTWARE,
5067 ),
5068 KeyParameter::new(
5069 KeyParameterValue::CreationDateTime(12345677890),
5070 SecurityLevel::SOFTWARE,
5071 ),
5072 KeyParameter::new(
5073 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5074 SecurityLevel::TRUSTED_ENVIRONMENT,
5075 ),
5076 KeyParameter::new(
5077 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5078 SecurityLevel::TRUSTED_ENVIRONMENT,
5079 ),
5080 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5081 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5082 KeyParameter::new(
5083 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5084 SecurityLevel::SOFTWARE,
5085 ),
5086 KeyParameter::new(
5087 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5088 SecurityLevel::TRUSTED_ENVIRONMENT,
5089 ),
5090 KeyParameter::new(
5091 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5092 SecurityLevel::TRUSTED_ENVIRONMENT,
5093 ),
5094 KeyParameter::new(
5095 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5096 SecurityLevel::TRUSTED_ENVIRONMENT,
5097 ),
5098 KeyParameter::new(
5099 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5100 SecurityLevel::TRUSTED_ENVIRONMENT,
5101 ),
5102 KeyParameter::new(
5103 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5104 SecurityLevel::TRUSTED_ENVIRONMENT,
5105 ),
5106 KeyParameter::new(
5107 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5108 SecurityLevel::TRUSTED_ENVIRONMENT,
5109 ),
5110 KeyParameter::new(
5111 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5112 SecurityLevel::TRUSTED_ENVIRONMENT,
5113 ),
5114 KeyParameter::new(
5115 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5116 SecurityLevel::TRUSTED_ENVIRONMENT,
5117 ),
5118 KeyParameter::new(
5119 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5120 SecurityLevel::TRUSTED_ENVIRONMENT,
5121 ),
5122 KeyParameter::new(
5123 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5124 SecurityLevel::TRUSTED_ENVIRONMENT,
5125 ),
5126 KeyParameter::new(
5127 KeyParameterValue::VendorPatchLevel(3),
5128 SecurityLevel::TRUSTED_ENVIRONMENT,
5129 ),
5130 KeyParameter::new(
5131 KeyParameterValue::BootPatchLevel(4),
5132 SecurityLevel::TRUSTED_ENVIRONMENT,
5133 ),
5134 KeyParameter::new(
5135 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5136 SecurityLevel::TRUSTED_ENVIRONMENT,
5137 ),
5138 KeyParameter::new(
5139 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5140 SecurityLevel::TRUSTED_ENVIRONMENT,
5141 ),
5142 KeyParameter::new(
5143 KeyParameterValue::MacLength(256),
5144 SecurityLevel::TRUSTED_ENVIRONMENT,
5145 ),
5146 KeyParameter::new(
5147 KeyParameterValue::ResetSinceIdRotation,
5148 SecurityLevel::TRUSTED_ENVIRONMENT,
5149 ),
5150 KeyParameter::new(
5151 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5152 SecurityLevel::TRUSTED_ENVIRONMENT,
5153 ),
Qi Wub9433b52020-12-01 14:52:46 +08005154 ];
5155 if let Some(value) = max_usage_count {
5156 params.push(KeyParameter::new(
5157 KeyParameterValue::UsageCountLimit(value),
5158 SecurityLevel::SOFTWARE,
5159 ));
5160 }
5161 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005162 }
5163
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005164 fn make_test_key_entry(
5165 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005166 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005167 namespace: i64,
5168 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005169 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005170 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005171 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005172 let mut blob_metadata = BlobMetaData::new();
5173 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5174 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5175 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5176 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5177 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5178
5179 db.set_blob(
5180 &key_id,
5181 SubComponentType::KEY_BLOB,
5182 Some(TEST_KEY_BLOB),
5183 Some(&blob_metadata),
5184 )?;
5185 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5186 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005187
5188 let params = make_test_params(max_usage_count);
5189 db.insert_keyparameter(&key_id, &params)?;
5190
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005191 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005192 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005193 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005194 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005195 Ok(key_id)
5196 }
5197
Qi Wub9433b52020-12-01 14:52:46 +08005198 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5199 let params = make_test_params(max_usage_count);
5200
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005201 let mut blob_metadata = BlobMetaData::new();
5202 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5203 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5204 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5205 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5206 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5207
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005208 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005209 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005210
5211 KeyEntry {
5212 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005213 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005214 cert: Some(TEST_CERT_BLOB.to_vec()),
5215 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005216 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005217 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005218 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005219 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005220 }
5221 }
5222
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005223 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005224 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005225 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005226 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005227 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005228 NO_PARAMS,
5229 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005230 Ok((
5231 row.get(0)?,
5232 row.get(1)?,
5233 row.get(2)?,
5234 row.get(3)?,
5235 row.get(4)?,
5236 row.get(5)?,
5237 row.get(6)?,
5238 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005239 },
5240 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005241
5242 println!("Key entry table rows:");
5243 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005244 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005245 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005246 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5247 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005248 );
5249 }
5250 Ok(())
5251 }
5252
5253 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005254 let mut stmt = db
5255 .conn
5256 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005257 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5258 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5259 })?;
5260
5261 println!("Grant table rows:");
5262 for r in rows {
5263 let (id, gt, ki, av) = r.unwrap();
5264 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5265 }
5266 Ok(())
5267 }
5268
Joel Galenson0891bc12020-07-20 10:37:03 -07005269 // Use a custom random number generator that repeats each number once.
5270 // This allows us to test repeated elements.
5271
5272 thread_local! {
5273 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5274 }
5275
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005276 fn reset_random() {
5277 RANDOM_COUNTER.with(|counter| {
5278 *counter.borrow_mut() = 0;
5279 })
5280 }
5281
Joel Galenson0891bc12020-07-20 10:37:03 -07005282 pub fn random() -> i64 {
5283 RANDOM_COUNTER.with(|counter| {
5284 let result = *counter.borrow() / 2;
5285 *counter.borrow_mut() += 1;
5286 result
5287 })
5288 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005289
5290 #[test]
5291 fn test_last_off_body() -> Result<()> {
5292 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005293 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005294 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5295 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5296 tx.commit()?;
5297 let one_second = Duration::from_secs(1);
5298 thread::sleep(one_second);
5299 db.update_last_off_body(MonotonicRawTime::now())?;
5300 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5301 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5302 tx2.commit()?;
5303 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5304 Ok(())
5305 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005306
5307 #[test]
5308 fn test_unbind_keys_for_user() -> Result<()> {
5309 let mut db = new_test_db()?;
5310 db.unbind_keys_for_user(1, false)?;
5311
5312 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5313 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5314 db.unbind_keys_for_user(2, false)?;
5315
5316 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5317 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5318
5319 db.unbind_keys_for_user(1, true)?;
5320 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5321
5322 Ok(())
5323 }
5324
5325 #[test]
5326 fn test_store_super_key() -> Result<()> {
5327 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005328 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005329 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005330 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005331 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005332 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005333
5334 let (encrypted_super_key, metadata) =
5335 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005336 db.store_super_key(
5337 1,
5338 &USER_SUPER_KEY,
5339 &encrypted_super_key,
5340 &metadata,
5341 &KeyMetaData::new(),
5342 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005343
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005344 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005345 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005346
Paul Crowley7a658392021-03-18 17:08:20 -07005347 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005348 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5349 USER_SUPER_KEY.algorithm,
5350 key_entry,
5351 &pw,
5352 None,
5353 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005354
Paul Crowley7a658392021-03-18 17:08:20 -07005355 let decrypted_secret_bytes =
5356 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5357 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005358 Ok(())
5359 }
Seth Moore78c091f2021-04-09 21:38:30 +00005360
5361 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5362 vec![
5363 StatsdStorageType::KeyEntry,
5364 StatsdStorageType::KeyEntryIdIndex,
5365 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5366 StatsdStorageType::BlobEntry,
5367 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5368 StatsdStorageType::KeyParameter,
5369 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5370 StatsdStorageType::KeyMetadata,
5371 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5372 StatsdStorageType::Grant,
5373 StatsdStorageType::AuthToken,
5374 StatsdStorageType::BlobMetadata,
5375 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5376 ]
5377 }
5378
5379 /// Perform a simple check to ensure that we can query all the storage types
5380 /// that are supported by the DB. Check for reasonable values.
5381 #[test]
5382 fn test_query_all_valid_table_sizes() -> Result<()> {
5383 const PAGE_SIZE: i64 = 4096;
5384
5385 let mut db = new_test_db()?;
5386
5387 for t in get_valid_statsd_storage_types() {
5388 let stat = db.get_storage_stat(t)?;
5389 assert!(stat.size >= PAGE_SIZE);
5390 assert!(stat.size >= stat.unused_size);
5391 }
5392
5393 Ok(())
5394 }
5395
5396 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5397 get_valid_statsd_storage_types()
5398 .into_iter()
5399 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5400 .collect()
5401 }
5402
5403 fn assert_storage_increased(
5404 db: &mut KeystoreDB,
5405 increased_storage_types: Vec<StatsdStorageType>,
5406 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5407 ) {
5408 for storage in increased_storage_types {
5409 // Verify the expected storage increased.
5410 let new = db.get_storage_stat(storage).unwrap();
5411 let storage = storage as i32;
5412 let old = &baseline[&storage];
5413 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5414 assert!(
5415 new.unused_size <= old.unused_size,
5416 "{}: {} <= {}",
5417 storage,
5418 new.unused_size,
5419 old.unused_size
5420 );
5421
5422 // Update the baseline with the new value so that it succeeds in the
5423 // later comparison.
5424 baseline.insert(storage, new);
5425 }
5426
5427 // Get an updated map of the storage and verify there were no unexpected changes.
5428 let updated_stats = get_storage_stats_map(db);
5429 assert_eq!(updated_stats.len(), baseline.len());
5430
5431 for &k in baseline.keys() {
5432 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5433 let mut s = String::new();
5434 for &k in map.keys() {
5435 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5436 .expect("string concat failed");
5437 }
5438 s
5439 };
5440
5441 assert!(
5442 updated_stats[&k].size == baseline[&k].size
5443 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5444 "updated_stats:\n{}\nbaseline:\n{}",
5445 stringify(&updated_stats),
5446 stringify(&baseline)
5447 );
5448 }
5449 }
5450
5451 #[test]
5452 fn test_verify_key_table_size_reporting() -> Result<()> {
5453 let mut db = new_test_db()?;
5454 let mut working_stats = get_storage_stats_map(&mut db);
5455
5456 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5457 assert_storage_increased(
5458 &mut db,
5459 vec![
5460 StatsdStorageType::KeyEntry,
5461 StatsdStorageType::KeyEntryIdIndex,
5462 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5463 ],
5464 &mut working_stats,
5465 );
5466
5467 let mut blob_metadata = BlobMetaData::new();
5468 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5469 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5470 assert_storage_increased(
5471 &mut db,
5472 vec![
5473 StatsdStorageType::BlobEntry,
5474 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5475 StatsdStorageType::BlobMetadata,
5476 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5477 ],
5478 &mut working_stats,
5479 );
5480
5481 let params = make_test_params(None);
5482 db.insert_keyparameter(&key_id, &params)?;
5483 assert_storage_increased(
5484 &mut db,
5485 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5486 &mut working_stats,
5487 );
5488
5489 let mut metadata = KeyMetaData::new();
5490 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5491 db.insert_key_metadata(&key_id, &metadata)?;
5492 assert_storage_increased(
5493 &mut db,
5494 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5495 &mut working_stats,
5496 );
5497
5498 let mut sum = 0;
5499 for stat in working_stats.values() {
5500 sum += stat.size;
5501 }
5502 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5503 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5504
5505 Ok(())
5506 }
5507
5508 #[test]
5509 fn test_verify_auth_table_size_reporting() -> Result<()> {
5510 let mut db = new_test_db()?;
5511 let mut working_stats = get_storage_stats_map(&mut db);
5512 db.insert_auth_token(&HardwareAuthToken {
5513 challenge: 123,
5514 userId: 456,
5515 authenticatorId: 789,
5516 authenticatorType: kmhw_authenticator_type::ANY,
5517 timestamp: Timestamp { milliSeconds: 10 },
5518 mac: b"mac".to_vec(),
5519 })?;
5520 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5521 Ok(())
5522 }
5523
5524 #[test]
5525 fn test_verify_grant_table_size_reporting() -> Result<()> {
5526 const OWNER: i64 = 1;
5527 let mut db = new_test_db()?;
5528 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5529
5530 let mut working_stats = get_storage_stats_map(&mut db);
5531 db.grant(
5532 &KeyDescriptor {
5533 domain: Domain::APP,
5534 nspace: 0,
5535 alias: Some(TEST_ALIAS.to_string()),
5536 blob: None,
5537 },
5538 OWNER as u32,
5539 123,
5540 key_perm_set![KeyPerm::use_()],
5541 |_, _| Ok(()),
5542 )?;
5543
5544 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5545
5546 Ok(())
5547 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005548}