blob: 7a8eca355a43e5505e168469721b89ae581e42dc [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Janis Danisevskisb42fc182020-12-15 08:41:27 -080044use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080045use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070046use crate::permission::KeyPermSet;
Janis Danisevskis850d4862021-05-05 08:41:14 -070047use crate::utils::{get_current_time_in_seconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080048use crate::{
49 db_utils::{self, SqlField},
50 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070051 super_key::USER_SUPER_KEY,
52};
53use crate::{
54 error::{Error as KsError, ErrorCode, ResponseCode},
55 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080056};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080057use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080058use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070059
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000060use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080061 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000062 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080063};
64use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000065 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000066};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070067use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070068 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070069};
Max Bires2b2e6562020-09-22 11:22:36 -070070use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
71 AttestationPoolStatus::AttestationPoolStatus,
72};
Seth Moore78c091f2021-04-09 21:38:30 +000073use statslog_rust::keystore2_storage_stats::{
74 Keystore2StorageStats, StorageType as StatsdStorageType,
75};
Max Bires2b2e6562020-09-22 11:22:36 -070076
77use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080078use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000079use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070080#[cfg(not(test))]
81use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070082use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080083 params,
84 types::FromSql,
85 types::FromSqlResult,
86 types::ToSqlOutput,
87 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080088 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070089};
Max Bires2b2e6562020-09-22 11:22:36 -070090
Janis Danisevskisaec14592020-11-12 09:41:49 -080091use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080093 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070094 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080095 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080096};
Max Bires2b2e6562020-09-22 11:22:36 -070097
Joel Galenson0891bc12020-07-20 10:37:03 -070098#[cfg(test)]
99use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -0700100
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800101impl_metadata!(
102 /// A set of metadata for key entries.
103 #[derive(Debug, Default, Eq, PartialEq)]
104 pub struct KeyMetaData;
105 /// A metadata entry for key entries.
106 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
107 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800108 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800109 CreationDate(DateTime) with accessor creation_date,
110 /// Expiration date for attestation keys.
111 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700112 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
113 /// provisioning
114 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
115 /// Vector representing the raw public key so results from the server can be matched
116 /// to the right entry
117 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700118 /// SEC1 public key for ECDH encryption
119 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800120 // --- ADD NEW META DATA FIELDS HERE ---
121 // For backwards compatibility add new entries only to
122 // end of this list and above this comment.
123 };
124);
125
126impl KeyMetaData {
127 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
128 let mut stmt = tx
129 .prepare(
130 "SELECT tag, data from persistent.keymetadata
131 WHERE keyentryid = ?;",
132 )
133 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
134
135 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
136
137 let mut rows =
138 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
139 db_utils::with_rows_extract_all(&mut rows, |row| {
140 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
141 metadata.insert(
142 db_tag,
143 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
144 .context("Failed to read KeyMetaEntry.")?,
145 );
146 Ok(())
147 })
148 .context("In KeyMetaData::load_from_db.")?;
149
150 Ok(Self { data: metadata })
151 }
152
153 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
154 let mut stmt = tx
155 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000156 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800157 VALUES (?, ?, ?);",
158 )
159 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
160
161 let iter = self.data.iter();
162 for (tag, entry) in iter {
163 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
164 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
165 })?;
166 }
167 Ok(())
168 }
169}
170
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800171impl_metadata!(
172 /// A set of metadata for key blobs.
173 #[derive(Debug, Default, Eq, PartialEq)]
174 pub struct BlobMetaData;
175 /// A metadata entry for key blobs.
176 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
177 pub enum BlobMetaEntry {
178 /// If present, indicates that the blob is encrypted with another key or a key derived
179 /// from a password.
180 EncryptedBy(EncryptedBy) with accessor encrypted_by,
181 /// If the blob is password encrypted this field is set to the
182 /// salt used for the key derivation.
183 Salt(Vec<u8>) with accessor salt,
184 /// If the blob is encrypted, this field is set to the initialization vector.
185 Iv(Vec<u8>) with accessor iv,
186 /// If the blob is encrypted, this field holds the AEAD TAG.
187 AeadTag(Vec<u8>) with accessor aead_tag,
188 /// The uuid of the owning KeyMint instance.
189 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700190 /// If the key is ECDH encrypted, this is the ephemeral public key
191 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000192 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
193 /// of that key
194 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800195 // --- ADD NEW META DATA FIELDS HERE ---
196 // For backwards compatibility add new entries only to
197 // end of this list and above this comment.
198 };
199);
200
201impl BlobMetaData {
202 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
203 let mut stmt = tx
204 .prepare(
205 "SELECT tag, data from persistent.blobmetadata
206 WHERE blobentryid = ?;",
207 )
208 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
209
210 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
211
212 let mut rows =
213 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
214 db_utils::with_rows_extract_all(&mut rows, |row| {
215 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
216 metadata.insert(
217 db_tag,
218 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
219 .context("Failed to read BlobMetaEntry.")?,
220 );
221 Ok(())
222 })
223 .context("In BlobMetaData::load_from_db.")?;
224
225 Ok(Self { data: metadata })
226 }
227
228 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
229 let mut stmt = tx
230 .prepare(
231 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
232 VALUES (?, ?, ?);",
233 )
234 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
235
236 let iter = self.data.iter();
237 for (tag, entry) in iter {
238 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
239 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
240 })?;
241 }
242 Ok(())
243 }
244}
245
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800246/// Indicates the type of the keyentry.
247#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
248pub enum KeyType {
249 /// This is a client key type. These keys are created or imported through the Keystore 2.0
250 /// AIDL interface android.system.keystore2.
251 Client,
252 /// This is a super key type. These keys are created by keystore itself and used to encrypt
253 /// other key blobs to provide LSKF binding.
254 Super,
255 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
256 Attestation,
257}
258
259impl ToSql for KeyType {
260 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
261 Ok(ToSqlOutput::Owned(Value::Integer(match self {
262 KeyType::Client => 0,
263 KeyType::Super => 1,
264 KeyType::Attestation => 2,
265 })))
266 }
267}
268
269impl FromSql for KeyType {
270 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
271 match i64::column_result(value)? {
272 0 => Ok(KeyType::Client),
273 1 => Ok(KeyType::Super),
274 2 => Ok(KeyType::Attestation),
275 v => Err(FromSqlError::OutOfRange(v)),
276 }
277 }
278}
279
Max Bires8e93d2b2021-01-14 13:17:59 -0800280/// Uuid representation that can be stored in the database.
281/// Right now it can only be initialized from SecurityLevel.
282/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
283#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
284pub struct Uuid([u8; 16]);
285
286impl Deref for Uuid {
287 type Target = [u8; 16];
288
289 fn deref(&self) -> &Self::Target {
290 &self.0
291 }
292}
293
294impl From<SecurityLevel> for Uuid {
295 fn from(sec_level: SecurityLevel) -> Self {
296 Self((sec_level.0 as u128).to_be_bytes())
297 }
298}
299
300impl ToSql for Uuid {
301 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
302 self.0.to_sql()
303 }
304}
305
306impl FromSql for Uuid {
307 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
308 let blob = Vec::<u8>::column_result(value)?;
309 if blob.len() != 16 {
310 return Err(FromSqlError::OutOfRange(blob.len() as i64));
311 }
312 let mut arr = [0u8; 16];
313 arr.copy_from_slice(&blob);
314 Ok(Self(arr))
315 }
316}
317
318/// Key entries that are not associated with any KeyMint instance, such as pure certificate
319/// entries are associated with this UUID.
320pub static KEYSTORE_UUID: Uuid = Uuid([
321 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
322]);
323
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800324/// Indicates how the sensitive part of this key blob is encrypted.
325#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
326pub enum EncryptedBy {
327 /// The keyblob is encrypted by a user password.
328 /// In the database this variant is represented as NULL.
329 Password,
330 /// The keyblob is encrypted by another key with wrapped key id.
331 /// In the database this variant is represented as non NULL value
332 /// that is convertible to i64, typically NUMERIC.
333 KeyId(i64),
334}
335
336impl ToSql for EncryptedBy {
337 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
338 match self {
339 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
340 Self::KeyId(id) => id.to_sql(),
341 }
342 }
343}
344
345impl FromSql for EncryptedBy {
346 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
347 match value {
348 ValueRef::Null => Ok(Self::Password),
349 _ => Ok(Self::KeyId(i64::column_result(value)?)),
350 }
351 }
352}
353
354/// A database representation of wall clock time. DateTime stores unix epoch time as
355/// i64 in milliseconds.
356#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
357pub struct DateTime(i64);
358
359/// Error type returned when creating DateTime or converting it from and to
360/// SystemTime.
361#[derive(thiserror::Error, Debug)]
362pub enum DateTimeError {
363 /// This is returned when SystemTime and Duration computations fail.
364 #[error(transparent)]
365 SystemTimeError(#[from] SystemTimeError),
366
367 /// This is returned when type conversions fail.
368 #[error(transparent)]
369 TypeConversion(#[from] std::num::TryFromIntError),
370
371 /// This is returned when checked time arithmetic failed.
372 #[error("Time arithmetic failed.")]
373 TimeArithmetic,
374}
375
376impl DateTime {
377 /// Constructs a new DateTime object denoting the current time. This may fail during
378 /// conversion to unix epoch time and during conversion to the internal i64 representation.
379 pub fn now() -> Result<Self, DateTimeError> {
380 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
381 }
382
383 /// Constructs a new DateTime object from milliseconds.
384 pub fn from_millis_epoch(millis: i64) -> Self {
385 Self(millis)
386 }
387
388 /// Returns unix epoch time in milliseconds.
389 pub fn to_millis_epoch(&self) -> i64 {
390 self.0
391 }
392
393 /// Returns unix epoch time in seconds.
394 pub fn to_secs_epoch(&self) -> i64 {
395 self.0 / 1000
396 }
397}
398
399impl ToSql for DateTime {
400 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
401 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
402 }
403}
404
405impl FromSql for DateTime {
406 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
407 Ok(Self(i64::column_result(value)?))
408 }
409}
410
411impl TryInto<SystemTime> for DateTime {
412 type Error = DateTimeError;
413
414 fn try_into(self) -> Result<SystemTime, Self::Error> {
415 // We want to construct a SystemTime representation equivalent to self, denoting
416 // a point in time THEN, but we cannot set the time directly. We can only construct
417 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
418 // and between EPOCH and THEN. With this common reference we can construct the
419 // duration between NOW and THEN which we can add to our SystemTime representation
420 // of NOW to get a SystemTime representation of THEN.
421 // Durations can only be positive, thus the if statement below.
422 let now = SystemTime::now();
423 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
424 let then_epoch = Duration::from_millis(self.0.try_into()?);
425 Ok(if now_epoch > then_epoch {
426 // then = now - (now_epoch - then_epoch)
427 now_epoch
428 .checked_sub(then_epoch)
429 .and_then(|d| now.checked_sub(d))
430 .ok_or(DateTimeError::TimeArithmetic)?
431 } else {
432 // then = now + (then_epoch - now_epoch)
433 then_epoch
434 .checked_sub(now_epoch)
435 .and_then(|d| now.checked_add(d))
436 .ok_or(DateTimeError::TimeArithmetic)?
437 })
438 }
439}
440
441impl TryFrom<SystemTime> for DateTime {
442 type Error = DateTimeError;
443
444 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
445 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
446 }
447}
448
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800449#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
450enum KeyLifeCycle {
451 /// Existing keys have a key ID but are not fully populated yet.
452 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
453 /// them to Unreferenced for garbage collection.
454 Existing,
455 /// A live key is fully populated and usable by clients.
456 Live,
457 /// An unreferenced key is scheduled for garbage collection.
458 Unreferenced,
459}
460
461impl ToSql for KeyLifeCycle {
462 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
463 match self {
464 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
465 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
466 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
467 }
468 }
469}
470
471impl FromSql for KeyLifeCycle {
472 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
473 match i64::column_result(value)? {
474 0 => Ok(KeyLifeCycle::Existing),
475 1 => Ok(KeyLifeCycle::Live),
476 2 => Ok(KeyLifeCycle::Unreferenced),
477 v => Err(FromSqlError::OutOfRange(v)),
478 }
479 }
480}
481
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700482/// Keys have a KeyMint blob component and optional public certificate and
483/// certificate chain components.
484/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
485/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800486#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700487pub struct KeyEntryLoadBits(u32);
488
489impl KeyEntryLoadBits {
490 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
491 pub const NONE: KeyEntryLoadBits = Self(0);
492 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
493 pub const KM: KeyEntryLoadBits = Self(1);
494 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
495 pub const PUBLIC: KeyEntryLoadBits = Self(2);
496 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
497 pub const BOTH: KeyEntryLoadBits = Self(3);
498
499 /// Returns true if this object indicates that the public components shall be loaded.
500 pub const fn load_public(&self) -> bool {
501 self.0 & Self::PUBLIC.0 != 0
502 }
503
504 /// Returns true if the object indicates that the KeyMint component shall be loaded.
505 pub const fn load_km(&self) -> bool {
506 self.0 & Self::KM.0 != 0
507 }
508}
509
Janis Danisevskisaec14592020-11-12 09:41:49 -0800510lazy_static! {
511 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
512}
513
514struct KeyIdLockDb {
515 locked_keys: Mutex<HashSet<i64>>,
516 cond_var: Condvar,
517}
518
519/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
520/// from the database a second time. Most functions manipulating the key blob database
521/// require a KeyIdGuard.
522#[derive(Debug)]
523pub struct KeyIdGuard(i64);
524
525impl KeyIdLockDb {
526 fn new() -> Self {
527 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
528 }
529
530 /// This function blocks until an exclusive lock for the given key entry id can
531 /// be acquired. It returns a guard object, that represents the lifecycle of the
532 /// acquired lock.
533 pub fn get(&self, key_id: i64) -> KeyIdGuard {
534 let mut locked_keys = self.locked_keys.lock().unwrap();
535 while locked_keys.contains(&key_id) {
536 locked_keys = self.cond_var.wait(locked_keys).unwrap();
537 }
538 locked_keys.insert(key_id);
539 KeyIdGuard(key_id)
540 }
541
542 /// This function attempts to acquire an exclusive lock on a given key id. If the
543 /// given key id is already taken the function returns None immediately. If a lock
544 /// can be acquired this function returns a guard object, that represents the
545 /// lifecycle of the acquired lock.
546 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
547 let mut locked_keys = self.locked_keys.lock().unwrap();
548 if locked_keys.insert(key_id) {
549 Some(KeyIdGuard(key_id))
550 } else {
551 None
552 }
553 }
554}
555
556impl KeyIdGuard {
557 /// Get the numeric key id of the locked key.
558 pub fn id(&self) -> i64 {
559 self.0
560 }
561}
562
563impl Drop for KeyIdGuard {
564 fn drop(&mut self) {
565 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
566 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800567 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800568 KEY_ID_LOCK.cond_var.notify_all();
569 }
570}
571
Max Bires8e93d2b2021-01-14 13:17:59 -0800572/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700573#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800574pub struct CertificateInfo {
575 cert: Option<Vec<u8>>,
576 cert_chain: Option<Vec<u8>>,
577}
578
579impl CertificateInfo {
580 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
581 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
582 Self { cert, cert_chain }
583 }
584
585 /// Take the cert
586 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
587 self.cert.take()
588 }
589
590 /// Take the cert chain
591 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
592 self.cert_chain.take()
593 }
594}
595
Max Bires2b2e6562020-09-22 11:22:36 -0700596/// This type represents a certificate chain with a private key corresponding to the leaf
597/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
Max Bires2b2e6562020-09-22 11:22:36 -0700598pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800599 /// A KM key blob
600 pub private_key: ZVec,
601 /// A batch cert for private_key
602 pub batch_cert: Vec<u8>,
603 /// A full certificate chain from root signing authority to private_key, including batch_cert
604 /// for convenience.
605 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700606}
607
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700608/// This type represents a Keystore 2.0 key entry.
609/// An entry has a unique `id` by which it can be found in the database.
610/// It has a security level field, key parameters, and three optional fields
611/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800612#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700613pub struct KeyEntry {
614 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800615 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700616 cert: Option<Vec<u8>>,
617 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800618 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700619 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800620 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800621 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700622}
623
624impl KeyEntry {
625 /// Returns the unique id of the Key entry.
626 pub fn id(&self) -> i64 {
627 self.id
628 }
629 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800630 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
631 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700632 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800633 /// Extracts the Optional KeyMint blob including its metadata.
634 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
635 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700636 }
637 /// Exposes the optional public certificate.
638 pub fn cert(&self) -> &Option<Vec<u8>> {
639 &self.cert
640 }
641 /// Extracts the optional public certificate.
642 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
643 self.cert.take()
644 }
645 /// Exposes the optional public certificate chain.
646 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
647 &self.cert_chain
648 }
649 /// Extracts the optional public certificate_chain.
650 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
651 self.cert_chain.take()
652 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800653 /// Returns the uuid of the owning KeyMint instance.
654 pub fn km_uuid(&self) -> &Uuid {
655 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700656 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700657 /// Exposes the key parameters of this key entry.
658 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
659 &self.parameters
660 }
661 /// Consumes this key entry and extracts the keyparameters from it.
662 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
663 self.parameters
664 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800665 /// Exposes the key metadata of this key entry.
666 pub fn metadata(&self) -> &KeyMetaData {
667 &self.metadata
668 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800669 /// This returns true if the entry is a pure certificate entry with no
670 /// private key component.
671 pub fn pure_cert(&self) -> bool {
672 self.pure_cert
673 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000674 /// Consumes this key entry and extracts the keyparameters and metadata from it.
675 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
676 (self.parameters, self.metadata)
677 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700678}
679
680/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800681#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700682pub struct SubComponentType(u32);
683impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800684 /// Persistent identifier for a key blob.
685 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700686 /// Persistent identifier for a certificate blob.
687 pub const CERT: SubComponentType = Self(1);
688 /// Persistent identifier for a certificate chain blob.
689 pub const CERT_CHAIN: SubComponentType = Self(2);
690}
691
692impl ToSql for SubComponentType {
693 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
694 self.0.to_sql()
695 }
696}
697
698impl FromSql for SubComponentType {
699 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
700 Ok(Self(u32::column_result(value)?))
701 }
702}
703
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800704/// This trait is private to the database module. It is used to convey whether or not the garbage
705/// collector shall be invoked after a database access. All closures passed to
706/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
707/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
708/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
709/// `.need_gc()`.
710trait DoGc<T> {
711 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
712
713 fn no_gc(self) -> Result<(bool, T)>;
714
715 fn need_gc(self) -> Result<(bool, T)>;
716}
717
718impl<T> DoGc<T> for Result<T> {
719 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
720 self.map(|r| (need_gc, r))
721 }
722
723 fn no_gc(self) -> Result<(bool, T)> {
724 self.do_gc(false)
725 }
726
727 fn need_gc(self) -> Result<(bool, T)> {
728 self.do_gc(true)
729 }
730}
731
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700732/// KeystoreDB wraps a connection to an SQLite database and tracks its
733/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700734pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700735 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700736 gc: Option<Arc<Gc>>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700737}
738
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000739/// Database representation of the monotonic time retrieved from the system call clock_gettime with
740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
741#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
742pub struct MonotonicRawTime(i64);
743
744impl MonotonicRawTime {
745 /// Constructs a new MonotonicRawTime
746 pub fn now() -> Self {
747 Self(get_current_time_in_seconds())
748 }
749
David Drysdale0e45a612021-02-25 17:24:36 +0000750 /// Constructs a new MonotonicRawTime from a given number of seconds.
751 pub fn from_secs(val: i64) -> Self {
752 Self(val)
753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
757 self.0
758 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800759
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000760 /// Returns the value of MonotonicRawTime in milli seconds as i64
761 pub fn milli_seconds(&self) -> i64 {
762 self.0 * 1000
763 }
764
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800765 /// Like i64::checked_sub.
766 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
767 self.0.checked_sub(other.0).map(Self)
768 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000769}
770
771impl ToSql for MonotonicRawTime {
772 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
773 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
774 }
775}
776
777impl FromSql for MonotonicRawTime {
778 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
779 Ok(Self(i64::column_result(value)?))
780 }
781}
782
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000783/// This struct encapsulates the information to be stored in the database about the auth tokens
784/// received by keystore.
785pub struct AuthTokenEntry {
786 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000787 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000788}
789
790impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000791 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000792 AuthTokenEntry { auth_token, time_received }
793 }
794
795 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800796 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
799 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 })
801 }
802
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000803 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800804 pub fn auth_token(&self) -> &HardwareAuthToken {
805 &self.auth_token
806 }
807
808 /// Returns the auth token wrapped by the AuthTokenEntry
809 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000810 self.auth_token
811 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800812
813 /// Returns the time that this auth token was received.
814 pub fn time_received(&self) -> MonotonicRawTime {
815 self.time_received
816 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000817
818 /// Returns the challenge value of the auth token.
819 pub fn challenge(&self) -> i64 {
820 self.auth_token.challenge
821 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822}
823
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800824/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
825/// This object does not allow access to the database connection. But it keeps a database
826/// connection alive in order to keep the in memory per boot database alive.
827pub struct PerBootDbKeepAlive(Connection);
828
Joel Galenson26f4d012020-07-17 14:57:21 -0700829impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800830 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800831 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
832
Seth Moore78c091f2021-04-09 21:38:30 +0000833 /// Name of the file that holds the cross-boot persistent database.
834 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
835
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800836 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
837 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
838 let conn = Connection::open_in_memory()
839 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
840
841 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
842 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
843 Ok(PerBootDbKeepAlive(conn))
844 }
845
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700846 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800847 /// files persistent.sqlite and perboot.sqlite in the given directory.
848 /// It also attempts to initialize all of the tables.
849 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700850 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700851 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700852 let _wp = wd::watch_millis("KeystoreDB::new", 500);
853
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800855 let mut persistent_path = db_root.to_path_buf();
Seth Moore78c091f2021-04-09 21:38:30 +0000856 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700857
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800858 // Now convert them to strings prefixed with "file:"
859 let mut persistent_path_str = "file:".to_owned();
860 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800861
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800862 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800863
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
865 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
866
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800867 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800868 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800869 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 })?;
871 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700872 }
873
Janis Danisevskis66784c42021-01-27 08:40:25 -0800874 fn init_tables(tx: &Transaction) -> Result<()> {
875 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700876 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700877 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800878 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700879 domain INTEGER,
880 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800881 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800882 state INTEGER,
883 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700884 NO_PARAMS,
885 )
886 .context("Failed to initialize \"keyentry\" table.")?;
887
Janis Danisevskis66784c42021-01-27 08:40:25 -0800888 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800889 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
890 ON keyentry(id);",
891 NO_PARAMS,
892 )
893 .context("Failed to create index keyentry_id_index.")?;
894
895 tx.execute(
896 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
897 ON keyentry(domain, namespace, alias);",
898 NO_PARAMS,
899 )
900 .context("Failed to create index keyentry_domain_namespace_index.")?;
901
902 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700903 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
904 id INTEGER PRIMARY KEY,
905 subcomponent_type INTEGER,
906 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800907 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700908 NO_PARAMS,
909 )
910 .context("Failed to initialize \"blobentry\" table.")?;
911
Janis Danisevskis66784c42021-01-27 08:40:25 -0800912 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800913 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
914 ON blobentry(keyentryid);",
915 NO_PARAMS,
916 )
917 .context("Failed to create index blobentry_keyentryid_index.")?;
918
919 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800920 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
921 id INTEGER PRIMARY KEY,
922 blobentryid INTEGER,
923 tag INTEGER,
924 data ANY,
925 UNIQUE (blobentryid, tag));",
926 NO_PARAMS,
927 )
928 .context("Failed to initialize \"blobmetadata\" table.")?;
929
930 tx.execute(
931 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
932 ON blobmetadata(blobentryid);",
933 NO_PARAMS,
934 )
935 .context("Failed to create index blobmetadata_blobentryid_index.")?;
936
937 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700938 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000939 keyentryid INTEGER,
940 tag INTEGER,
941 data ANY,
942 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700943 NO_PARAMS,
944 )
945 .context("Failed to initialize \"keyparameter\" table.")?;
946
Janis Danisevskis66784c42021-01-27 08:40:25 -0800947 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800948 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
949 ON keyparameter(keyentryid);",
950 NO_PARAMS,
951 )
952 .context("Failed to create index keyparameter_keyentryid_index.")?;
953
954 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800955 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
956 keyentryid INTEGER,
957 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000958 data ANY,
959 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800960 NO_PARAMS,
961 )
962 .context("Failed to initialize \"keymetadata\" table.")?;
963
Janis Danisevskis66784c42021-01-27 08:40:25 -0800964 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800965 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
966 ON keymetadata(keyentryid);",
967 NO_PARAMS,
968 )
969 .context("Failed to create index keymetadata_keyentryid_index.")?;
970
971 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800972 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700973 id INTEGER UNIQUE,
974 grantee INTEGER,
975 keyentryid INTEGER,
976 access_vector INTEGER);",
977 NO_PARAMS,
978 )
979 .context("Failed to initialize \"grant\" table.")?;
980
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000981 //TODO: only drop the following two perboot tables if this is the first start up
982 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800983 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000984 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800985 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000986 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
987 id INTEGER PRIMARY KEY,
988 challenge INTEGER,
989 user_id INTEGER,
990 auth_id INTEGER,
991 authenticator_type INTEGER,
992 timestamp INTEGER,
993 mac BLOB,
994 time_received INTEGER,
995 UNIQUE(user_id, auth_id, authenticator_type));",
996 NO_PARAMS,
997 )
998 .context("Failed to initialize \"authtoken\" table.")?;
999
Janis Danisevskis66784c42021-01-27 08:40:25 -08001000 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001001 // .context("Failed to drop perboot.metadata table")?;
1002 // metadata table stores certain miscellaneous information required for keystore functioning
1003 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001004 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001005 "CREATE TABLE IF NOT EXISTS perboot.metadata (
1006 key TEXT,
1007 value BLOB,
1008 UNIQUE(key));",
1009 NO_PARAMS,
1010 )
1011 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -07001012 Ok(())
1013 }
1014
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001015 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
1016 let conn =
1017 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1018
Janis Danisevskis66784c42021-01-27 08:40:25 -08001019 loop {
1020 if let Err(e) = conn
1021 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1022 .context("Failed to attach database persistent.")
1023 {
1024 if Self::is_locked_error(&e) {
1025 std::thread::sleep(std::time::Duration::from_micros(500));
1026 continue;
1027 } else {
1028 return Err(e);
1029 }
1030 }
1031 break;
1032 }
1033 loop {
1034 if let Err(e) = conn
1035 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1036 .context("Failed to attach database perboot.")
1037 {
1038 if Self::is_locked_error(&e) {
1039 std::thread::sleep(std::time::Duration::from_micros(500));
1040 continue;
1041 } else {
1042 return Err(e);
1043 }
1044 }
1045 break;
1046 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047
1048 Ok(conn)
1049 }
1050
Seth Moore78c091f2021-04-09 21:38:30 +00001051 fn do_table_size_query(
1052 &mut self,
1053 storage_type: StatsdStorageType,
1054 query: &str,
1055 params: &[&str],
1056 ) -> Result<Keystore2StorageStats> {
1057 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1058 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1059 .with_context(|| {
1060 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1061 })
1062 .no_gc()
1063 })?;
1064 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1065 }
1066
1067 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1068 self.do_table_size_query(
1069 StatsdStorageType::Database,
1070 "SELECT page_count * page_size, freelist_count * page_size
1071 FROM pragma_page_count('persistent'),
1072 pragma_page_size('persistent'),
1073 persistent.pragma_freelist_count();",
1074 &[],
1075 )
1076 }
1077
1078 fn get_table_size(
1079 &mut self,
1080 storage_type: StatsdStorageType,
1081 schema: &str,
1082 table: &str,
1083 ) -> Result<Keystore2StorageStats> {
1084 self.do_table_size_query(
1085 storage_type,
1086 "SELECT pgsize,unused FROM dbstat(?1)
1087 WHERE name=?2 AND aggregate=TRUE;",
1088 &[schema, table],
1089 )
1090 }
1091
1092 /// Fetches a storage statisitics atom for a given storage type. For storage
1093 /// types that map to a table, information about the table's storage is
1094 /// returned. Requests for storage types that are not DB tables return None.
1095 pub fn get_storage_stat(
1096 &mut self,
1097 storage_type: StatsdStorageType,
1098 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001099 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1100
Seth Moore78c091f2021-04-09 21:38:30 +00001101 match storage_type {
1102 StatsdStorageType::Database => self.get_total_size(),
1103 StatsdStorageType::KeyEntry => {
1104 self.get_table_size(storage_type, "persistent", "keyentry")
1105 }
1106 StatsdStorageType::KeyEntryIdIndex => {
1107 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1108 }
1109 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1110 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1111 }
1112 StatsdStorageType::BlobEntry => {
1113 self.get_table_size(storage_type, "persistent", "blobentry")
1114 }
1115 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1116 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1117 }
1118 StatsdStorageType::KeyParameter => {
1119 self.get_table_size(storage_type, "persistent", "keyparameter")
1120 }
1121 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1122 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1123 }
1124 StatsdStorageType::KeyMetadata => {
1125 self.get_table_size(storage_type, "persistent", "keymetadata")
1126 }
1127 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1128 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1129 }
1130 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1131 StatsdStorageType::AuthToken => {
1132 self.get_table_size(storage_type, "perboot", "authtoken")
1133 }
1134 StatsdStorageType::BlobMetadata => {
1135 self.get_table_size(storage_type, "persistent", "blobmetadata")
1136 }
1137 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1138 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1139 }
1140 _ => Err(anyhow::Error::msg(format!(
1141 "Unsupported storage type: {}",
1142 storage_type as i32
1143 ))),
1144 }
1145 }
1146
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001147 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001148 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1149 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001150 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1151 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001152 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 blob_ids_to_delete: &[i64],
1155 max_blobs: usize,
1156 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001157 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001158 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001159 // Delete the given blobs.
1160 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161 tx.execute(
1162 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001163 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001164 )
1165 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001166 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1167 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001168 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001169
1170 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1171
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1173 let result: Vec<(i64, Vec<u8>)> = {
1174 let mut stmt = tx
1175 .prepare(
1176 "SELECT id, blob FROM persistent.blobentry
1177 WHERE subcomponent_type = ?
1178 AND (
1179 id NOT IN (
1180 SELECT MAX(id) FROM persistent.blobentry
1181 WHERE subcomponent_type = ?
1182 GROUP BY keyentryid, subcomponent_type
1183 )
1184 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1185 ) LIMIT ?;",
1186 )
1187 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001188
Janis Danisevskis3395f862021-05-06 10:54:17 -07001189 let rows = stmt
1190 .query_map(
1191 params![
1192 SubComponentType::KEY_BLOB,
1193 SubComponentType::KEY_BLOB,
1194 max_blobs as i64,
1195 ],
1196 |row| Ok((row.get(0)?, row.get(1)?)),
1197 )
1198 .context("Trying to query superseded blob.")?;
1199
1200 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1201 .context("Trying to extract superseded blobs.")?
1202 };
1203
1204 let result = result
1205 .into_iter()
1206 .map(|(blob_id, blob)| {
1207 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1208 })
1209 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1210 .context("Trying to load blob metadata.")?;
1211 if !result.is_empty() {
1212 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001213 }
1214
1215 // We did not find any superseded key blob, so let's remove other superseded blob in
1216 // one transaction.
1217 tx.execute(
1218 "DELETE FROM persistent.blobentry
1219 WHERE NOT subcomponent_type = ?
1220 AND (
1221 id NOT IN (
1222 SELECT MAX(id) FROM persistent.blobentry
1223 WHERE NOT subcomponent_type = ?
1224 GROUP BY keyentryid, subcomponent_type
1225 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1226 );",
1227 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1228 )
1229 .context("Trying to purge superseded blobs.")?;
1230
Janis Danisevskis3395f862021-05-06 10:54:17 -07001231 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001232 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001233 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001234 }
1235
1236 /// This maintenance function should be called only once before the database is used for the
1237 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1238 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1239 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1240 /// Keystore crashed at some point during key generation. Callers may want to log such
1241 /// occurrences.
1242 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1243 /// it to `KeyLifeCycle::Live` may have grants.
1244 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001245 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1246
Janis Danisevskis66784c42021-01-27 08:40:25 -08001247 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1248 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001249 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1250 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1251 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001252 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001253 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001254 })
1255 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001256 }
1257
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001258 /// Checks if a key exists with given key type and key descriptor properties.
1259 pub fn key_exists(
1260 &mut self,
1261 domain: Domain,
1262 nspace: i64,
1263 alias: &str,
1264 key_type: KeyType,
1265 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001266 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1267
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001268 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1269 let key_descriptor =
1270 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1271 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1272 match result {
1273 Ok(_) => Ok(true),
1274 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1275 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1276 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1277 },
1278 }
1279 .no_gc()
1280 })
1281 .context("In key_exists.")
1282 }
1283
Hasini Gunasingheda895552021-01-27 19:34:37 +00001284 /// Stores a super key in the database.
1285 pub fn store_super_key(
1286 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001287 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001288 key_type: &SuperKeyType,
1289 blob: &[u8],
1290 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001291 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001292 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001293 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1294
Hasini Gunasingheda895552021-01-27 19:34:37 +00001295 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1296 let key_id = Self::insert_with_retry(|id| {
1297 tx.execute(
1298 "INSERT into persistent.keyentry
1299 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001300 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001301 params![
1302 id,
1303 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001304 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001305 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001306 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001307 KeyLifeCycle::Live,
1308 &KEYSTORE_UUID,
1309 ],
1310 )
1311 })
1312 .context("Failed to insert into keyentry table.")?;
1313
Paul Crowley8d5b2532021-03-19 10:53:07 -07001314 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1315
Hasini Gunasingheda895552021-01-27 19:34:37 +00001316 Self::set_blob_internal(
1317 &tx,
1318 key_id,
1319 SubComponentType::KEY_BLOB,
1320 Some(blob),
1321 Some(blob_metadata),
1322 )
1323 .context("Failed to store key blob.")?;
1324
1325 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1326 .context("Trying to load key components.")
1327 .no_gc()
1328 })
1329 .context("In store_super_key.")
1330 }
1331
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001332 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001333 pub fn load_super_key(
1334 &mut self,
1335 key_type: &SuperKeyType,
1336 user_id: u32,
1337 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001338 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1339
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001340 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1341 let key_descriptor = KeyDescriptor {
1342 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001343 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001344 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001345 blob: None,
1346 };
1347 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1348 match id {
1349 Ok(id) => {
1350 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1351 .context("In load_super_key. Failed to load key entry.")?;
1352 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1353 }
1354 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1355 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1356 _ => Err(error).context("In load_super_key."),
1357 },
1358 }
1359 .no_gc()
1360 })
1361 .context("In load_super_key.")
1362 }
1363
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001364 /// Atomically loads a key entry and associated metadata or creates it using the
1365 /// callback create_new_key callback. The callback is called during a database
1366 /// transaction. This means that implementers should be mindful about using
1367 /// blocking operations such as IPC or grabbing mutexes.
1368 pub fn get_or_create_key_with<F>(
1369 &mut self,
1370 domain: Domain,
1371 namespace: i64,
1372 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001373 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001374 create_new_key: F,
1375 ) -> Result<(KeyIdGuard, KeyEntry)>
1376 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001377 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001378 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001379 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1380
Janis Danisevskis66784c42021-01-27 08:40:25 -08001381 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1382 let id = {
1383 let mut stmt = tx
1384 .prepare(
1385 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001386 WHERE
1387 key_type = ?
1388 AND domain = ?
1389 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001390 AND alias = ?
1391 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001392 )
1393 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1394 let mut rows = stmt
1395 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1396 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001397
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 db_utils::with_rows_extract_one(&mut rows, |row| {
1399 Ok(match row {
1400 Some(r) => r.get(0).context("Failed to unpack id.")?,
1401 None => None,
1402 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 .context("In get_or_create_key_with.")?
1405 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001406
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 let (id, entry) = match id {
1408 Some(id) => (
1409 id,
1410 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1411 .context("In get_or_create_key_with.")?,
1412 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001413
Janis Danisevskis66784c42021-01-27 08:40:25 -08001414 None => {
1415 let id = Self::insert_with_retry(|id| {
1416 tx.execute(
1417 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001418 (id, key_type, domain, namespace, alias, state, km_uuid)
1419 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001420 params![
1421 id,
1422 KeyType::Super,
1423 domain.0,
1424 namespace,
1425 alias,
1426 KeyLifeCycle::Live,
1427 km_uuid,
1428 ],
1429 )
1430 })
1431 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001432
Janis Danisevskis66784c42021-01-27 08:40:25 -08001433 let (blob, metadata) =
1434 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001435 Self::set_blob_internal(
1436 &tx,
1437 id,
1438 SubComponentType::KEY_BLOB,
1439 Some(&blob),
1440 Some(&metadata),
1441 )
Paul Crowley7a658392021-03-18 17:08:20 -07001442 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001443 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001444 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001445 KeyEntry {
1446 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001447 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001448 pure_cert: false,
1449 ..Default::default()
1450 },
1451 )
1452 }
1453 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001454 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001455 })
1456 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001457 }
1458
Janis Danisevskis66784c42021-01-27 08:40:25 -08001459 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1460 /// waiting for the database file to become available. This makes it
1461 /// impossible to successfully recover from a locked database when the
1462 /// transaction holding the device busy is in the same process on a
1463 /// different connection. As a result the busy handler has to time out and
1464 /// fail in order to make progress.
1465 ///
1466 /// Instead, we set the busy handler to None (return immediately). And catch
1467 /// Busy and Locked errors (the latter occur on in memory databases with
1468 /// shared cache, e.g., the per-boot database.) and restart the transaction
1469 /// after a grace period of half a millisecond.
1470 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001471 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001472 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1473 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001474 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1475 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001476 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001477 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001478 loop {
1479 match self
1480 .conn
1481 .transaction_with_behavior(behavior)
1482 .context("In with_transaction.")
1483 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1484 .and_then(|(result, tx)| {
1485 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1486 Ok(result)
1487 }) {
1488 Ok(result) => break Ok(result),
1489 Err(e) => {
1490 if Self::is_locked_error(&e) {
1491 std::thread::sleep(std::time::Duration::from_micros(500));
1492 continue;
1493 } else {
1494 return Err(e).context("In with_transaction.");
1495 }
1496 }
1497 }
1498 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001499 .map(|(need_gc, result)| {
1500 if need_gc {
1501 if let Some(ref gc) = self.gc {
1502 gc.notify_gc();
1503 }
1504 }
1505 result
1506 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001507 }
1508
1509 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001510 matches!(
1511 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1512 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1513 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1514 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001515 }
1516
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001517 /// Creates a new key entry and allocates a new randomized id for the new key.
1518 /// The key id gets associated with a domain and namespace but not with an alias.
1519 /// To complete key generation `rebind_alias` should be called after all of the
1520 /// key artifacts, i.e., blobs and parameters have been associated with the new
1521 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1522 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001523 pub fn create_key_entry(
1524 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001525 domain: &Domain,
1526 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001527 km_uuid: &Uuid,
1528 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001529 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1530
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001531 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001532 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001533 })
1534 .context("In create_key_entry.")
1535 }
1536
1537 fn create_key_entry_internal(
1538 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001539 domain: &Domain,
1540 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001541 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001542 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001543 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001544 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001545 _ => {
1546 return Err(KsError::sys())
1547 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1548 }
1549 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001550 Ok(KEY_ID_LOCK.get(
1551 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001552 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001553 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001554 (id, key_type, domain, namespace, alias, state, km_uuid)
1555 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001556 params![
1557 id,
1558 KeyType::Client,
1559 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001560 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001561 KeyLifeCycle::Existing,
1562 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001563 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001564 )
1565 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001566 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001567 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001568 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001569
Max Bires2b2e6562020-09-22 11:22:36 -07001570 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1571 /// The key id gets associated with a domain and namespace later but not with an alias. The
1572 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1573 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1574 /// a key.
1575 pub fn create_attestation_key_entry(
1576 &mut self,
1577 maced_public_key: &[u8],
1578 raw_public_key: &[u8],
1579 private_key: &[u8],
1580 km_uuid: &Uuid,
1581 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001582 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1583
Max Bires2b2e6562020-09-22 11:22:36 -07001584 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1585 let key_id = KEY_ID_LOCK.get(
1586 Self::insert_with_retry(|id| {
1587 tx.execute(
1588 "INSERT into persistent.keyentry
1589 (id, key_type, domain, namespace, alias, state, km_uuid)
1590 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1591 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1592 )
1593 })
1594 .context("In create_key_entry")?,
1595 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001596 Self::set_blob_internal(
1597 &tx,
1598 key_id.0,
1599 SubComponentType::KEY_BLOB,
1600 Some(private_key),
1601 None,
1602 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001603 let mut metadata = KeyMetaData::new();
1604 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1605 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1606 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001607 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001608 })
1609 .context("In create_attestation_key_entry")
1610 }
1611
Janis Danisevskis377d1002021-01-27 19:07:48 -08001612 /// Set a new blob and associates it with the given key id. Each blob
1613 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001614 /// Each key can have one of each sub component type associated. If more
1615 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001616 /// will get garbage collected.
1617 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1618 /// removed by setting blob to None.
1619 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001620 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001621 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001622 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001623 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001624 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001625 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001626 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1627
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001628 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001629 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001630 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001631 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001632 }
1633
Janis Danisevskiseed69842021-02-18 20:04:10 -08001634 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1635 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1636 /// We use this to insert key blobs into the database which can then be garbage collected
1637 /// lazily by the key garbage collector.
1638 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001639 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1640
Janis Danisevskiseed69842021-02-18 20:04:10 -08001641 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1642 Self::set_blob_internal(
1643 &tx,
1644 Self::UNASSIGNED_KEY_ID,
1645 SubComponentType::KEY_BLOB,
1646 Some(blob),
1647 Some(blob_metadata),
1648 )
1649 .need_gc()
1650 })
1651 .context("In set_deleted_blob.")
1652 }
1653
Janis Danisevskis377d1002021-01-27 19:07:48 -08001654 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001655 tx: &Transaction,
1656 key_id: i64,
1657 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001658 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001659 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001660 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001661 match (blob, sc_type) {
1662 (Some(blob), _) => {
1663 tx.execute(
1664 "INSERT INTO persistent.blobentry
1665 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1666 params![sc_type, key_id, blob],
1667 )
1668 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001669 if let Some(blob_metadata) = blob_metadata {
1670 let blob_id = tx
1671 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1672 row.get(0)
1673 })
1674 .context("In set_blob_internal: Failed to get new blob id.")?;
1675 blob_metadata
1676 .store_in_db(blob_id, tx)
1677 .context("In set_blob_internal: Trying to store blob metadata.")?;
1678 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001679 }
1680 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1681 tx.execute(
1682 "DELETE FROM persistent.blobentry
1683 WHERE subcomponent_type = ? AND keyentryid = ?;",
1684 params![sc_type, key_id],
1685 )
1686 .context("In set_blob_internal: Failed to delete blob.")?;
1687 }
1688 (None, _) => {
1689 return Err(KsError::sys())
1690 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1691 }
1692 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001693 Ok(())
1694 }
1695
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001696 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1697 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001698 #[cfg(test)]
1699 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001700 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001701 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001702 })
1703 .context("In insert_keyparameter.")
1704 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001705
Janis Danisevskis66784c42021-01-27 08:40:25 -08001706 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001707 tx: &Transaction,
1708 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001709 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001710 ) -> Result<()> {
1711 let mut stmt = tx
1712 .prepare(
1713 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1714 VALUES (?, ?, ?, ?);",
1715 )
1716 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1717
Janis Danisevskis66784c42021-01-27 08:40:25 -08001718 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001719 stmt.insert(params![
1720 key_id.0,
1721 p.get_tag().0,
1722 p.key_parameter_value(),
1723 p.security_level().0
1724 ])
1725 .with_context(|| {
1726 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1727 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001728 }
1729 Ok(())
1730 }
1731
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001732 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001733 #[cfg(test)]
1734 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001735 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001736 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001737 })
1738 .context("In insert_key_metadata.")
1739 }
1740
Max Bires2b2e6562020-09-22 11:22:36 -07001741 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1742 /// on the public key.
1743 pub fn store_signed_attestation_certificate_chain(
1744 &mut self,
1745 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001746 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001747 cert_chain: &[u8],
1748 expiration_date: i64,
1749 km_uuid: &Uuid,
1750 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001751 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1752
Max Bires2b2e6562020-09-22 11:22:36 -07001753 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1754 let mut stmt = tx
1755 .prepare(
1756 "SELECT keyentryid
1757 FROM persistent.keymetadata
1758 WHERE tag = ? AND data = ? AND keyentryid IN
1759 (SELECT id
1760 FROM persistent.keyentry
1761 WHERE
1762 alias IS NULL AND
1763 domain IS NULL AND
1764 namespace IS NULL AND
1765 key_type = ? AND
1766 km_uuid = ?);",
1767 )
1768 .context("Failed to store attestation certificate chain.")?;
1769 let mut rows = stmt
1770 .query(params![
1771 KeyMetaData::AttestationRawPubKey,
1772 raw_public_key,
1773 KeyType::Attestation,
1774 km_uuid
1775 ])
1776 .context("Failed to fetch keyid")?;
1777 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1778 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1779 .get(0)
1780 .context("Failed to unpack id.")
1781 })
1782 .context("Failed to get key_id.")?;
1783 let num_updated = tx
1784 .execute(
1785 "UPDATE persistent.keyentry
1786 SET alias = ?
1787 WHERE id = ?;",
1788 params!["signed", key_id],
1789 )
1790 .context("Failed to update alias.")?;
1791 if num_updated != 1 {
1792 return Err(KsError::sys()).context("Alias not updated for the key.");
1793 }
1794 let mut metadata = KeyMetaData::new();
1795 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1796 expiration_date,
1797 )));
1798 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001799 Self::set_blob_internal(
1800 &tx,
1801 key_id,
1802 SubComponentType::CERT_CHAIN,
1803 Some(cert_chain),
1804 None,
1805 )
1806 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001807 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1808 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001809 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001810 })
1811 .context("In store_signed_attestation_certificate_chain: ")
1812 }
1813
1814 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1815 /// currently have a key assigned to it.
1816 pub fn assign_attestation_key(
1817 &mut self,
1818 domain: Domain,
1819 namespace: i64,
1820 km_uuid: &Uuid,
1821 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001822 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1823
Max Bires2b2e6562020-09-22 11:22:36 -07001824 match domain {
1825 Domain::APP | Domain::SELINUX => {}
1826 _ => {
1827 return Err(KsError::sys()).context(format!(
1828 concat!(
1829 "In assign_attestation_key: Domain {:?} ",
1830 "must be either App or SELinux.",
1831 ),
1832 domain
1833 ));
1834 }
1835 }
1836 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1837 let result = tx
1838 .execute(
1839 "UPDATE persistent.keyentry
1840 SET domain=?1, namespace=?2
1841 WHERE
1842 id =
1843 (SELECT MIN(id)
1844 FROM persistent.keyentry
1845 WHERE ALIAS IS NOT NULL
1846 AND domain IS NULL
1847 AND key_type IS ?3
1848 AND state IS ?4
1849 AND km_uuid IS ?5)
1850 AND
1851 (SELECT COUNT(*)
1852 FROM persistent.keyentry
1853 WHERE domain=?1
1854 AND namespace=?2
1855 AND key_type IS ?3
1856 AND state IS ?4
1857 AND km_uuid IS ?5) = 0;",
1858 params![
1859 domain.0 as u32,
1860 namespace,
1861 KeyType::Attestation,
1862 KeyLifeCycle::Live,
1863 km_uuid,
1864 ],
1865 )
1866 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001867 if result == 0 {
1868 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1869 } else if result > 1 {
1870 return Err(KsError::sys())
1871 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001872 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001873 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001874 })
1875 .context("In assign_attestation_key: ")
1876 }
1877
1878 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1879 /// provisioning server, or the maximum number available if there are not num_keys number of
1880 /// entries in the table.
1881 pub fn fetch_unsigned_attestation_keys(
1882 &mut self,
1883 num_keys: i32,
1884 km_uuid: &Uuid,
1885 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001886 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1887
Max Bires2b2e6562020-09-22 11:22:36 -07001888 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1889 let mut stmt = tx
1890 .prepare(
1891 "SELECT data
1892 FROM persistent.keymetadata
1893 WHERE tag = ? AND keyentryid IN
1894 (SELECT id
1895 FROM persistent.keyentry
1896 WHERE
1897 alias IS NULL AND
1898 domain IS NULL AND
1899 namespace IS NULL AND
1900 key_type = ? AND
1901 km_uuid = ?
1902 LIMIT ?);",
1903 )
1904 .context("Failed to prepare statement")?;
1905 let rows = stmt
1906 .query_map(
1907 params![
1908 KeyMetaData::AttestationMacedPublicKey,
1909 KeyType::Attestation,
1910 km_uuid,
1911 num_keys
1912 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001913 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001914 )?
1915 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1916 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001917 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001918 })
1919 .context("In fetch_unsigned_attestation_keys")
1920 }
1921
1922 /// Removes any keys that have expired as of the current time. Returns the number of keys
1923 /// marked unreferenced that are bound to be garbage collected.
1924 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001925 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1926
Max Bires2b2e6562020-09-22 11:22:36 -07001927 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1928 let mut stmt = tx
1929 .prepare(
1930 "SELECT keyentryid, data
1931 FROM persistent.keymetadata
1932 WHERE tag = ? AND keyentryid IN
1933 (SELECT id
1934 FROM persistent.keyentry
1935 WHERE key_type = ?);",
1936 )
1937 .context("Failed to prepare query")?;
1938 let key_ids_to_check = stmt
1939 .query_map(
1940 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1941 |row| Ok((row.get(0)?, row.get(1)?)),
1942 )?
1943 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1944 .context("Failed to get date metadata")?;
1945 let curr_time = DateTime::from_millis_epoch(
1946 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1947 );
1948 let mut num_deleted = 0;
1949 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1950 if Self::mark_unreferenced(&tx, id)? {
1951 num_deleted += 1;
1952 }
1953 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001954 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001955 })
1956 .context("In delete_expired_attestation_keys: ")
1957 }
1958
Max Bires60d7ed12021-03-05 15:59:22 -08001959 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1960 /// they are in. This is useful primarily as a testing mechanism.
1961 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001962 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1963
Max Bires60d7ed12021-03-05 15:59:22 -08001964 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1965 let mut stmt = tx
1966 .prepare(
1967 "SELECT id FROM persistent.keyentry
1968 WHERE key_type IS ?;",
1969 )
1970 .context("Failed to prepare statement")?;
1971 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001972 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001973 .collect::<rusqlite::Result<Vec<i64>>>()
1974 .context("Failed to execute statement")?;
1975 let num_deleted = keys_to_delete
1976 .iter()
1977 .map(|id| Self::mark_unreferenced(&tx, *id))
1978 .collect::<Result<Vec<bool>>>()
1979 .context("Failed to execute mark_unreferenced on a keyid")?
1980 .into_iter()
1981 .filter(|result| *result)
1982 .count() as i64;
1983 Ok(num_deleted).do_gc(num_deleted != 0)
1984 })
1985 .context("In delete_all_attestation_keys: ")
1986 }
1987
Max Bires2b2e6562020-09-22 11:22:36 -07001988 /// Counts the number of keys that will expire by the provided epoch date and the number of
1989 /// keys not currently assigned to a domain.
1990 pub fn get_attestation_pool_status(
1991 &mut self,
1992 date: i64,
1993 km_uuid: &Uuid,
1994 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001995 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1996
Max Bires2b2e6562020-09-22 11:22:36 -07001997 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1998 let mut stmt = tx.prepare(
1999 "SELECT data
2000 FROM persistent.keymetadata
2001 WHERE tag = ? AND keyentryid IN
2002 (SELECT id
2003 FROM persistent.keyentry
2004 WHERE alias IS NOT NULL
2005 AND key_type = ?
2006 AND km_uuid = ?
2007 AND state = ?);",
2008 )?;
2009 let times = stmt
2010 .query_map(
2011 params![
2012 KeyMetaData::AttestationExpirationDate,
2013 KeyType::Attestation,
2014 km_uuid,
2015 KeyLifeCycle::Live
2016 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002017 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002018 )?
2019 .collect::<rusqlite::Result<Vec<DateTime>>>()
2020 .context("Failed to execute metadata statement")?;
2021 let expiring =
2022 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2023 as i32;
2024 stmt = tx.prepare(
2025 "SELECT alias, domain
2026 FROM persistent.keyentry
2027 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2028 )?;
2029 let rows = stmt
2030 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2031 Ok((row.get(0)?, row.get(1)?))
2032 })?
2033 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2034 .context("Failed to execute keyentry statement")?;
2035 let mut unassigned = 0i32;
2036 let mut attested = 0i32;
2037 let total = rows.len() as i32;
2038 for (alias, domain) in rows {
2039 match (alias, domain) {
2040 (Some(_alias), None) => {
2041 attested += 1;
2042 unassigned += 1;
2043 }
2044 (Some(_alias), Some(_domain)) => {
2045 attested += 1;
2046 }
2047 _ => {}
2048 }
2049 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002050 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002051 })
2052 .context("In get_attestation_pool_status: ")
2053 }
2054
2055 /// Fetches the private key and corresponding certificate chain assigned to a
2056 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2057 /// not assigned, or one CertificateChain.
2058 pub fn retrieve_attestation_key_and_cert_chain(
2059 &mut self,
2060 domain: Domain,
2061 namespace: i64,
2062 km_uuid: &Uuid,
2063 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002064 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2065
Max Bires2b2e6562020-09-22 11:22:36 -07002066 match domain {
2067 Domain::APP | Domain::SELINUX => {}
2068 _ => {
2069 return Err(KsError::sys())
2070 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2071 }
2072 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002073 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2074 let mut stmt = tx.prepare(
2075 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002076 FROM persistent.blobentry
2077 WHERE keyentryid IN
2078 (SELECT id
2079 FROM persistent.keyentry
2080 WHERE key_type = ?
2081 AND domain = ?
2082 AND namespace = ?
2083 AND state = ?
2084 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002085 )?;
2086 let rows = stmt
2087 .query_map(
2088 params![
2089 KeyType::Attestation,
2090 domain.0 as u32,
2091 namespace,
2092 KeyLifeCycle::Live,
2093 km_uuid
2094 ],
2095 |row| Ok((row.get(0)?, row.get(1)?)),
2096 )?
2097 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002098 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002099 if rows.is_empty() {
2100 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002101 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002102 return Err(KsError::sys()).context(format!(
2103 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002104 "Expected to get a single attestation",
2105 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2106 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002107 rows.len()
2108 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002109 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002110 let mut km_blob: Vec<u8> = Vec::new();
2111 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002112 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002113 for row in rows {
2114 let sub_type: SubComponentType = row.0;
2115 match sub_type {
2116 SubComponentType::KEY_BLOB => {
2117 km_blob = row.1;
2118 }
2119 SubComponentType::CERT_CHAIN => {
2120 cert_chain_blob = row.1;
2121 }
Max Biresb2e1d032021-02-08 21:35:05 -08002122 SubComponentType::CERT => {
2123 batch_cert_blob = row.1;
2124 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002125 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2126 }
2127 }
2128 Ok(Some(CertificateChain {
2129 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002130 batch_cert: batch_cert_blob,
2131 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002132 }))
2133 .no_gc()
2134 })
Max Biresb2e1d032021-02-08 21:35:05 -08002135 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002136 }
2137
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002138 /// Updates the alias column of the given key id `newid` with the given alias,
2139 /// and atomically, removes the alias, domain, and namespace from another row
2140 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002141 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2142 /// collector.
2143 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002144 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002145 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002146 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002147 domain: &Domain,
2148 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002149 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002150 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002151 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002152 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002153 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002154 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002155 domain
2156 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002157 }
2158 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002159 let updated = tx
2160 .execute(
2161 "UPDATE persistent.keyentry
2162 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002163 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002164 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2165 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002166 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002167 let result = tx
2168 .execute(
2169 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002170 SET alias = ?, state = ?
2171 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2172 params![
2173 alias,
2174 KeyLifeCycle::Live,
2175 newid.0,
2176 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002177 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002178 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002179 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002180 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002181 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002182 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002183 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002184 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002185 result
2186 ));
2187 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002188 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002189 }
2190
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002191 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2192 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2193 pub fn migrate_key_namespace(
2194 &mut self,
2195 key_id_guard: KeyIdGuard,
2196 destination: &KeyDescriptor,
2197 caller_uid: u32,
2198 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2199 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002200 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2201
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002202 let destination = match destination.domain {
2203 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2204 Domain::SELINUX => (*destination).clone(),
2205 domain => {
2206 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2207 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2208 }
2209 };
2210
2211 // Security critical: Must return immediately on failure. Do not remove the '?';
2212 check_permission(&destination)
2213 .context("In migrate_key_namespace: Trying to check permission.")?;
2214
2215 let alias = destination
2216 .alias
2217 .as_ref()
2218 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2219 .context("In migrate_key_namespace: Alias must be specified.")?;
2220
2221 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2222 // Query the destination location. If there is a key, the migration request fails.
2223 if tx
2224 .query_row(
2225 "SELECT id FROM persistent.keyentry
2226 WHERE alias = ? AND domain = ? AND namespace = ?;",
2227 params![alias, destination.domain.0, destination.nspace],
2228 |_| Ok(()),
2229 )
2230 .optional()
2231 .context("Failed to query destination.")?
2232 .is_some()
2233 {
2234 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2235 .context("Target already exists.");
2236 }
2237
2238 let updated = tx
2239 .execute(
2240 "UPDATE persistent.keyentry
2241 SET alias = ?, domain = ?, namespace = ?
2242 WHERE id = ?;",
2243 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2244 )
2245 .context("Failed to update key entry.")?;
2246
2247 if updated != 1 {
2248 return Err(KsError::sys())
2249 .context(format!("Update succeeded, but {} rows were updated.", updated));
2250 }
2251 Ok(()).no_gc()
2252 })
2253 .context("In migrate_key_namespace:")
2254 }
2255
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002256 /// Store a new key in a single transaction.
2257 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2258 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002259 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2260 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002261 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002262 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002263 key: &KeyDescriptor,
2264 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002265 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002266 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002267 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002268 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002269 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002270 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2271
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002272 let (alias, domain, namespace) = match key {
2273 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2274 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2275 (alias, key.domain, nspace)
2276 }
2277 _ => {
2278 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2279 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2280 }
2281 };
2282 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002283 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002284 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002285 let (blob, blob_metadata) = *blob_info;
2286 Self::set_blob_internal(
2287 tx,
2288 key_id.id(),
2289 SubComponentType::KEY_BLOB,
2290 Some(blob),
2291 Some(&blob_metadata),
2292 )
2293 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002294 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002295 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002296 .context("Trying to insert the certificate.")?;
2297 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002298 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002299 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002300 tx,
2301 key_id.id(),
2302 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002303 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002304 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002305 )
2306 .context("Trying to insert the certificate chain.")?;
2307 }
2308 Self::insert_keyparameter_internal(tx, &key_id, params)
2309 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002310 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002311 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002312 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002313 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002314 })
2315 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002316 }
2317
Janis Danisevskis377d1002021-01-27 19:07:48 -08002318 /// Store a new certificate
2319 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2320 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002321 pub fn store_new_certificate(
2322 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002323 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002324 cert: &[u8],
2325 km_uuid: &Uuid,
2326 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002327 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2328
Janis Danisevskis377d1002021-01-27 19:07:48 -08002329 let (alias, domain, namespace) = match key {
2330 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2331 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2332 (alias, key.domain, nspace)
2333 }
2334 _ => {
2335 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2336 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2337 )
2338 }
2339 };
2340 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002341 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002342 .context("Trying to create new key entry.")?;
2343
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002344 Self::set_blob_internal(
2345 tx,
2346 key_id.id(),
2347 SubComponentType::CERT_CHAIN,
2348 Some(cert),
2349 None,
2350 )
2351 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002352
2353 let mut metadata = KeyMetaData::new();
2354 metadata.add(KeyMetaEntry::CreationDate(
2355 DateTime::now().context("Trying to make creation time.")?,
2356 ));
2357
2358 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2359
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002360 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002361 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002362 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002363 })
2364 .context("In store_new_certificate.")
2365 }
2366
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002367 // Helper function loading the key_id given the key descriptor
2368 // tuple comprising domain, namespace, and alias.
2369 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002370 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002371 let alias = key
2372 .alias
2373 .as_ref()
2374 .map_or_else(|| Err(KsError::sys()), Ok)
2375 .context("In load_key_entry_id: Alias must be specified.")?;
2376 let mut stmt = tx
2377 .prepare(
2378 "SELECT id FROM persistent.keyentry
2379 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002380 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002381 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002382 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002383 AND alias = ?
2384 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002385 )
2386 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2387 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002388 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002389 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002390 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002391 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002392 .get(0)
2393 .context("Failed to unpack id.")
2394 })
2395 .context("In load_key_entry_id.")
2396 }
2397
2398 /// This helper function completes the access tuple of a key, which is required
2399 /// to perform access control. The strategy depends on the `domain` field in the
2400 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002401 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002402 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002403 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002404 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002405 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002406 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002407 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408 /// `namespace`.
2409 /// In each case the information returned is sufficient to perform the access
2410 /// check and the key id can be used to load further key artifacts.
2411 fn load_access_tuple(
2412 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002413 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002414 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002415 caller_uid: u32,
2416 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2417 match key.domain {
2418 // Domain App or SELinux. In this case we load the key_id from
2419 // the keyentry database for further loading of key components.
2420 // We already have the full access tuple to perform access control.
2421 // The only distinction is that we use the caller_uid instead
2422 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002423 // Domain::APP.
2424 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002425 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002426 if access_key.domain == Domain::APP {
2427 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002428 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002429 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002430 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002431
2432 Ok((key_id, access_key, None))
2433 }
2434
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002435 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002436 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002437 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 let mut stmt = tx
2439 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002440 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002441 WHERE grantee = ? AND id = ? AND
2442 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002443 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002444 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002445 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002446 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002447 .context("Domain:Grant: query failed.")?;
2448 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002449 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002450 let r =
2451 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002452 Ok((
2453 r.get(0).context("Failed to unpack key_id.")?,
2454 r.get(1).context("Failed to unpack access_vector.")?,
2455 ))
2456 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002457 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002458 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002459 }
2460
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002461 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002462 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002463 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002464 let (domain, namespace): (Domain, i64) = {
2465 let mut stmt = tx
2466 .prepare(
2467 "SELECT domain, namespace FROM persistent.keyentry
2468 WHERE
2469 id = ?
2470 AND state = ?;",
2471 )
2472 .context("Domain::KEY_ID: prepare statement failed")?;
2473 let mut rows = stmt
2474 .query(params![key.nspace, KeyLifeCycle::Live])
2475 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002476 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002477 let r =
2478 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002479 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002480 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002481 r.get(1).context("Failed to unpack namespace.")?,
2482 ))
2483 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002484 .context("Domain::KEY_ID.")?
2485 };
2486
2487 // We may use a key by id after loading it by grant.
2488 // In this case we have to check if the caller has a grant for this particular
2489 // key. We can skip this if we already know that the caller is the owner.
2490 // But we cannot know this if domain is anything but App. E.g. in the case
2491 // of Domain::SELINUX we have to speculatively check for grants because we have to
2492 // consult the SEPolicy before we know if the caller is the owner.
2493 let access_vector: Option<KeyPermSet> =
2494 if domain != Domain::APP || namespace != caller_uid as i64 {
2495 let access_vector: Option<i32> = tx
2496 .query_row(
2497 "SELECT access_vector FROM persistent.grant
2498 WHERE grantee = ? AND keyentryid = ?;",
2499 params![caller_uid as i64, key.nspace],
2500 |row| row.get(0),
2501 )
2502 .optional()
2503 .context("Domain::KEY_ID: query grant failed.")?;
2504 access_vector.map(|p| p.into())
2505 } else {
2506 None
2507 };
2508
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002509 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002510 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002511 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002512 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002513
Janis Danisevskis45760022021-01-19 16:34:10 -08002514 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002515 }
2516 _ => Err(anyhow!(KsError::sys())),
2517 }
2518 }
2519
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002520 fn load_blob_components(
2521 key_id: i64,
2522 load_bits: KeyEntryLoadBits,
2523 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002524 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002525 let mut stmt = tx
2526 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002527 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002528 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2529 )
2530 .context("In load_blob_components: prepare statement failed.")?;
2531
2532 let mut rows =
2533 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2534
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002535 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002536 let mut cert_blob: Option<Vec<u8>> = None;
2537 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002538 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002539 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002540 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002541 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002542 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002543 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2544 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002545 key_blob = Some((
2546 row.get(0).context("Failed to extract key blob id.")?,
2547 row.get(2).context("Failed to extract key blob.")?,
2548 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002549 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002550 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002551 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002552 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002553 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002554 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002555 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002556 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002557 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002558 (SubComponentType::CERT, _, _)
2559 | (SubComponentType::CERT_CHAIN, _, _)
2560 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002561 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2562 }
2563 Ok(())
2564 })
2565 .context("In load_blob_components.")?;
2566
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002567 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2568 Ok(Some((
2569 blob,
2570 BlobMetaData::load_from_db(blob_id, tx)
2571 .context("In load_blob_components: Trying to load blob_metadata.")?,
2572 )))
2573 })?;
2574
2575 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002576 }
2577
2578 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2579 let mut stmt = tx
2580 .prepare(
2581 "SELECT tag, data, security_level from persistent.keyparameter
2582 WHERE keyentryid = ?;",
2583 )
2584 .context("In load_key_parameters: prepare statement failed.")?;
2585
2586 let mut parameters: Vec<KeyParameter> = Vec::new();
2587
2588 let mut rows =
2589 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002590 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002591 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2592 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002593 parameters.push(
2594 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2595 .context("Failed to read KeyParameter.")?,
2596 );
2597 Ok(())
2598 })
2599 .context("In load_key_parameters.")?;
2600
2601 Ok(parameters)
2602 }
2603
Qi Wub9433b52020-12-01 14:52:46 +08002604 /// Decrements the usage count of a limited use key. This function first checks whether the
2605 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2606 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2607 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002608 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002609 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2610
Qi Wub9433b52020-12-01 14:52:46 +08002611 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2612 let limit: Option<i32> = tx
2613 .query_row(
2614 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2615 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2616 |row| row.get(0),
2617 )
2618 .optional()
2619 .context("Trying to load usage count")?;
2620
2621 let limit = limit
2622 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2623 .context("The Key no longer exists. Key is exhausted.")?;
2624
2625 tx.execute(
2626 "UPDATE persistent.keyparameter
2627 SET data = data - 1
2628 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2629 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2630 )
2631 .context("Failed to update key usage count.")?;
2632
2633 match limit {
2634 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002635 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002636 .context("Trying to mark limited use key for deletion."),
2637 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002638 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002639 }
2640 })
2641 .context("In check_and_update_key_usage_count.")
2642 }
2643
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002644 /// Load a key entry by the given key descriptor.
2645 /// It uses the `check_permission` callback to verify if the access is allowed
2646 /// given the key access tuple read from the database using `load_access_tuple`.
2647 /// With `load_bits` the caller may specify which blobs shall be loaded from
2648 /// the blob database.
2649 pub fn load_key_entry(
2650 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002651 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002652 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002653 load_bits: KeyEntryLoadBits,
2654 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002655 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2656 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002657 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2658
Janis Danisevskis66784c42021-01-27 08:40:25 -08002659 loop {
2660 match self.load_key_entry_internal(
2661 key,
2662 key_type,
2663 load_bits,
2664 caller_uid,
2665 &check_permission,
2666 ) {
2667 Ok(result) => break Ok(result),
2668 Err(e) => {
2669 if Self::is_locked_error(&e) {
2670 std::thread::sleep(std::time::Duration::from_micros(500));
2671 continue;
2672 } else {
2673 return Err(e).context("In load_key_entry.");
2674 }
2675 }
2676 }
2677 }
2678 }
2679
2680 fn load_key_entry_internal(
2681 &mut self,
2682 key: &KeyDescriptor,
2683 key_type: KeyType,
2684 load_bits: KeyEntryLoadBits,
2685 caller_uid: u32,
2686 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002687 ) -> Result<(KeyIdGuard, KeyEntry)> {
2688 // KEY ID LOCK 1/2
2689 // If we got a key descriptor with a key id we can get the lock right away.
2690 // Otherwise we have to defer it until we know the key id.
2691 let key_id_guard = match key.domain {
2692 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2693 _ => None,
2694 };
2695
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002696 let tx = self
2697 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002698 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002699 .context("In load_key_entry: Failed to initialize transaction.")?;
2700
2701 // Load the key_id and complete the access control tuple.
2702 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002703 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2704 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002705
2706 // Perform access control. It is vital that we return here if the permission is denied.
2707 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002708 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002709
Janis Danisevskisaec14592020-11-12 09:41:49 -08002710 // KEY ID LOCK 2/2
2711 // If we did not get a key id lock by now, it was because we got a key descriptor
2712 // without a key id. At this point we got the key id, so we can try and get a lock.
2713 // However, we cannot block here, because we are in the middle of the transaction.
2714 // So first we try to get the lock non blocking. If that fails, we roll back the
2715 // transaction and block until we get the lock. After we successfully got the lock,
2716 // we start a new transaction and load the access tuple again.
2717 //
2718 // We don't need to perform access control again, because we already established
2719 // that the caller had access to the given key. But we need to make sure that the
2720 // key id still exists. So we have to load the key entry by key id this time.
2721 let (key_id_guard, tx) = match key_id_guard {
2722 None => match KEY_ID_LOCK.try_get(key_id) {
2723 None => {
2724 // Roll back the transaction.
2725 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002726
Janis Danisevskisaec14592020-11-12 09:41:49 -08002727 // Block until we have a key id lock.
2728 let key_id_guard = KEY_ID_LOCK.get(key_id);
2729
2730 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002731 let tx = self
2732 .conn
2733 .unchecked_transaction()
2734 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002735
2736 Self::load_access_tuple(
2737 &tx,
2738 // This time we have to load the key by the retrieved key id, because the
2739 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002740 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002741 domain: Domain::KEY_ID,
2742 nspace: key_id,
2743 ..Default::default()
2744 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002745 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002746 caller_uid,
2747 )
2748 .context("In load_key_entry. (deferred key lock)")?;
2749 (key_id_guard, tx)
2750 }
2751 Some(l) => (l, tx),
2752 },
2753 Some(key_id_guard) => (key_id_guard, tx),
2754 };
2755
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002756 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2757 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002758
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002759 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2760
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002761 Ok((key_id_guard, key_entry))
2762 }
2763
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002764 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002765 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002766 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2767 .context("Trying to delete keyentry.")?;
2768 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2769 .context("Trying to delete keymetadata.")?;
2770 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2771 .context("Trying to delete keyparameters.")?;
2772 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2773 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002774 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002775 }
2776
2777 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002778 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002779 pub fn unbind_key(
2780 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002781 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002782 key_type: KeyType,
2783 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002784 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002785 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002786 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2787
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002788 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2789 let (key_id, access_key_descriptor, access_vector) =
2790 Self::load_access_tuple(tx, key, key_type, caller_uid)
2791 .context("Trying to get access tuple.")?;
2792
2793 // Perform access control. It is vital that we return here if the permission is denied.
2794 // So do not touch that '?' at the end.
2795 check_permission(&access_key_descriptor, access_vector)
2796 .context("While checking permission.")?;
2797
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002798 Self::mark_unreferenced(tx, key_id)
2799 .map(|need_gc| (need_gc, ()))
2800 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002801 })
2802 .context("In unbind_key.")
2803 }
2804
Max Bires8e93d2b2021-01-14 13:17:59 -08002805 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2806 tx.query_row(
2807 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2808 params![key_id],
2809 |row| row.get(0),
2810 )
2811 .context("In get_key_km_uuid.")
2812 }
2813
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002814 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2815 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2816 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002817 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2818
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002819 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2820 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2821 .context("In unbind_keys_for_namespace.");
2822 }
2823 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2824 tx.execute(
2825 "DELETE FROM persistent.keymetadata
2826 WHERE keyentryid IN (
2827 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002828 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002829 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002830 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002831 )
2832 .context("Trying to delete keymetadata.")?;
2833 tx.execute(
2834 "DELETE FROM persistent.keyparameter
2835 WHERE keyentryid IN (
2836 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002837 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002838 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002839 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002840 )
2841 .context("Trying to delete keyparameters.")?;
2842 tx.execute(
2843 "DELETE FROM persistent.grant
2844 WHERE keyentryid IN (
2845 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002846 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002847 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002848 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002849 )
2850 .context("Trying to delete grants.")?;
2851 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002852 "DELETE FROM persistent.keyentry
2853 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2854 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002855 )
2856 .context("Trying to delete keyentry.")?;
2857 Ok(()).need_gc()
2858 })
2859 .context("In unbind_keys_for_namespace")
2860 }
2861
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002862 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2863 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2864 {
2865 tx.execute(
2866 "DELETE FROM persistent.keymetadata
2867 WHERE keyentryid IN (
2868 SELECT id FROM persistent.keyentry
2869 WHERE state = ?
2870 );",
2871 params![KeyLifeCycle::Unreferenced],
2872 )
2873 .context("Trying to delete keymetadata.")?;
2874 tx.execute(
2875 "DELETE FROM persistent.keyparameter
2876 WHERE keyentryid IN (
2877 SELECT id FROM persistent.keyentry
2878 WHERE state = ?
2879 );",
2880 params![KeyLifeCycle::Unreferenced],
2881 )
2882 .context("Trying to delete keyparameters.")?;
2883 tx.execute(
2884 "DELETE FROM persistent.grant
2885 WHERE keyentryid IN (
2886 SELECT id FROM persistent.keyentry
2887 WHERE state = ?
2888 );",
2889 params![KeyLifeCycle::Unreferenced],
2890 )
2891 .context("Trying to delete grants.")?;
2892 tx.execute(
2893 "DELETE FROM persistent.keyentry
2894 WHERE state = ?;",
2895 params![KeyLifeCycle::Unreferenced],
2896 )
2897 .context("Trying to delete keyentry.")?;
2898 Result::<()>::Ok(())
2899 }
2900 .context("In cleanup_unreferenced")
2901 }
2902
Hasini Gunasingheda895552021-01-27 19:34:37 +00002903 /// Delete the keys created on behalf of the user, denoted by the user id.
2904 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2905 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2906 /// The caller of this function should notify the gc if the returned value is true.
2907 pub fn unbind_keys_for_user(
2908 &mut self,
2909 user_id: u32,
2910 keep_non_super_encrypted_keys: bool,
2911 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002912 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2913
Hasini Gunasingheda895552021-01-27 19:34:37 +00002914 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2915 let mut stmt = tx
2916 .prepare(&format!(
2917 "SELECT id from persistent.keyentry
2918 WHERE (
2919 key_type = ?
2920 AND domain = ?
2921 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2922 AND state = ?
2923 ) OR (
2924 key_type = ?
2925 AND namespace = ?
2926 AND alias = ?
2927 AND state = ?
2928 );",
2929 aid_user_offset = AID_USER_OFFSET
2930 ))
2931 .context(concat!(
2932 "In unbind_keys_for_user. ",
2933 "Failed to prepare the query to find the keys created by apps."
2934 ))?;
2935
2936 let mut rows = stmt
2937 .query(params![
2938 // WHERE client key:
2939 KeyType::Client,
2940 Domain::APP.0 as u32,
2941 user_id,
2942 KeyLifeCycle::Live,
2943 // OR super key:
2944 KeyType::Super,
2945 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002946 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002947 KeyLifeCycle::Live
2948 ])
2949 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2950
2951 let mut key_ids: Vec<i64> = Vec::new();
2952 db_utils::with_rows_extract_all(&mut rows, |row| {
2953 key_ids
2954 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2955 Ok(())
2956 })
2957 .context("In unbind_keys_for_user.")?;
2958
2959 let mut notify_gc = false;
2960 for key_id in key_ids {
2961 if keep_non_super_encrypted_keys {
2962 // Load metadata and filter out non-super-encrypted keys.
2963 if let (_, Some((_, blob_metadata)), _, _) =
2964 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2965 .context("In unbind_keys_for_user: Trying to load blob info.")?
2966 {
2967 if blob_metadata.encrypted_by().is_none() {
2968 continue;
2969 }
2970 }
2971 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002972 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002973 .context("In unbind_keys_for_user.")?
2974 || notify_gc;
2975 }
2976 Ok(()).do_gc(notify_gc)
2977 })
2978 .context("In unbind_keys_for_user.")
2979 }
2980
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002981 fn load_key_components(
2982 tx: &Transaction,
2983 load_bits: KeyEntryLoadBits,
2984 key_id: i64,
2985 ) -> Result<KeyEntry> {
2986 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2987
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002988 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002989 Self::load_blob_components(key_id, load_bits, &tx)
2990 .context("In load_key_components.")?;
2991
Max Bires8e93d2b2021-01-14 13:17:59 -08002992 let parameters = Self::load_key_parameters(key_id, &tx)
2993 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002994
Max Bires8e93d2b2021-01-14 13:17:59 -08002995 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2996 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002997
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002998 Ok(KeyEntry {
2999 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003000 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003001 cert: cert_blob,
3002 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003003 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003004 parameters,
3005 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003006 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003007 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003008 }
3009
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003010 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3011 /// The key descriptors will have the domain, nspace, and alias field set.
3012 /// Domain must be APP or SELINUX, the caller must make sure of that.
3013 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003014 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3015
Janis Danisevskis66784c42021-01-27 08:40:25 -08003016 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3017 let mut stmt = tx
3018 .prepare(
3019 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003020 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003021 )
3022 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003023
Janis Danisevskis66784c42021-01-27 08:40:25 -08003024 let mut rows = stmt
3025 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
3026 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003027
Janis Danisevskis66784c42021-01-27 08:40:25 -08003028 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3029 db_utils::with_rows_extract_all(&mut rows, |row| {
3030 descriptors.push(KeyDescriptor {
3031 domain,
3032 nspace: namespace,
3033 alias: Some(row.get(0).context("Trying to extract alias.")?),
3034 blob: None,
3035 });
3036 Ok(())
3037 })
3038 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003039 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003040 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003041 }
3042
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003043 /// Adds a grant to the grant table.
3044 /// Like `load_key_entry` this function loads the access tuple before
3045 /// it uses the callback for a permission check. Upon success,
3046 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3047 /// grant table. The new row will have a randomized id, which is used as
3048 /// grant id in the namespace field of the resulting KeyDescriptor.
3049 pub fn grant(
3050 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003051 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003052 caller_uid: u32,
3053 grantee_uid: u32,
3054 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003055 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003056 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003057 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3058
Janis Danisevskis66784c42021-01-27 08:40:25 -08003059 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3060 // Load the key_id and complete the access control tuple.
3061 // We ignore the access vector here because grants cannot be granted.
3062 // The access vector returned here expresses the permissions the
3063 // grantee has if key.domain == Domain::GRANT. But this vector
3064 // cannot include the grant permission by design, so there is no way the
3065 // subsequent permission check can pass.
3066 // We could check key.domain == Domain::GRANT and fail early.
3067 // But even if we load the access tuple by grant here, the permission
3068 // check denies the attempt to create a grant by grant descriptor.
3069 let (key_id, access_key_descriptor, _) =
3070 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3071 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003072
Janis Danisevskis66784c42021-01-27 08:40:25 -08003073 // Perform access control. It is vital that we return here if the permission
3074 // was denied. So do not touch that '?' at the end of the line.
3075 // This permission check checks if the caller has the grant permission
3076 // for the given key and in addition to all of the permissions
3077 // expressed in `access_vector`.
3078 check_permission(&access_key_descriptor, &access_vector)
3079 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003080
Janis Danisevskis66784c42021-01-27 08:40:25 -08003081 let grant_id = if let Some(grant_id) = tx
3082 .query_row(
3083 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003084 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003085 params![key_id, grantee_uid],
3086 |row| row.get(0),
3087 )
3088 .optional()
3089 .context("In grant: Failed get optional existing grant id.")?
3090 {
3091 tx.execute(
3092 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003093 SET access_vector = ?
3094 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003096 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003097 .context("In grant: Failed to update existing grant.")?;
3098 grant_id
3099 } else {
3100 Self::insert_with_retry(|id| {
3101 tx.execute(
3102 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3103 VALUES (?, ?, ?, ?);",
3104 params![id, grantee_uid, key_id, i32::from(access_vector)],
3105 )
3106 })
3107 .context("In grant")?
3108 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003109
Janis Danisevskis66784c42021-01-27 08:40:25 -08003110 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003111 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003112 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003113 }
3114
3115 /// This function checks permissions like `grant` and `load_key_entry`
3116 /// before removing a grant from the grant table.
3117 pub fn ungrant(
3118 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003119 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003120 caller_uid: u32,
3121 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003122 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003123 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003124 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3125
Janis Danisevskis66784c42021-01-27 08:40:25 -08003126 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3127 // Load the key_id and complete the access control tuple.
3128 // We ignore the access vector here because grants cannot be granted.
3129 let (key_id, access_key_descriptor, _) =
3130 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3131 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003132
Janis Danisevskis66784c42021-01-27 08:40:25 -08003133 // Perform access control. We must return here if the permission
3134 // was denied. So do not touch the '?' at the end of this line.
3135 check_permission(&access_key_descriptor)
3136 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003137
Janis Danisevskis66784c42021-01-27 08:40:25 -08003138 tx.execute(
3139 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003140 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003141 params![key_id, grantee_uid],
3142 )
3143 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003144
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003145 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003146 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003147 }
3148
Joel Galenson845f74b2020-09-09 14:11:55 -07003149 // Generates a random id and passes it to the given function, which will
3150 // try to insert it into a database. If that insertion fails, retry;
3151 // otherwise return the id.
3152 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3153 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003154 let newid: i64 = match random() {
3155 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3156 i => i,
3157 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003158 match inserter(newid) {
3159 // If the id already existed, try again.
3160 Err(rusqlite::Error::SqliteFailure(
3161 libsqlite3_sys::Error {
3162 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3163 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3164 },
3165 _,
3166 )) => (),
3167 Err(e) => {
3168 return Err(e).context("In insert_with_retry: failed to insert into database.")
3169 }
3170 _ => return Ok(newid),
3171 }
3172 }
3173 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003174
3175 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
3176 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003177 let _wp = wd::watch_millis("KeystoreDB::insert_auth_token", 500);
3178
Janis Danisevskis66784c42021-01-27 08:40:25 -08003179 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3180 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003181 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
3182 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
3183 params![
3184 auth_token.challenge,
3185 auth_token.userId,
3186 auth_token.authenticatorId,
3187 auth_token.authenticatorType.0 as i32,
3188 auth_token.timestamp.milliSeconds as i64,
3189 auth_token.mac,
3190 MonotonicRawTime::now(),
3191 ],
3192 )
3193 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003194 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003195 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003196 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003197
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003198 /// Find the newest auth token matching the given predicate.
3199 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003200 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003201 p: F,
3202 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
3203 where
3204 F: Fn(&AuthTokenEntry) -> bool,
3205 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003206 let _wp = wd::watch_millis("KeystoreDB::find_auth_token_entry", 500);
3207
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003208 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3209 let mut stmt = tx
3210 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
3211 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003212
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003213 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003214
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003215 while let Some(row) = rows.next().context("Failed to get next row.")? {
3216 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003217 HardwareAuthToken {
3218 challenge: row.get(1)?,
3219 userId: row.get(2)?,
3220 authenticatorId: row.get(3)?,
3221 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3222 timestamp: Timestamp { milliSeconds: row.get(5)? },
3223 mac: row.get(6)?,
3224 },
3225 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003226 );
3227 if p(&entry) {
3228 return Ok(Some((
3229 entry,
3230 Self::get_last_off_body(tx)
3231 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003232 )))
3233 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003234 }
3235 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003236 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003237 })
3238 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003239 }
3240
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003241 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003242 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003243 let _wp = wd::watch_millis("KeystoreDB::insert_last_off_body", 500);
3244
Janis Danisevskis66784c42021-01-27 08:40:25 -08003245 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3246 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003247 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3248 params!["last_off_body", last_off_body],
3249 )
3250 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003251 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003252 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003253 }
3254
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003255 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003256 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003257 let _wp = wd::watch_millis("KeystoreDB::update_last_off_body", 500);
3258
Janis Danisevskis66784c42021-01-27 08:40:25 -08003259 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3260 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003261 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3262 params![last_off_body, "last_off_body"],
3263 )
3264 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003265 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003266 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003267 }
3268
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003269 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003270 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003271 let _wp = wd::watch_millis("KeystoreDB::get_last_off_body", 500);
3272
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003273 tx.query_row(
3274 "SELECT value from perboot.metadata WHERE key = ?;",
3275 params!["last_off_body"],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07003276 |row| row.get(0),
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003277 )
3278 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003279 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003280}
3281
3282#[cfg(test)]
3283mod tests {
3284
3285 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003286 use crate::key_parameter::{
3287 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3288 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3289 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003290 use crate::key_perm_set;
3291 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003292 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003293 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003294 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3295 HardwareAuthToken::HardwareAuthToken,
3296 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003297 };
3298 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003299 Timestamp::Timestamp,
3300 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003301 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003302 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003303 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003304 use std::collections::BTreeMap;
3305 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003306 use std::sync::atomic::{AtomicU8, Ordering};
3307 use std::sync::Arc;
3308 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003309 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003310 #[cfg(disabled)]
3311 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003312
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003313 fn new_test_db() -> Result<KeystoreDB> {
3314 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3315
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003316 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003317 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003318 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003319 })?;
3320 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003321 }
3322
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003323 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3324 where
3325 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3326 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003327 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003328
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003329 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003330 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003331
Janis Danisevskis3395f862021-05-06 10:54:17 -07003332 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003333 }
3334
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003335 fn rebind_alias(
3336 db: &mut KeystoreDB,
3337 newid: &KeyIdGuard,
3338 alias: &str,
3339 domain: Domain,
3340 namespace: i64,
3341 ) -> Result<bool> {
3342 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003343 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003344 })
3345 .context("In rebind_alias.")
3346 }
3347
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003348 #[test]
3349 fn datetime() -> Result<()> {
3350 let conn = Connection::open_in_memory()?;
3351 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3352 let now = SystemTime::now();
3353 let duration = Duration::from_secs(1000);
3354 let then = now.checked_sub(duration).unwrap();
3355 let soon = now.checked_add(duration).unwrap();
3356 conn.execute(
3357 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3358 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3359 )?;
3360 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3361 let mut rows = stmt.query(NO_PARAMS)?;
3362 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3363 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3364 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3365 assert!(rows.next()?.is_none());
3366 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3367 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3368 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3369 Ok(())
3370 }
3371
Joel Galenson0891bc12020-07-20 10:37:03 -07003372 // Ensure that we're using the "injected" random function, not the real one.
3373 #[test]
3374 fn test_mocked_random() {
3375 let rand1 = random();
3376 let rand2 = random();
3377 let rand3 = random();
3378 if rand1 == rand2 {
3379 assert_eq!(rand2 + 1, rand3);
3380 } else {
3381 assert_eq!(rand1 + 1, rand2);
3382 assert_eq!(rand2, rand3);
3383 }
3384 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003385
Joel Galenson26f4d012020-07-17 14:57:21 -07003386 // Test that we have the correct tables.
3387 #[test]
3388 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003389 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003390 let tables = db
3391 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003392 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003393 .query_map(params![], |row| row.get(0))?
3394 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003395 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003396 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003397 assert_eq!(tables[1], "blobmetadata");
3398 assert_eq!(tables[2], "grant");
3399 assert_eq!(tables[3], "keyentry");
3400 assert_eq!(tables[4], "keymetadata");
3401 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003402 let tables = db
3403 .conn
3404 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3405 .query_map(params![], |row| row.get(0))?
3406 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003407
3408 assert_eq!(tables.len(), 2);
3409 assert_eq!(tables[0], "authtoken");
3410 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003411 Ok(())
3412 }
3413
3414 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003415 fn test_auth_token_table_invariant() -> Result<()> {
3416 let mut db = new_test_db()?;
3417 let auth_token1 = HardwareAuthToken {
3418 challenge: i64::MAX,
3419 userId: 200,
3420 authenticatorId: 200,
3421 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3422 timestamp: Timestamp { milliSeconds: 500 },
3423 mac: String::from("mac").into_bytes(),
3424 };
3425 db.insert_auth_token(&auth_token1)?;
3426 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3427 assert_eq!(auth_tokens_returned.len(), 1);
3428
3429 // insert another auth token with the same values for the columns in the UNIQUE constraint
3430 // of the auth token table and different value for timestamp
3431 let auth_token2 = HardwareAuthToken {
3432 challenge: i64::MAX,
3433 userId: 200,
3434 authenticatorId: 200,
3435 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3436 timestamp: Timestamp { milliSeconds: 600 },
3437 mac: String::from("mac").into_bytes(),
3438 };
3439
3440 db.insert_auth_token(&auth_token2)?;
3441 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3442 assert_eq!(auth_tokens_returned.len(), 1);
3443
3444 if let Some(auth_token) = auth_tokens_returned.pop() {
3445 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3446 }
3447
3448 // insert another auth token with the different values for the columns in the UNIQUE
3449 // constraint of the auth token table
3450 let auth_token3 = HardwareAuthToken {
3451 challenge: i64::MAX,
3452 userId: 201,
3453 authenticatorId: 200,
3454 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3455 timestamp: Timestamp { milliSeconds: 600 },
3456 mac: String::from("mac").into_bytes(),
3457 };
3458
3459 db.insert_auth_token(&auth_token3)?;
3460 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3461 assert_eq!(auth_tokens_returned.len(), 2);
3462
3463 Ok(())
3464 }
3465
3466 // utility function for test_auth_token_table_invariant()
3467 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3468 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3469
3470 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3471 .query_map(NO_PARAMS, |row| {
3472 Ok(AuthTokenEntry::new(
3473 HardwareAuthToken {
3474 challenge: row.get(1)?,
3475 userId: row.get(2)?,
3476 authenticatorId: row.get(3)?,
3477 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3478 timestamp: Timestamp { milliSeconds: row.get(5)? },
3479 mac: row.get(6)?,
3480 },
3481 row.get(7)?,
3482 ))
3483 })?
3484 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3485 Ok(auth_token_entries)
3486 }
3487
3488 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003489 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003490 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003491 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003492
Janis Danisevskis66784c42021-01-27 08:40:25 -08003493 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003494 let entries = get_keyentry(&db)?;
3495 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003496
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003497 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003498
3499 let entries_new = get_keyentry(&db)?;
3500 assert_eq!(entries, entries_new);
3501 Ok(())
3502 }
3503
3504 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003505 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003506 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3507 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003508 }
3509
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003510 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003511
Janis Danisevskis66784c42021-01-27 08:40:25 -08003512 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3513 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003514
3515 let entries = get_keyentry(&db)?;
3516 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003517 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3518 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003519
3520 // Test that we must pass in a valid Domain.
3521 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003522 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003523 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003524 );
3525 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003526 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003527 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003528 );
3529 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003530 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003531 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003532 );
3533
3534 Ok(())
3535 }
3536
Joel Galenson33c04ad2020-08-03 11:04:38 -07003537 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003538 fn test_add_unsigned_key() -> Result<()> {
3539 let mut db = new_test_db()?;
3540 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3541 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3542 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3543 db.create_attestation_key_entry(
3544 &public_key,
3545 &raw_public_key,
3546 &private_key,
3547 &KEYSTORE_UUID,
3548 )?;
3549 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3550 assert_eq!(keys.len(), 1);
3551 assert_eq!(keys[0], public_key);
3552 Ok(())
3553 }
3554
3555 #[test]
3556 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3557 let mut db = new_test_db()?;
3558 let expiration_date: i64 = 20;
3559 let namespace: i64 = 30;
3560 let base_byte: u8 = 1;
3561 let loaded_values =
3562 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3563 let chain =
3564 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3565 assert_eq!(true, chain.is_some());
3566 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003567 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003568 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3569 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003570 Ok(())
3571 }
3572
3573 #[test]
3574 fn test_get_attestation_pool_status() -> Result<()> {
3575 let mut db = new_test_db()?;
3576 let namespace: i64 = 30;
3577 load_attestation_key_pool(
3578 &mut db, 10, /* expiration */
3579 namespace, 0x01, /* base_byte */
3580 )?;
3581 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3582 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3583 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3584 assert_eq!(status.expiring, 0);
3585 assert_eq!(status.attested, 3);
3586 assert_eq!(status.unassigned, 0);
3587 assert_eq!(status.total, 3);
3588 assert_eq!(
3589 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3590 1
3591 );
3592 assert_eq!(
3593 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3594 2
3595 );
3596 assert_eq!(
3597 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3598 3
3599 );
3600 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3601 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3602 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3603 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003604 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003605 db.create_attestation_key_entry(
3606 &public_key,
3607 &raw_public_key,
3608 &private_key,
3609 &KEYSTORE_UUID,
3610 )?;
3611 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3612 assert_eq!(status.attested, 3);
3613 assert_eq!(status.unassigned, 0);
3614 assert_eq!(status.total, 4);
3615 db.store_signed_attestation_certificate_chain(
3616 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003617 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003618 &cert_chain,
3619 20,
3620 &KEYSTORE_UUID,
3621 )?;
3622 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3623 assert_eq!(status.attested, 4);
3624 assert_eq!(status.unassigned, 1);
3625 assert_eq!(status.total, 4);
3626 Ok(())
3627 }
3628
3629 #[test]
3630 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003631 let temp_dir =
3632 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3633 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003634 let expiration_date: i64 =
3635 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3636 let namespace: i64 = 30;
3637 let namespace_del1: i64 = 45;
3638 let namespace_del2: i64 = 60;
3639 let entry_values = load_attestation_key_pool(
3640 &mut db,
3641 expiration_date,
3642 namespace,
3643 0x01, /* base_byte */
3644 )?;
3645 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3646 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003647
3648 let blob_entry_row_count: u32 = db
3649 .conn
3650 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3651 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003652 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3653 // one key, one certificate chain, and one certificate.
3654 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003655
Max Bires2b2e6562020-09-22 11:22:36 -07003656 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3657
3658 let mut cert_chain =
3659 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003660 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003661 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003662 assert_eq!(entry_values.batch_cert, value.batch_cert);
3663 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003664 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003665
3666 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3667 Domain::APP,
3668 namespace_del1,
3669 &KEYSTORE_UUID,
3670 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003671 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003672 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3673 Domain::APP,
3674 namespace_del2,
3675 &KEYSTORE_UUID,
3676 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003677 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003678
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003679 // Give the garbage collector half a second to catch up.
3680 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003681
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003682 let blob_entry_row_count: u32 = db
3683 .conn
3684 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3685 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003686 // There shound be 3 blob entries left, because we deleted two of the attestation
3687 // key entries with three blobs each.
3688 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003689
Max Bires2b2e6562020-09-22 11:22:36 -07003690 Ok(())
3691 }
3692
3693 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003694 fn test_delete_all_attestation_keys() -> Result<()> {
3695 let mut db = new_test_db()?;
3696 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3697 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3698 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3699 let result = db.delete_all_attestation_keys()?;
3700
3701 // Give the garbage collector half a second to catch up.
3702 std::thread::sleep(Duration::from_millis(500));
3703
3704 // Attestation keys should be deleted, and the regular key should remain.
3705 assert_eq!(result, 2);
3706
3707 Ok(())
3708 }
3709
3710 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003711 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003712 fn extractor(
3713 ke: &KeyEntryRow,
3714 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3715 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003716 }
3717
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003718 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003719 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3720 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003721 let entries = get_keyentry(&db)?;
3722 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003723 assert_eq!(
3724 extractor(&entries[0]),
3725 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3726 );
3727 assert_eq!(
3728 extractor(&entries[1]),
3729 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3730 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003731
3732 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003733 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003734 let entries = get_keyentry(&db)?;
3735 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003736 assert_eq!(
3737 extractor(&entries[0]),
3738 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3739 );
3740 assert_eq!(
3741 extractor(&entries[1]),
3742 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3743 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003744
3745 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003746 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003747 let entries = get_keyentry(&db)?;
3748 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003749 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3750 assert_eq!(
3751 extractor(&entries[1]),
3752 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3753 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003754
3755 // Test that we must pass in a valid Domain.
3756 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003757 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003758 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003759 );
3760 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003761 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003762 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003763 );
3764 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003765 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003766 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003767 );
3768
3769 // Test that we correctly handle setting an alias for something that does not exist.
3770 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003771 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003772 "Expected to update a single entry but instead updated 0",
3773 );
3774 // Test that we correctly abort the transaction in this case.
3775 let entries = get_keyentry(&db)?;
3776 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003777 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3778 assert_eq!(
3779 extractor(&entries[1]),
3780 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3781 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003782
3783 Ok(())
3784 }
3785
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003786 #[test]
3787 fn test_grant_ungrant() -> Result<()> {
3788 const CALLER_UID: u32 = 15;
3789 const GRANTEE_UID: u32 = 12;
3790 const SELINUX_NAMESPACE: i64 = 7;
3791
3792 let mut db = new_test_db()?;
3793 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003794 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3795 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3796 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003797 )?;
3798 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003799 domain: super::Domain::APP,
3800 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003801 alias: Some("key".to_string()),
3802 blob: None,
3803 };
3804 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3805 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3806
3807 // Reset totally predictable random number generator in case we
3808 // are not the first test running on this thread.
3809 reset_random();
3810 let next_random = 0i64;
3811
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003812 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003813 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003814 assert_eq!(*a, PVEC1);
3815 assert_eq!(
3816 *k,
3817 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003818 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003819 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003820 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003821 alias: Some("key".to_string()),
3822 blob: None,
3823 }
3824 );
3825 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003826 })
3827 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003828
3829 assert_eq!(
3830 app_granted_key,
3831 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003832 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003833 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003834 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003835 alias: None,
3836 blob: None,
3837 }
3838 );
3839
3840 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003841 domain: super::Domain::SELINUX,
3842 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003843 alias: Some("yek".to_string()),
3844 blob: None,
3845 };
3846
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003847 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003848 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003849 assert_eq!(*a, PVEC1);
3850 assert_eq!(
3851 *k,
3852 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003853 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003854 // namespace must be the supplied SELinux
3855 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003856 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003857 alias: Some("yek".to_string()),
3858 blob: None,
3859 }
3860 );
3861 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003862 })
3863 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003864
3865 assert_eq!(
3866 selinux_granted_key,
3867 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003868 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003869 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003870 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003871 alias: None,
3872 blob: None,
3873 }
3874 );
3875
3876 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003877 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003878 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003879 assert_eq!(*a, PVEC2);
3880 assert_eq!(
3881 *k,
3882 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003883 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003884 // namespace must be the supplied SELinux
3885 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003886 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003887 alias: Some("yek".to_string()),
3888 blob: None,
3889 }
3890 );
3891 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003892 })
3893 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003894
3895 assert_eq!(
3896 selinux_granted_key,
3897 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003898 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003899 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003900 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003901 alias: None,
3902 blob: None,
3903 }
3904 );
3905
3906 {
3907 // Limiting scope of stmt, because it borrows db.
3908 let mut stmt = db
3909 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003910 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003911 let mut rows =
3912 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3913 Ok((
3914 row.get(0)?,
3915 row.get(1)?,
3916 row.get(2)?,
3917 KeyPermSet::from(row.get::<_, i32>(3)?),
3918 ))
3919 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003920
3921 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003922 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003923 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003924 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003925 assert!(rows.next().is_none());
3926 }
3927
3928 debug_dump_keyentry_table(&mut db)?;
3929 println!("app_key {:?}", app_key);
3930 println!("selinux_key {:?}", selinux_key);
3931
Janis Danisevskis66784c42021-01-27 08:40:25 -08003932 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3933 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003934
3935 Ok(())
3936 }
3937
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003938 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003939 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3940 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3941
3942 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003943 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003944 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003945 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003946 let mut blob_metadata = BlobMetaData::new();
3947 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3948 db.set_blob(
3949 &key_id,
3950 SubComponentType::KEY_BLOB,
3951 Some(TEST_KEY_BLOB),
3952 Some(&blob_metadata),
3953 )?;
3954 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3955 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003956 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003957
3958 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003959 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003960 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003961 )?;
3962 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003963 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3964 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003965 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003966 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003967 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003968 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003969 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003970 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003971 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003972
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003973 drop(rows);
3974 drop(stmt);
3975
3976 assert_eq!(
3977 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3978 BlobMetaData::load_from_db(id, tx).no_gc()
3979 })
3980 .expect("Should find blob metadata."),
3981 blob_metadata
3982 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003983 Ok(())
3984 }
3985
3986 static TEST_ALIAS: &str = "my super duper key";
3987
3988 #[test]
3989 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3990 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003991 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003992 .context("test_insert_and_load_full_keyentry_domain_app")?
3993 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003994 let (_key_guard, key_entry) = db
3995 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003996 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003997 domain: Domain::APP,
3998 nspace: 0,
3999 alias: Some(TEST_ALIAS.to_string()),
4000 blob: None,
4001 },
4002 KeyType::Client,
4003 KeyEntryLoadBits::BOTH,
4004 1,
4005 |_k, _av| Ok(()),
4006 )
4007 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004008 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004009
4010 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004011 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004012 domain: Domain::APP,
4013 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004014 alias: Some(TEST_ALIAS.to_string()),
4015 blob: None,
4016 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004017 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004018 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004019 |_, _| Ok(()),
4020 )
4021 .unwrap();
4022
4023 assert_eq!(
4024 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4025 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004026 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004027 domain: Domain::APP,
4028 nspace: 0,
4029 alias: Some(TEST_ALIAS.to_string()),
4030 blob: None,
4031 },
4032 KeyType::Client,
4033 KeyEntryLoadBits::NONE,
4034 1,
4035 |_k, _av| Ok(()),
4036 )
4037 .unwrap_err()
4038 .root_cause()
4039 .downcast_ref::<KsError>()
4040 );
4041
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004042 Ok(())
4043 }
4044
4045 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004046 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4047 let mut db = new_test_db()?;
4048
4049 db.store_new_certificate(
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 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004057 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004058 )
4059 .expect("Trying to insert cert.");
4060
4061 let (_key_guard, mut key_entry) = db
4062 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004063 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004064 domain: Domain::APP,
4065 nspace: 1,
4066 alias: Some(TEST_ALIAS.to_string()),
4067 blob: None,
4068 },
4069 KeyType::Client,
4070 KeyEntryLoadBits::PUBLIC,
4071 1,
4072 |_k, _av| Ok(()),
4073 )
4074 .expect("Trying to read certificate entry.");
4075
4076 assert!(key_entry.pure_cert());
4077 assert!(key_entry.cert().is_none());
4078 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4079
4080 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004081 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004082 domain: Domain::APP,
4083 nspace: 1,
4084 alias: Some(TEST_ALIAS.to_string()),
4085 blob: None,
4086 },
4087 KeyType::Client,
4088 1,
4089 |_, _| Ok(()),
4090 )
4091 .unwrap();
4092
4093 assert_eq!(
4094 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4095 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004096 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004097 domain: Domain::APP,
4098 nspace: 1,
4099 alias: Some(TEST_ALIAS.to_string()),
4100 blob: None,
4101 },
4102 KeyType::Client,
4103 KeyEntryLoadBits::NONE,
4104 1,
4105 |_k, _av| Ok(()),
4106 )
4107 .unwrap_err()
4108 .root_cause()
4109 .downcast_ref::<KsError>()
4110 );
4111
4112 Ok(())
4113 }
4114
4115 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004116 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4117 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004118 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004119 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4120 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004121 let (_key_guard, key_entry) = db
4122 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004123 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004124 domain: Domain::SELINUX,
4125 nspace: 1,
4126 alias: Some(TEST_ALIAS.to_string()),
4127 blob: None,
4128 },
4129 KeyType::Client,
4130 KeyEntryLoadBits::BOTH,
4131 1,
4132 |_k, _av| Ok(()),
4133 )
4134 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004135 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004136
4137 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004138 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004139 domain: Domain::SELINUX,
4140 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004141 alias: Some(TEST_ALIAS.to_string()),
4142 blob: None,
4143 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004144 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004145 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004146 |_, _| Ok(()),
4147 )
4148 .unwrap();
4149
4150 assert_eq!(
4151 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4152 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004153 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004154 domain: Domain::SELINUX,
4155 nspace: 1,
4156 alias: Some(TEST_ALIAS.to_string()),
4157 blob: None,
4158 },
4159 KeyType::Client,
4160 KeyEntryLoadBits::NONE,
4161 1,
4162 |_k, _av| Ok(()),
4163 )
4164 .unwrap_err()
4165 .root_cause()
4166 .downcast_ref::<KsError>()
4167 );
4168
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004169 Ok(())
4170 }
4171
4172 #[test]
4173 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4174 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004175 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004176 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4177 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004178 let (_, key_entry) = db
4179 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004180 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004181 KeyType::Client,
4182 KeyEntryLoadBits::BOTH,
4183 1,
4184 |_k, _av| Ok(()),
4185 )
4186 .unwrap();
4187
Qi Wub9433b52020-12-01 14:52:46 +08004188 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004189
4190 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004191 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004192 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004193 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004194 |_, _| Ok(()),
4195 )
4196 .unwrap();
4197
4198 assert_eq!(
4199 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4200 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004201 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004202 KeyType::Client,
4203 KeyEntryLoadBits::NONE,
4204 1,
4205 |_k, _av| Ok(()),
4206 )
4207 .unwrap_err()
4208 .root_cause()
4209 .downcast_ref::<KsError>()
4210 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004211
4212 Ok(())
4213 }
4214
4215 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004216 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4217 let mut db = new_test_db()?;
4218 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4219 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4220 .0;
4221 // Update the usage count of the limited use key.
4222 db.check_and_update_key_usage_count(key_id)?;
4223
4224 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004225 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004226 KeyType::Client,
4227 KeyEntryLoadBits::BOTH,
4228 1,
4229 |_k, _av| Ok(()),
4230 )?;
4231
4232 // The usage count is decremented now.
4233 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4234
4235 Ok(())
4236 }
4237
4238 #[test]
4239 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4240 let mut db = new_test_db()?;
4241 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4242 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4243 .0;
4244 // Update the usage count of the limited use key.
4245 db.check_and_update_key_usage_count(key_id).expect(concat!(
4246 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4247 "This should succeed."
4248 ));
4249
4250 // Try to update the exhausted limited use key.
4251 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4252 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4253 "This should fail."
4254 ));
4255 assert_eq!(
4256 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4257 e.root_cause().downcast_ref::<KsError>().unwrap()
4258 );
4259
4260 Ok(())
4261 }
4262
4263 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004264 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4265 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004266 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004267 .context("test_insert_and_load_full_keyentry_from_grant")?
4268 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004269
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004270 let granted_key = db
4271 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004272 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004273 domain: Domain::APP,
4274 nspace: 0,
4275 alias: Some(TEST_ALIAS.to_string()),
4276 blob: None,
4277 },
4278 1,
4279 2,
4280 key_perm_set![KeyPerm::use_()],
4281 |_k, _av| Ok(()),
4282 )
4283 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004284
4285 debug_dump_grant_table(&mut db)?;
4286
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004287 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004288 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4289 assert_eq!(Domain::GRANT, k.domain);
4290 assert!(av.unwrap().includes(KeyPerm::use_()));
4291 Ok(())
4292 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004293 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004294
Qi Wub9433b52020-12-01 14:52:46 +08004295 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004296
Janis Danisevskis66784c42021-01-27 08:40:25 -08004297 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004298
4299 assert_eq!(
4300 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4301 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004302 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004303 KeyType::Client,
4304 KeyEntryLoadBits::NONE,
4305 2,
4306 |_k, _av| Ok(()),
4307 )
4308 .unwrap_err()
4309 .root_cause()
4310 .downcast_ref::<KsError>()
4311 );
4312
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004313 Ok(())
4314 }
4315
Janis Danisevskis45760022021-01-19 16:34:10 -08004316 // This test attempts to load a key by key id while the caller is not the owner
4317 // but a grant exists for the given key and the caller.
4318 #[test]
4319 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4320 let mut db = new_test_db()?;
4321 const OWNER_UID: u32 = 1u32;
4322 const GRANTEE_UID: u32 = 2u32;
4323 const SOMEONE_ELSE_UID: u32 = 3u32;
4324 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4325 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4326 .0;
4327
4328 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004329 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004330 domain: Domain::APP,
4331 nspace: 0,
4332 alias: Some(TEST_ALIAS.to_string()),
4333 blob: None,
4334 },
4335 OWNER_UID,
4336 GRANTEE_UID,
4337 key_perm_set![KeyPerm::use_()],
4338 |_k, _av| Ok(()),
4339 )
4340 .unwrap();
4341
4342 debug_dump_grant_table(&mut db)?;
4343
4344 let id_descriptor =
4345 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4346
4347 let (_, key_entry) = db
4348 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004349 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004350 KeyType::Client,
4351 KeyEntryLoadBits::BOTH,
4352 GRANTEE_UID,
4353 |k, av| {
4354 assert_eq!(Domain::APP, k.domain);
4355 assert_eq!(OWNER_UID as i64, k.nspace);
4356 assert!(av.unwrap().includes(KeyPerm::use_()));
4357 Ok(())
4358 },
4359 )
4360 .unwrap();
4361
4362 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4363
4364 let (_, key_entry) = db
4365 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004366 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004367 KeyType::Client,
4368 KeyEntryLoadBits::BOTH,
4369 SOMEONE_ELSE_UID,
4370 |k, av| {
4371 assert_eq!(Domain::APP, k.domain);
4372 assert_eq!(OWNER_UID as i64, k.nspace);
4373 assert!(av.is_none());
4374 Ok(())
4375 },
4376 )
4377 .unwrap();
4378
4379 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4380
Janis Danisevskis66784c42021-01-27 08:40:25 -08004381 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004382
4383 assert_eq!(
4384 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4385 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004386 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004387 KeyType::Client,
4388 KeyEntryLoadBits::NONE,
4389 GRANTEE_UID,
4390 |_k, _av| Ok(()),
4391 )
4392 .unwrap_err()
4393 .root_cause()
4394 .downcast_ref::<KsError>()
4395 );
4396
4397 Ok(())
4398 }
4399
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004400 // Creates a key migrates it to a different location and then tries to access it by the old
4401 // and new location.
4402 #[test]
4403 fn test_migrate_key_app_to_app() -> Result<()> {
4404 let mut db = new_test_db()?;
4405 const SOURCE_UID: u32 = 1u32;
4406 const DESTINATION_UID: u32 = 2u32;
4407 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4408 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4409 let key_id_guard =
4410 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4411 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4412
4413 let source_descriptor: KeyDescriptor = KeyDescriptor {
4414 domain: Domain::APP,
4415 nspace: -1,
4416 alias: Some(SOURCE_ALIAS.to_string()),
4417 blob: None,
4418 };
4419
4420 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4421 domain: Domain::APP,
4422 nspace: -1,
4423 alias: Some(DESTINATION_ALIAS.to_string()),
4424 blob: None,
4425 };
4426
4427 let key_id = key_id_guard.id();
4428
4429 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4430 Ok(())
4431 })
4432 .unwrap();
4433
4434 let (_, key_entry) = db
4435 .load_key_entry(
4436 &destination_descriptor,
4437 KeyType::Client,
4438 KeyEntryLoadBits::BOTH,
4439 DESTINATION_UID,
4440 |k, av| {
4441 assert_eq!(Domain::APP, k.domain);
4442 assert_eq!(DESTINATION_UID as i64, k.nspace);
4443 assert!(av.is_none());
4444 Ok(())
4445 },
4446 )
4447 .unwrap();
4448
4449 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4450
4451 assert_eq!(
4452 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4453 db.load_key_entry(
4454 &source_descriptor,
4455 KeyType::Client,
4456 KeyEntryLoadBits::NONE,
4457 SOURCE_UID,
4458 |_k, _av| Ok(()),
4459 )
4460 .unwrap_err()
4461 .root_cause()
4462 .downcast_ref::<KsError>()
4463 );
4464
4465 Ok(())
4466 }
4467
4468 // Creates a key migrates it to a different location and then tries to access it by the old
4469 // and new location.
4470 #[test]
4471 fn test_migrate_key_app_to_selinux() -> Result<()> {
4472 let mut db = new_test_db()?;
4473 const SOURCE_UID: u32 = 1u32;
4474 const DESTINATION_UID: u32 = 2u32;
4475 const DESTINATION_NAMESPACE: i64 = 1000i64;
4476 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4477 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4478 let key_id_guard =
4479 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4480 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4481
4482 let source_descriptor: KeyDescriptor = KeyDescriptor {
4483 domain: Domain::APP,
4484 nspace: -1,
4485 alias: Some(SOURCE_ALIAS.to_string()),
4486 blob: None,
4487 };
4488
4489 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4490 domain: Domain::SELINUX,
4491 nspace: DESTINATION_NAMESPACE,
4492 alias: Some(DESTINATION_ALIAS.to_string()),
4493 blob: None,
4494 };
4495
4496 let key_id = key_id_guard.id();
4497
4498 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4499 Ok(())
4500 })
4501 .unwrap();
4502
4503 let (_, key_entry) = db
4504 .load_key_entry(
4505 &destination_descriptor,
4506 KeyType::Client,
4507 KeyEntryLoadBits::BOTH,
4508 DESTINATION_UID,
4509 |k, av| {
4510 assert_eq!(Domain::SELINUX, k.domain);
4511 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4512 assert!(av.is_none());
4513 Ok(())
4514 },
4515 )
4516 .unwrap();
4517
4518 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4519
4520 assert_eq!(
4521 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4522 db.load_key_entry(
4523 &source_descriptor,
4524 KeyType::Client,
4525 KeyEntryLoadBits::NONE,
4526 SOURCE_UID,
4527 |_k, _av| Ok(()),
4528 )
4529 .unwrap_err()
4530 .root_cause()
4531 .downcast_ref::<KsError>()
4532 );
4533
4534 Ok(())
4535 }
4536
4537 // Creates two keys and tries to migrate the first to the location of the second which
4538 // is expected to fail.
4539 #[test]
4540 fn test_migrate_key_destination_occupied() -> Result<()> {
4541 let mut db = new_test_db()?;
4542 const SOURCE_UID: u32 = 1u32;
4543 const DESTINATION_UID: u32 = 2u32;
4544 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4545 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4546 let key_id_guard =
4547 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4548 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4549 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4550 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4551
4552 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4553 domain: Domain::APP,
4554 nspace: -1,
4555 alias: Some(DESTINATION_ALIAS.to_string()),
4556 blob: None,
4557 };
4558
4559 assert_eq!(
4560 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4561 db.migrate_key_namespace(
4562 key_id_guard,
4563 &destination_descriptor,
4564 DESTINATION_UID,
4565 |_k| Ok(())
4566 )
4567 .unwrap_err()
4568 .root_cause()
4569 .downcast_ref::<KsError>()
4570 );
4571
4572 Ok(())
4573 }
4574
Janis Danisevskisaec14592020-11-12 09:41:49 -08004575 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4576
Janis Danisevskisaec14592020-11-12 09:41:49 -08004577 #[test]
4578 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4579 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004580 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4581 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004582 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004583 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004584 .context("test_insert_and_load_full_keyentry_domain_app")?
4585 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004586 let (_key_guard, key_entry) = db
4587 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004588 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004589 domain: Domain::APP,
4590 nspace: 0,
4591 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4592 blob: None,
4593 },
4594 KeyType::Client,
4595 KeyEntryLoadBits::BOTH,
4596 33,
4597 |_k, _av| Ok(()),
4598 )
4599 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004600 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004601 let state = Arc::new(AtomicU8::new(1));
4602 let state2 = state.clone();
4603
4604 // Spawning a second thread that attempts to acquire the key id lock
4605 // for the same key as the primary thread. The primary thread then
4606 // waits, thereby forcing the secondary thread into the second stage
4607 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4608 // The test succeeds if the secondary thread observes the transition
4609 // of `state` from 1 to 2, despite having a whole second to overtake
4610 // the primary thread.
4611 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004612 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004613 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004614 assert!(db
4615 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004616 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004617 domain: Domain::APP,
4618 nspace: 0,
4619 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4620 blob: None,
4621 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004622 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004623 KeyEntryLoadBits::BOTH,
4624 33,
4625 |_k, _av| Ok(()),
4626 )
4627 .is_ok());
4628 // We should only see a 2 here because we can only return
4629 // from load_key_entry when the `_key_guard` expires,
4630 // which happens at the end of the scope.
4631 assert_eq!(2, state2.load(Ordering::Relaxed));
4632 });
4633
4634 thread::sleep(std::time::Duration::from_millis(1000));
4635
4636 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4637
4638 // Return the handle from this scope so we can join with the
4639 // secondary thread after the key id lock has expired.
4640 handle
4641 // This is where the `_key_guard` goes out of scope,
4642 // which is the reason for concurrent load_key_entry on the same key
4643 // to unblock.
4644 };
4645 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4646 // main test thread. We will not see failing asserts in secondary threads otherwise.
4647 handle.join().unwrap();
4648 Ok(())
4649 }
4650
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004651 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004652 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004653 let temp_dir =
4654 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4655
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004656 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4657 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004658
4659 let _tx1 = db1
4660 .conn
4661 .transaction_with_behavior(TransactionBehavior::Immediate)
4662 .expect("Failed to create first transaction.");
4663
4664 let error = db2
4665 .conn
4666 .transaction_with_behavior(TransactionBehavior::Immediate)
4667 .context("Transaction begin failed.")
4668 .expect_err("This should fail.");
4669 let root_cause = error.root_cause();
4670 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4671 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4672 {
4673 return;
4674 }
4675 panic!(
4676 "Unexpected error {:?} \n{:?} \n{:?}",
4677 error,
4678 root_cause,
4679 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4680 )
4681 }
4682
4683 #[cfg(disabled)]
4684 #[test]
4685 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4686 let temp_dir = Arc::new(
4687 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4688 .expect("Failed to create temp dir."),
4689 );
4690
4691 let test_begin = Instant::now();
4692
4693 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4694 const KEY_COUNT: u32 = 500u32;
4695 const OPEN_DB_COUNT: u32 = 50u32;
4696
4697 let mut actual_key_count = KEY_COUNT;
4698 // First insert KEY_COUNT keys.
4699 for count in 0..KEY_COUNT {
4700 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4701 actual_key_count = count;
4702 break;
4703 }
4704 let alias = format!("test_alias_{}", count);
4705 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4706 .expect("Failed to make key entry.");
4707 }
4708
4709 // Insert more keys from a different thread and into a different namespace.
4710 let temp_dir1 = temp_dir.clone();
4711 let handle1 = thread::spawn(move || {
4712 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4713
4714 for count in 0..actual_key_count {
4715 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4716 return;
4717 }
4718 let alias = format!("test_alias_{}", count);
4719 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4720 .expect("Failed to make key entry.");
4721 }
4722
4723 // then unbind them again.
4724 for count in 0..actual_key_count {
4725 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4726 return;
4727 }
4728 let key = KeyDescriptor {
4729 domain: Domain::APP,
4730 nspace: -1,
4731 alias: Some(format!("test_alias_{}", count)),
4732 blob: None,
4733 };
4734 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4735 }
4736 });
4737
4738 // And start unbinding the first set of keys.
4739 let temp_dir2 = temp_dir.clone();
4740 let handle2 = thread::spawn(move || {
4741 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4742
4743 for count in 0..actual_key_count {
4744 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4745 return;
4746 }
4747 let key = KeyDescriptor {
4748 domain: Domain::APP,
4749 nspace: -1,
4750 alias: Some(format!("test_alias_{}", count)),
4751 blob: None,
4752 };
4753 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4754 }
4755 });
4756
4757 let stop_deleting = Arc::new(AtomicU8::new(0));
4758 let stop_deleting2 = stop_deleting.clone();
4759
4760 // And delete anything that is unreferenced keys.
4761 let temp_dir3 = temp_dir.clone();
4762 let handle3 = thread::spawn(move || {
4763 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4764
4765 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4766 while let Some((key_guard, _key)) =
4767 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4768 {
4769 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4770 return;
4771 }
4772 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4773 }
4774 std::thread::sleep(std::time::Duration::from_millis(100));
4775 }
4776 });
4777
4778 // While a lot of inserting and deleting is going on we have to open database connections
4779 // successfully and use them.
4780 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4781 // out of scope.
4782 #[allow(clippy::redundant_clone)]
4783 let temp_dir4 = temp_dir.clone();
4784 let handle4 = thread::spawn(move || {
4785 for count in 0..OPEN_DB_COUNT {
4786 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4787 return;
4788 }
4789 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4790
4791 let alias = format!("test_alias_{}", count);
4792 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4793 .expect("Failed to make key entry.");
4794 let key = KeyDescriptor {
4795 domain: Domain::APP,
4796 nspace: -1,
4797 alias: Some(alias),
4798 blob: None,
4799 };
4800 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4801 }
4802 });
4803
4804 handle1.join().expect("Thread 1 panicked.");
4805 handle2.join().expect("Thread 2 panicked.");
4806 handle4.join().expect("Thread 4 panicked.");
4807
4808 stop_deleting.store(1, Ordering::Relaxed);
4809 handle3.join().expect("Thread 3 panicked.");
4810
4811 Ok(())
4812 }
4813
4814 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004815 fn list() -> Result<()> {
4816 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004817 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004818 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4819 (Domain::APP, 1, "test1"),
4820 (Domain::APP, 1, "test2"),
4821 (Domain::APP, 1, "test3"),
4822 (Domain::APP, 1, "test4"),
4823 (Domain::APP, 1, "test5"),
4824 (Domain::APP, 1, "test6"),
4825 (Domain::APP, 1, "test7"),
4826 (Domain::APP, 2, "test1"),
4827 (Domain::APP, 2, "test2"),
4828 (Domain::APP, 2, "test3"),
4829 (Domain::APP, 2, "test4"),
4830 (Domain::APP, 2, "test5"),
4831 (Domain::APP, 2, "test6"),
4832 (Domain::APP, 2, "test8"),
4833 (Domain::SELINUX, 100, "test1"),
4834 (Domain::SELINUX, 100, "test2"),
4835 (Domain::SELINUX, 100, "test3"),
4836 (Domain::SELINUX, 100, "test4"),
4837 (Domain::SELINUX, 100, "test5"),
4838 (Domain::SELINUX, 100, "test6"),
4839 (Domain::SELINUX, 100, "test9"),
4840 ];
4841
4842 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4843 .iter()
4844 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004845 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4846 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004847 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4848 });
4849 (entry.id(), *ns)
4850 })
4851 .collect();
4852
4853 for (domain, namespace) in
4854 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4855 {
4856 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4857 .iter()
4858 .filter_map(|(domain, ns, alias)| match ns {
4859 ns if *ns == *namespace => Some(KeyDescriptor {
4860 domain: *domain,
4861 nspace: *ns,
4862 alias: Some(alias.to_string()),
4863 blob: None,
4864 }),
4865 _ => None,
4866 })
4867 .collect();
4868 list_o_descriptors.sort();
4869 let mut list_result = db.list(*domain, *namespace)?;
4870 list_result.sort();
4871 assert_eq!(list_o_descriptors, list_result);
4872
4873 let mut list_o_ids: Vec<i64> = list_o_descriptors
4874 .into_iter()
4875 .map(|d| {
4876 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004877 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004878 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004879 KeyType::Client,
4880 KeyEntryLoadBits::NONE,
4881 *namespace as u32,
4882 |_, _| Ok(()),
4883 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004884 .unwrap();
4885 entry.id()
4886 })
4887 .collect();
4888 list_o_ids.sort_unstable();
4889 let mut loaded_entries: Vec<i64> = list_o_keys
4890 .iter()
4891 .filter_map(|(id, ns)| match ns {
4892 ns if *ns == *namespace => Some(*id),
4893 _ => None,
4894 })
4895 .collect();
4896 loaded_entries.sort_unstable();
4897 assert_eq!(list_o_ids, loaded_entries);
4898 }
4899 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4900
4901 Ok(())
4902 }
4903
Joel Galenson0891bc12020-07-20 10:37:03 -07004904 // Helpers
4905
4906 // Checks that the given result is an error containing the given string.
4907 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4908 let error_str = format!(
4909 "{:#?}",
4910 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4911 );
4912 assert!(
4913 error_str.contains(target),
4914 "The string \"{}\" should contain \"{}\"",
4915 error_str,
4916 target
4917 );
4918 }
4919
Joel Galenson2aab4432020-07-22 15:27:57 -07004920 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004921 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004922 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004923 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004924 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004925 namespace: Option<i64>,
4926 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004927 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004928 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004929 }
4930
4931 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4932 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004933 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004934 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004935 Ok(KeyEntryRow {
4936 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004937 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004938 domain: match row.get(2)? {
4939 Some(i) => Some(Domain(i)),
4940 None => None,
4941 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004942 namespace: row.get(3)?,
4943 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004944 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004945 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004946 })
4947 })?
4948 .map(|r| r.context("Could not read keyentry row."))
4949 .collect::<Result<Vec<_>>>()
4950 }
4951
Max Biresb2e1d032021-02-08 21:35:05 -08004952 struct RemoteProvValues {
4953 cert_chain: Vec<u8>,
4954 priv_key: Vec<u8>,
4955 batch_cert: Vec<u8>,
4956 }
4957
Max Bires2b2e6562020-09-22 11:22:36 -07004958 fn load_attestation_key_pool(
4959 db: &mut KeystoreDB,
4960 expiration_date: i64,
4961 namespace: i64,
4962 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004963 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004964 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4965 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4966 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4967 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004968 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004969 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4970 db.store_signed_attestation_certificate_chain(
4971 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004972 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004973 &cert_chain,
4974 expiration_date,
4975 &KEYSTORE_UUID,
4976 )?;
4977 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004978 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004979 }
4980
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004981 // Note: The parameters and SecurityLevel associations are nonsensical. This
4982 // collection is only used to check if the parameters are preserved as expected by the
4983 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004984 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4985 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004986 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4987 KeyParameter::new(
4988 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4989 SecurityLevel::TRUSTED_ENVIRONMENT,
4990 ),
4991 KeyParameter::new(
4992 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4993 SecurityLevel::TRUSTED_ENVIRONMENT,
4994 ),
4995 KeyParameter::new(
4996 KeyParameterValue::Algorithm(Algorithm::RSA),
4997 SecurityLevel::TRUSTED_ENVIRONMENT,
4998 ),
4999 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5000 KeyParameter::new(
5001 KeyParameterValue::BlockMode(BlockMode::ECB),
5002 SecurityLevel::TRUSTED_ENVIRONMENT,
5003 ),
5004 KeyParameter::new(
5005 KeyParameterValue::BlockMode(BlockMode::GCM),
5006 SecurityLevel::TRUSTED_ENVIRONMENT,
5007 ),
5008 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5009 KeyParameter::new(
5010 KeyParameterValue::Digest(Digest::MD5),
5011 SecurityLevel::TRUSTED_ENVIRONMENT,
5012 ),
5013 KeyParameter::new(
5014 KeyParameterValue::Digest(Digest::SHA_2_224),
5015 SecurityLevel::TRUSTED_ENVIRONMENT,
5016 ),
5017 KeyParameter::new(
5018 KeyParameterValue::Digest(Digest::SHA_2_256),
5019 SecurityLevel::STRONGBOX,
5020 ),
5021 KeyParameter::new(
5022 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5023 SecurityLevel::TRUSTED_ENVIRONMENT,
5024 ),
5025 KeyParameter::new(
5026 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5027 SecurityLevel::TRUSTED_ENVIRONMENT,
5028 ),
5029 KeyParameter::new(
5030 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5031 SecurityLevel::STRONGBOX,
5032 ),
5033 KeyParameter::new(
5034 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5035 SecurityLevel::TRUSTED_ENVIRONMENT,
5036 ),
5037 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5038 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5039 KeyParameter::new(
5040 KeyParameterValue::EcCurve(EcCurve::P_224),
5041 SecurityLevel::TRUSTED_ENVIRONMENT,
5042 ),
5043 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5044 KeyParameter::new(
5045 KeyParameterValue::EcCurve(EcCurve::P_384),
5046 SecurityLevel::TRUSTED_ENVIRONMENT,
5047 ),
5048 KeyParameter::new(
5049 KeyParameterValue::EcCurve(EcCurve::P_521),
5050 SecurityLevel::TRUSTED_ENVIRONMENT,
5051 ),
5052 KeyParameter::new(
5053 KeyParameterValue::RSAPublicExponent(3),
5054 SecurityLevel::TRUSTED_ENVIRONMENT,
5055 ),
5056 KeyParameter::new(
5057 KeyParameterValue::IncludeUniqueID,
5058 SecurityLevel::TRUSTED_ENVIRONMENT,
5059 ),
5060 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5061 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5062 KeyParameter::new(
5063 KeyParameterValue::ActiveDateTime(1234567890),
5064 SecurityLevel::STRONGBOX,
5065 ),
5066 KeyParameter::new(
5067 KeyParameterValue::OriginationExpireDateTime(1234567890),
5068 SecurityLevel::TRUSTED_ENVIRONMENT,
5069 ),
5070 KeyParameter::new(
5071 KeyParameterValue::UsageExpireDateTime(1234567890),
5072 SecurityLevel::TRUSTED_ENVIRONMENT,
5073 ),
5074 KeyParameter::new(
5075 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5076 SecurityLevel::TRUSTED_ENVIRONMENT,
5077 ),
5078 KeyParameter::new(
5079 KeyParameterValue::MaxUsesPerBoot(1234567890),
5080 SecurityLevel::TRUSTED_ENVIRONMENT,
5081 ),
5082 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5083 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5084 KeyParameter::new(
5085 KeyParameterValue::NoAuthRequired,
5086 SecurityLevel::TRUSTED_ENVIRONMENT,
5087 ),
5088 KeyParameter::new(
5089 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5090 SecurityLevel::TRUSTED_ENVIRONMENT,
5091 ),
5092 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5093 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5094 KeyParameter::new(
5095 KeyParameterValue::TrustedUserPresenceRequired,
5096 SecurityLevel::TRUSTED_ENVIRONMENT,
5097 ),
5098 KeyParameter::new(
5099 KeyParameterValue::TrustedConfirmationRequired,
5100 SecurityLevel::TRUSTED_ENVIRONMENT,
5101 ),
5102 KeyParameter::new(
5103 KeyParameterValue::UnlockedDeviceRequired,
5104 SecurityLevel::TRUSTED_ENVIRONMENT,
5105 ),
5106 KeyParameter::new(
5107 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5108 SecurityLevel::SOFTWARE,
5109 ),
5110 KeyParameter::new(
5111 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5112 SecurityLevel::SOFTWARE,
5113 ),
5114 KeyParameter::new(
5115 KeyParameterValue::CreationDateTime(12345677890),
5116 SecurityLevel::SOFTWARE,
5117 ),
5118 KeyParameter::new(
5119 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5120 SecurityLevel::TRUSTED_ENVIRONMENT,
5121 ),
5122 KeyParameter::new(
5123 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5124 SecurityLevel::TRUSTED_ENVIRONMENT,
5125 ),
5126 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5127 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5128 KeyParameter::new(
5129 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5130 SecurityLevel::SOFTWARE,
5131 ),
5132 KeyParameter::new(
5133 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5134 SecurityLevel::TRUSTED_ENVIRONMENT,
5135 ),
5136 KeyParameter::new(
5137 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5138 SecurityLevel::TRUSTED_ENVIRONMENT,
5139 ),
5140 KeyParameter::new(
5141 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5142 SecurityLevel::TRUSTED_ENVIRONMENT,
5143 ),
5144 KeyParameter::new(
5145 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5146 SecurityLevel::TRUSTED_ENVIRONMENT,
5147 ),
5148 KeyParameter::new(
5149 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5150 SecurityLevel::TRUSTED_ENVIRONMENT,
5151 ),
5152 KeyParameter::new(
5153 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5154 SecurityLevel::TRUSTED_ENVIRONMENT,
5155 ),
5156 KeyParameter::new(
5157 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5158 SecurityLevel::TRUSTED_ENVIRONMENT,
5159 ),
5160 KeyParameter::new(
5161 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5162 SecurityLevel::TRUSTED_ENVIRONMENT,
5163 ),
5164 KeyParameter::new(
5165 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5166 SecurityLevel::TRUSTED_ENVIRONMENT,
5167 ),
5168 KeyParameter::new(
5169 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5170 SecurityLevel::TRUSTED_ENVIRONMENT,
5171 ),
5172 KeyParameter::new(
5173 KeyParameterValue::VendorPatchLevel(3),
5174 SecurityLevel::TRUSTED_ENVIRONMENT,
5175 ),
5176 KeyParameter::new(
5177 KeyParameterValue::BootPatchLevel(4),
5178 SecurityLevel::TRUSTED_ENVIRONMENT,
5179 ),
5180 KeyParameter::new(
5181 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5182 SecurityLevel::TRUSTED_ENVIRONMENT,
5183 ),
5184 KeyParameter::new(
5185 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5186 SecurityLevel::TRUSTED_ENVIRONMENT,
5187 ),
5188 KeyParameter::new(
5189 KeyParameterValue::MacLength(256),
5190 SecurityLevel::TRUSTED_ENVIRONMENT,
5191 ),
5192 KeyParameter::new(
5193 KeyParameterValue::ResetSinceIdRotation,
5194 SecurityLevel::TRUSTED_ENVIRONMENT,
5195 ),
5196 KeyParameter::new(
5197 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5198 SecurityLevel::TRUSTED_ENVIRONMENT,
5199 ),
Qi Wub9433b52020-12-01 14:52:46 +08005200 ];
5201 if let Some(value) = max_usage_count {
5202 params.push(KeyParameter::new(
5203 KeyParameterValue::UsageCountLimit(value),
5204 SecurityLevel::SOFTWARE,
5205 ));
5206 }
5207 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005208 }
5209
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005210 fn make_test_key_entry(
5211 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005212 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005213 namespace: i64,
5214 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005215 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005216 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005217 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005218 let mut blob_metadata = BlobMetaData::new();
5219 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5220 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5221 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5222 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5223 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5224
5225 db.set_blob(
5226 &key_id,
5227 SubComponentType::KEY_BLOB,
5228 Some(TEST_KEY_BLOB),
5229 Some(&blob_metadata),
5230 )?;
5231 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5232 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005233
5234 let params = make_test_params(max_usage_count);
5235 db.insert_keyparameter(&key_id, &params)?;
5236
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005237 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005238 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005239 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005240 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005241 Ok(key_id)
5242 }
5243
Qi Wub9433b52020-12-01 14:52:46 +08005244 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5245 let params = make_test_params(max_usage_count);
5246
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005247 let mut blob_metadata = BlobMetaData::new();
5248 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5249 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5250 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5251 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5252 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5253
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005254 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005255 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005256
5257 KeyEntry {
5258 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005259 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005260 cert: Some(TEST_CERT_BLOB.to_vec()),
5261 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005262 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005263 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005264 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005265 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005266 }
5267 }
5268
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005269 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005270 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005271 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005272 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005273 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005274 NO_PARAMS,
5275 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005276 Ok((
5277 row.get(0)?,
5278 row.get(1)?,
5279 row.get(2)?,
5280 row.get(3)?,
5281 row.get(4)?,
5282 row.get(5)?,
5283 row.get(6)?,
5284 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005285 },
5286 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005287
5288 println!("Key entry table rows:");
5289 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005290 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005291 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005292 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5293 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005294 );
5295 }
5296 Ok(())
5297 }
5298
5299 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005300 let mut stmt = db
5301 .conn
5302 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005303 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5304 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5305 })?;
5306
5307 println!("Grant table rows:");
5308 for r in rows {
5309 let (id, gt, ki, av) = r.unwrap();
5310 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5311 }
5312 Ok(())
5313 }
5314
Joel Galenson0891bc12020-07-20 10:37:03 -07005315 // Use a custom random number generator that repeats each number once.
5316 // This allows us to test repeated elements.
5317
5318 thread_local! {
5319 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5320 }
5321
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005322 fn reset_random() {
5323 RANDOM_COUNTER.with(|counter| {
5324 *counter.borrow_mut() = 0;
5325 })
5326 }
5327
Joel Galenson0891bc12020-07-20 10:37:03 -07005328 pub fn random() -> i64 {
5329 RANDOM_COUNTER.with(|counter| {
5330 let result = *counter.borrow() / 2;
5331 *counter.borrow_mut() += 1;
5332 result
5333 })
5334 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005335
5336 #[test]
5337 fn test_last_off_body() -> Result<()> {
5338 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005339 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005340 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5341 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5342 tx.commit()?;
5343 let one_second = Duration::from_secs(1);
5344 thread::sleep(one_second);
5345 db.update_last_off_body(MonotonicRawTime::now())?;
5346 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5347 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5348 tx2.commit()?;
5349 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5350 Ok(())
5351 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005352
5353 #[test]
5354 fn test_unbind_keys_for_user() -> Result<()> {
5355 let mut db = new_test_db()?;
5356 db.unbind_keys_for_user(1, false)?;
5357
5358 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5359 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5360 db.unbind_keys_for_user(2, false)?;
5361
5362 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5363 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5364
5365 db.unbind_keys_for_user(1, true)?;
5366 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5367
5368 Ok(())
5369 }
5370
5371 #[test]
5372 fn test_store_super_key() -> Result<()> {
5373 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005374 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005375 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005376 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005377 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005378 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005379
5380 let (encrypted_super_key, metadata) =
5381 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005382 db.store_super_key(
5383 1,
5384 &USER_SUPER_KEY,
5385 &encrypted_super_key,
5386 &metadata,
5387 &KeyMetaData::new(),
5388 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005389
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005390 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005391 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005392
Paul Crowley7a658392021-03-18 17:08:20 -07005393 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005394 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5395 USER_SUPER_KEY.algorithm,
5396 key_entry,
5397 &pw,
5398 None,
5399 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005400
Paul Crowley7a658392021-03-18 17:08:20 -07005401 let decrypted_secret_bytes =
5402 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5403 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005404 Ok(())
5405 }
Seth Moore78c091f2021-04-09 21:38:30 +00005406
5407 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5408 vec![
5409 StatsdStorageType::KeyEntry,
5410 StatsdStorageType::KeyEntryIdIndex,
5411 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5412 StatsdStorageType::BlobEntry,
5413 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5414 StatsdStorageType::KeyParameter,
5415 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5416 StatsdStorageType::KeyMetadata,
5417 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5418 StatsdStorageType::Grant,
5419 StatsdStorageType::AuthToken,
5420 StatsdStorageType::BlobMetadata,
5421 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5422 ]
5423 }
5424
5425 /// Perform a simple check to ensure that we can query all the storage types
5426 /// that are supported by the DB. Check for reasonable values.
5427 #[test]
5428 fn test_query_all_valid_table_sizes() -> Result<()> {
5429 const PAGE_SIZE: i64 = 4096;
5430
5431 let mut db = new_test_db()?;
5432
5433 for t in get_valid_statsd_storage_types() {
5434 let stat = db.get_storage_stat(t)?;
5435 assert!(stat.size >= PAGE_SIZE);
5436 assert!(stat.size >= stat.unused_size);
5437 }
5438
5439 Ok(())
5440 }
5441
5442 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5443 get_valid_statsd_storage_types()
5444 .into_iter()
5445 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5446 .collect()
5447 }
5448
5449 fn assert_storage_increased(
5450 db: &mut KeystoreDB,
5451 increased_storage_types: Vec<StatsdStorageType>,
5452 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5453 ) {
5454 for storage in increased_storage_types {
5455 // Verify the expected storage increased.
5456 let new = db.get_storage_stat(storage).unwrap();
5457 let storage = storage as i32;
5458 let old = &baseline[&storage];
5459 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5460 assert!(
5461 new.unused_size <= old.unused_size,
5462 "{}: {} <= {}",
5463 storage,
5464 new.unused_size,
5465 old.unused_size
5466 );
5467
5468 // Update the baseline with the new value so that it succeeds in the
5469 // later comparison.
5470 baseline.insert(storage, new);
5471 }
5472
5473 // Get an updated map of the storage and verify there were no unexpected changes.
5474 let updated_stats = get_storage_stats_map(db);
5475 assert_eq!(updated_stats.len(), baseline.len());
5476
5477 for &k in baseline.keys() {
5478 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5479 let mut s = String::new();
5480 for &k in map.keys() {
5481 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5482 .expect("string concat failed");
5483 }
5484 s
5485 };
5486
5487 assert!(
5488 updated_stats[&k].size == baseline[&k].size
5489 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5490 "updated_stats:\n{}\nbaseline:\n{}",
5491 stringify(&updated_stats),
5492 stringify(&baseline)
5493 );
5494 }
5495 }
5496
5497 #[test]
5498 fn test_verify_key_table_size_reporting() -> Result<()> {
5499 let mut db = new_test_db()?;
5500 let mut working_stats = get_storage_stats_map(&mut db);
5501
5502 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5503 assert_storage_increased(
5504 &mut db,
5505 vec![
5506 StatsdStorageType::KeyEntry,
5507 StatsdStorageType::KeyEntryIdIndex,
5508 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5509 ],
5510 &mut working_stats,
5511 );
5512
5513 let mut blob_metadata = BlobMetaData::new();
5514 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5515 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5516 assert_storage_increased(
5517 &mut db,
5518 vec![
5519 StatsdStorageType::BlobEntry,
5520 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5521 StatsdStorageType::BlobMetadata,
5522 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5523 ],
5524 &mut working_stats,
5525 );
5526
5527 let params = make_test_params(None);
5528 db.insert_keyparameter(&key_id, &params)?;
5529 assert_storage_increased(
5530 &mut db,
5531 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5532 &mut working_stats,
5533 );
5534
5535 let mut metadata = KeyMetaData::new();
5536 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5537 db.insert_key_metadata(&key_id, &metadata)?;
5538 assert_storage_increased(
5539 &mut db,
5540 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5541 &mut working_stats,
5542 );
5543
5544 let mut sum = 0;
5545 for stat in working_stats.values() {
5546 sum += stat.size;
5547 }
5548 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5549 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5550
5551 Ok(())
5552 }
5553
5554 #[test]
5555 fn test_verify_auth_table_size_reporting() -> Result<()> {
5556 let mut db = new_test_db()?;
5557 let mut working_stats = get_storage_stats_map(&mut db);
5558 db.insert_auth_token(&HardwareAuthToken {
5559 challenge: 123,
5560 userId: 456,
5561 authenticatorId: 789,
5562 authenticatorType: kmhw_authenticator_type::ANY,
5563 timestamp: Timestamp { milliSeconds: 10 },
5564 mac: b"mac".to_vec(),
5565 })?;
5566 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5567 Ok(())
5568 }
5569
5570 #[test]
5571 fn test_verify_grant_table_size_reporting() -> Result<()> {
5572 const OWNER: i64 = 1;
5573 let mut db = new_test_db()?;
5574 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5575
5576 let mut working_stats = get_storage_stats_map(&mut db);
5577 db.grant(
5578 &KeyDescriptor {
5579 domain: Domain::APP,
5580 nspace: 0,
5581 alias: Some(TEST_ALIAS.to_string()),
5582 blob: None,
5583 },
5584 OWNER as u32,
5585 123,
5586 key_perm_set![KeyPerm::use_()],
5587 |_, _| Ok(()),
5588 )?;
5589
5590 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5591
5592 Ok(())
5593 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005594}