blob: e62ec4e53adebd5765448fc5780b8c1f5c61ad8b [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
Jeff Vander Stoep46bbc612021-04-09 08:55:21 +020044#![allow(clippy::needless_question_mark)]
45
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080047use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070048use crate::permission::KeyPermSet;
Janis Danisevskis850d4862021-05-05 08:41:14 -070049use crate::utils::{get_current_time_in_seconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080050use crate::{
51 db_utils::{self, SqlField},
52 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070053 super_key::USER_SUPER_KEY,
54};
55use crate::{
56 error::{Error as KsError, ErrorCode, ResponseCode},
57 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080058};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080059use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080060use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070061
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080063 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080065};
66use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000067 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000068};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070069use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070070 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070071};
Max Bires2b2e6562020-09-22 11:22:36 -070072use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
73 AttestationPoolStatus::AttestationPoolStatus,
74};
Seth Moore78c091f2021-04-09 21:38:30 +000075use statslog_rust::keystore2_storage_stats::{
76 Keystore2StorageStats, StorageType as StatsdStorageType,
77};
Max Bires2b2e6562020-09-22 11:22:36 -070078
79use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080080use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000081use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070082#[cfg(not(test))]
83use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070084use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080085 params,
86 types::FromSql,
87 types::FromSqlResult,
88 types::ToSqlOutput,
89 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080090 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070091};
Max Bires2b2e6562020-09-22 11:22:36 -070092
Janis Danisevskisaec14592020-11-12 09:41:49 -080093use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080095 path::Path,
96 sync::{Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080097 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080098};
Max Bires2b2e6562020-09-22 11:22:36 -070099
Joel Galenson0891bc12020-07-20 10:37:03 -0700100#[cfg(test)]
101use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -0700102
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800103impl_metadata!(
104 /// A set of metadata for key entries.
105 #[derive(Debug, Default, Eq, PartialEq)]
106 pub struct KeyMetaData;
107 /// A metadata entry for key entries.
108 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
109 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800110 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800111 CreationDate(DateTime) with accessor creation_date,
112 /// Expiration date for attestation keys.
113 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700114 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
115 /// provisioning
116 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
117 /// Vector representing the raw public key so results from the server can be matched
118 /// to the right entry
119 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700120 /// SEC1 public key for ECDH encryption
121 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800122 // --- ADD NEW META DATA FIELDS HERE ---
123 // For backwards compatibility add new entries only to
124 // end of this list and above this comment.
125 };
126);
127
128impl KeyMetaData {
129 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
130 let mut stmt = tx
131 .prepare(
132 "SELECT tag, data from persistent.keymetadata
133 WHERE keyentryid = ?;",
134 )
135 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
136
137 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
138
139 let mut rows =
140 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
141 db_utils::with_rows_extract_all(&mut rows, |row| {
142 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
143 metadata.insert(
144 db_tag,
145 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
146 .context("Failed to read KeyMetaEntry.")?,
147 );
148 Ok(())
149 })
150 .context("In KeyMetaData::load_from_db.")?;
151
152 Ok(Self { data: metadata })
153 }
154
155 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
156 let mut stmt = tx
157 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000158 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800159 VALUES (?, ?, ?);",
160 )
161 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
162
163 let iter = self.data.iter();
164 for (tag, entry) in iter {
165 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
166 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
167 })?;
168 }
169 Ok(())
170 }
171}
172
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800173impl_metadata!(
174 /// A set of metadata for key blobs.
175 #[derive(Debug, Default, Eq, PartialEq)]
176 pub struct BlobMetaData;
177 /// A metadata entry for key blobs.
178 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
179 pub enum BlobMetaEntry {
180 /// If present, indicates that the blob is encrypted with another key or a key derived
181 /// from a password.
182 EncryptedBy(EncryptedBy) with accessor encrypted_by,
183 /// If the blob is password encrypted this field is set to the
184 /// salt used for the key derivation.
185 Salt(Vec<u8>) with accessor salt,
186 /// If the blob is encrypted, this field is set to the initialization vector.
187 Iv(Vec<u8>) with accessor iv,
188 /// If the blob is encrypted, this field holds the AEAD TAG.
189 AeadTag(Vec<u8>) with accessor aead_tag,
190 /// The uuid of the owning KeyMint instance.
191 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700192 /// If the key is ECDH encrypted, this is the ephemeral public key
193 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000194 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
195 /// of that key
196 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800197 // --- ADD NEW META DATA FIELDS HERE ---
198 // For backwards compatibility add new entries only to
199 // end of this list and above this comment.
200 };
201);
202
203impl BlobMetaData {
204 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
205 let mut stmt = tx
206 .prepare(
207 "SELECT tag, data from persistent.blobmetadata
208 WHERE blobentryid = ?;",
209 )
210 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
211
212 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
213
214 let mut rows =
215 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
216 db_utils::with_rows_extract_all(&mut rows, |row| {
217 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
218 metadata.insert(
219 db_tag,
220 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
221 .context("Failed to read BlobMetaEntry.")?,
222 );
223 Ok(())
224 })
225 .context("In BlobMetaData::load_from_db.")?;
226
227 Ok(Self { data: metadata })
228 }
229
230 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
231 let mut stmt = tx
232 .prepare(
233 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
234 VALUES (?, ?, ?);",
235 )
236 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
237
238 let iter = self.data.iter();
239 for (tag, entry) in iter {
240 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
241 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
242 })?;
243 }
244 Ok(())
245 }
246}
247
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800248/// Indicates the type of the keyentry.
249#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
250pub enum KeyType {
251 /// This is a client key type. These keys are created or imported through the Keystore 2.0
252 /// AIDL interface android.system.keystore2.
253 Client,
254 /// This is a super key type. These keys are created by keystore itself and used to encrypt
255 /// other key blobs to provide LSKF binding.
256 Super,
257 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
258 Attestation,
259}
260
261impl ToSql for KeyType {
262 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
263 Ok(ToSqlOutput::Owned(Value::Integer(match self {
264 KeyType::Client => 0,
265 KeyType::Super => 1,
266 KeyType::Attestation => 2,
267 })))
268 }
269}
270
271impl FromSql for KeyType {
272 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
273 match i64::column_result(value)? {
274 0 => Ok(KeyType::Client),
275 1 => Ok(KeyType::Super),
276 2 => Ok(KeyType::Attestation),
277 v => Err(FromSqlError::OutOfRange(v)),
278 }
279 }
280}
281
Max Bires8e93d2b2021-01-14 13:17:59 -0800282/// Uuid representation that can be stored in the database.
283/// Right now it can only be initialized from SecurityLevel.
284/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
285#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
286pub struct Uuid([u8; 16]);
287
288impl Deref for Uuid {
289 type Target = [u8; 16];
290
291 fn deref(&self) -> &Self::Target {
292 &self.0
293 }
294}
295
296impl From<SecurityLevel> for Uuid {
297 fn from(sec_level: SecurityLevel) -> Self {
298 Self((sec_level.0 as u128).to_be_bytes())
299 }
300}
301
302impl ToSql for Uuid {
303 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
304 self.0.to_sql()
305 }
306}
307
308impl FromSql for Uuid {
309 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
310 let blob = Vec::<u8>::column_result(value)?;
311 if blob.len() != 16 {
312 return Err(FromSqlError::OutOfRange(blob.len() as i64));
313 }
314 let mut arr = [0u8; 16];
315 arr.copy_from_slice(&blob);
316 Ok(Self(arr))
317 }
318}
319
320/// Key entries that are not associated with any KeyMint instance, such as pure certificate
321/// entries are associated with this UUID.
322pub static KEYSTORE_UUID: Uuid = Uuid([
323 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
324]);
325
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800326/// Indicates how the sensitive part of this key blob is encrypted.
327#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
328pub enum EncryptedBy {
329 /// The keyblob is encrypted by a user password.
330 /// In the database this variant is represented as NULL.
331 Password,
332 /// The keyblob is encrypted by another key with wrapped key id.
333 /// In the database this variant is represented as non NULL value
334 /// that is convertible to i64, typically NUMERIC.
335 KeyId(i64),
336}
337
338impl ToSql for EncryptedBy {
339 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
340 match self {
341 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
342 Self::KeyId(id) => id.to_sql(),
343 }
344 }
345}
346
347impl FromSql for EncryptedBy {
348 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
349 match value {
350 ValueRef::Null => Ok(Self::Password),
351 _ => Ok(Self::KeyId(i64::column_result(value)?)),
352 }
353 }
354}
355
356/// A database representation of wall clock time. DateTime stores unix epoch time as
357/// i64 in milliseconds.
358#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
359pub struct DateTime(i64);
360
361/// Error type returned when creating DateTime or converting it from and to
362/// SystemTime.
363#[derive(thiserror::Error, Debug)]
364pub enum DateTimeError {
365 /// This is returned when SystemTime and Duration computations fail.
366 #[error(transparent)]
367 SystemTimeError(#[from] SystemTimeError),
368
369 /// This is returned when type conversions fail.
370 #[error(transparent)]
371 TypeConversion(#[from] std::num::TryFromIntError),
372
373 /// This is returned when checked time arithmetic failed.
374 #[error("Time arithmetic failed.")]
375 TimeArithmetic,
376}
377
378impl DateTime {
379 /// Constructs a new DateTime object denoting the current time. This may fail during
380 /// conversion to unix epoch time and during conversion to the internal i64 representation.
381 pub fn now() -> Result<Self, DateTimeError> {
382 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
383 }
384
385 /// Constructs a new DateTime object from milliseconds.
386 pub fn from_millis_epoch(millis: i64) -> Self {
387 Self(millis)
388 }
389
390 /// Returns unix epoch time in milliseconds.
391 pub fn to_millis_epoch(&self) -> i64 {
392 self.0
393 }
394
395 /// Returns unix epoch time in seconds.
396 pub fn to_secs_epoch(&self) -> i64 {
397 self.0 / 1000
398 }
399}
400
401impl ToSql for DateTime {
402 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
403 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
404 }
405}
406
407impl FromSql for DateTime {
408 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
409 Ok(Self(i64::column_result(value)?))
410 }
411}
412
413impl TryInto<SystemTime> for DateTime {
414 type Error = DateTimeError;
415
416 fn try_into(self) -> Result<SystemTime, Self::Error> {
417 // We want to construct a SystemTime representation equivalent to self, denoting
418 // a point in time THEN, but we cannot set the time directly. We can only construct
419 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
420 // and between EPOCH and THEN. With this common reference we can construct the
421 // duration between NOW and THEN which we can add to our SystemTime representation
422 // of NOW to get a SystemTime representation of THEN.
423 // Durations can only be positive, thus the if statement below.
424 let now = SystemTime::now();
425 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
426 let then_epoch = Duration::from_millis(self.0.try_into()?);
427 Ok(if now_epoch > then_epoch {
428 // then = now - (now_epoch - then_epoch)
429 now_epoch
430 .checked_sub(then_epoch)
431 .and_then(|d| now.checked_sub(d))
432 .ok_or(DateTimeError::TimeArithmetic)?
433 } else {
434 // then = now + (then_epoch - now_epoch)
435 then_epoch
436 .checked_sub(now_epoch)
437 .and_then(|d| now.checked_add(d))
438 .ok_or(DateTimeError::TimeArithmetic)?
439 })
440 }
441}
442
443impl TryFrom<SystemTime> for DateTime {
444 type Error = DateTimeError;
445
446 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
447 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
448 }
449}
450
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800451#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
452enum KeyLifeCycle {
453 /// Existing keys have a key ID but are not fully populated yet.
454 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
455 /// them to Unreferenced for garbage collection.
456 Existing,
457 /// A live key is fully populated and usable by clients.
458 Live,
459 /// An unreferenced key is scheduled for garbage collection.
460 Unreferenced,
461}
462
463impl ToSql for KeyLifeCycle {
464 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
465 match self {
466 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
467 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
468 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
469 }
470 }
471}
472
473impl FromSql for KeyLifeCycle {
474 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
475 match i64::column_result(value)? {
476 0 => Ok(KeyLifeCycle::Existing),
477 1 => Ok(KeyLifeCycle::Live),
478 2 => Ok(KeyLifeCycle::Unreferenced),
479 v => Err(FromSqlError::OutOfRange(v)),
480 }
481 }
482}
483
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700484/// Keys have a KeyMint blob component and optional public certificate and
485/// certificate chain components.
486/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
487/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800488#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700489pub struct KeyEntryLoadBits(u32);
490
491impl KeyEntryLoadBits {
492 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
493 pub const NONE: KeyEntryLoadBits = Self(0);
494 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
495 pub const KM: KeyEntryLoadBits = Self(1);
496 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
497 pub const PUBLIC: KeyEntryLoadBits = Self(2);
498 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
499 pub const BOTH: KeyEntryLoadBits = Self(3);
500
501 /// Returns true if this object indicates that the public components shall be loaded.
502 pub const fn load_public(&self) -> bool {
503 self.0 & Self::PUBLIC.0 != 0
504 }
505
506 /// Returns true if the object indicates that the KeyMint component shall be loaded.
507 pub const fn load_km(&self) -> bool {
508 self.0 & Self::KM.0 != 0
509 }
510}
511
Janis Danisevskisaec14592020-11-12 09:41:49 -0800512lazy_static! {
513 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
514}
515
516struct KeyIdLockDb {
517 locked_keys: Mutex<HashSet<i64>>,
518 cond_var: Condvar,
519}
520
521/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
522/// from the database a second time. Most functions manipulating the key blob database
523/// require a KeyIdGuard.
524#[derive(Debug)]
525pub struct KeyIdGuard(i64);
526
527impl KeyIdLockDb {
528 fn new() -> Self {
529 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
530 }
531
532 /// This function blocks until an exclusive lock for the given key entry id can
533 /// be acquired. It returns a guard object, that represents the lifecycle of the
534 /// acquired lock.
535 pub fn get(&self, key_id: i64) -> KeyIdGuard {
536 let mut locked_keys = self.locked_keys.lock().unwrap();
537 while locked_keys.contains(&key_id) {
538 locked_keys = self.cond_var.wait(locked_keys).unwrap();
539 }
540 locked_keys.insert(key_id);
541 KeyIdGuard(key_id)
542 }
543
544 /// This function attempts to acquire an exclusive lock on a given key id. If the
545 /// given key id is already taken the function returns None immediately. If a lock
546 /// can be acquired this function returns a guard object, that represents the
547 /// lifecycle of the acquired lock.
548 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
549 let mut locked_keys = self.locked_keys.lock().unwrap();
550 if locked_keys.insert(key_id) {
551 Some(KeyIdGuard(key_id))
552 } else {
553 None
554 }
555 }
556}
557
558impl KeyIdGuard {
559 /// Get the numeric key id of the locked key.
560 pub fn id(&self) -> i64 {
561 self.0
562 }
563}
564
565impl Drop for KeyIdGuard {
566 fn drop(&mut self) {
567 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
568 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800569 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800570 KEY_ID_LOCK.cond_var.notify_all();
571 }
572}
573
Max Bires8e93d2b2021-01-14 13:17:59 -0800574/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700575#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800576pub struct CertificateInfo {
577 cert: Option<Vec<u8>>,
578 cert_chain: Option<Vec<u8>>,
579}
580
581impl CertificateInfo {
582 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
583 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
584 Self { cert, cert_chain }
585 }
586
587 /// Take the cert
588 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
589 self.cert.take()
590 }
591
592 /// Take the cert chain
593 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
594 self.cert_chain.take()
595 }
596}
597
Max Bires2b2e6562020-09-22 11:22:36 -0700598/// This type represents a certificate chain with a private key corresponding to the leaf
599/// 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 -0700600pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800601 /// A KM key blob
602 pub private_key: ZVec,
603 /// A batch cert for private_key
604 pub batch_cert: Vec<u8>,
605 /// A full certificate chain from root signing authority to private_key, including batch_cert
606 /// for convenience.
607 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700608}
609
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700610/// This type represents a Keystore 2.0 key entry.
611/// An entry has a unique `id` by which it can be found in the database.
612/// It has a security level field, key parameters, and three optional fields
613/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800614#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615pub struct KeyEntry {
616 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800617 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700618 cert: Option<Vec<u8>>,
619 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800620 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700621 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800622 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800623 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700624}
625
626impl KeyEntry {
627 /// Returns the unique id of the Key entry.
628 pub fn id(&self) -> i64 {
629 self.id
630 }
631 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
633 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700634 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800635 /// Extracts the Optional KeyMint blob including its metadata.
636 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
637 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700638 }
639 /// Exposes the optional public certificate.
640 pub fn cert(&self) -> &Option<Vec<u8>> {
641 &self.cert
642 }
643 /// Extracts the optional public certificate.
644 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
645 self.cert.take()
646 }
647 /// Exposes the optional public certificate chain.
648 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
649 &self.cert_chain
650 }
651 /// Extracts the optional public certificate_chain.
652 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
653 self.cert_chain.take()
654 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800655 /// Returns the uuid of the owning KeyMint instance.
656 pub fn km_uuid(&self) -> &Uuid {
657 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700658 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700659 /// Exposes the key parameters of this key entry.
660 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
661 &self.parameters
662 }
663 /// Consumes this key entry and extracts the keyparameters from it.
664 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
665 self.parameters
666 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800667 /// Exposes the key metadata of this key entry.
668 pub fn metadata(&self) -> &KeyMetaData {
669 &self.metadata
670 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800671 /// This returns true if the entry is a pure certificate entry with no
672 /// private key component.
673 pub fn pure_cert(&self) -> bool {
674 self.pure_cert
675 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000676 /// Consumes this key entry and extracts the keyparameters and metadata from it.
677 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
678 (self.parameters, self.metadata)
679 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700680}
681
682/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800683#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700684pub struct SubComponentType(u32);
685impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800686 /// Persistent identifier for a key blob.
687 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700688 /// Persistent identifier for a certificate blob.
689 pub const CERT: SubComponentType = Self(1);
690 /// Persistent identifier for a certificate chain blob.
691 pub const CERT_CHAIN: SubComponentType = Self(2);
692}
693
694impl ToSql for SubComponentType {
695 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
696 self.0.to_sql()
697 }
698}
699
700impl FromSql for SubComponentType {
701 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
702 Ok(Self(u32::column_result(value)?))
703 }
704}
705
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800706/// This trait is private to the database module. It is used to convey whether or not the garbage
707/// collector shall be invoked after a database access. All closures passed to
708/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
709/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
710/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
711/// `.need_gc()`.
712trait DoGc<T> {
713 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
714
715 fn no_gc(self) -> Result<(bool, T)>;
716
717 fn need_gc(self) -> Result<(bool, T)>;
718}
719
720impl<T> DoGc<T> for Result<T> {
721 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
722 self.map(|r| (need_gc, r))
723 }
724
725 fn no_gc(self) -> Result<(bool, T)> {
726 self.do_gc(false)
727 }
728
729 fn need_gc(self) -> Result<(bool, T)> {
730 self.do_gc(true)
731 }
732}
733
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700734/// KeystoreDB wraps a connection to an SQLite database and tracks its
735/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700736pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700737 conn: Connection,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800738 gc: Option<Gc>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700739}
740
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000741/// Database representation of the monotonic time retrieved from the system call clock_gettime with
742/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
743#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
744pub struct MonotonicRawTime(i64);
745
746impl MonotonicRawTime {
747 /// Constructs a new MonotonicRawTime
748 pub fn now() -> Self {
749 Self(get_current_time_in_seconds())
750 }
751
David Drysdale0e45a612021-02-25 17:24:36 +0000752 /// Constructs a new MonotonicRawTime from a given number of seconds.
753 pub fn from_secs(val: i64) -> Self {
754 Self(val)
755 }
756
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000757 /// Returns the integer value of MonotonicRawTime as i64
758 pub fn seconds(&self) -> i64 {
759 self.0
760 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800761
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000762 /// Returns the value of MonotonicRawTime in milli seconds as i64
763 pub fn milli_seconds(&self) -> i64 {
764 self.0 * 1000
765 }
766
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800767 /// Like i64::checked_sub.
768 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
769 self.0.checked_sub(other.0).map(Self)
770 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000771}
772
773impl ToSql for MonotonicRawTime {
774 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
775 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
776 }
777}
778
779impl FromSql for MonotonicRawTime {
780 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
781 Ok(Self(i64::column_result(value)?))
782 }
783}
784
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000785/// This struct encapsulates the information to be stored in the database about the auth tokens
786/// received by keystore.
787pub struct AuthTokenEntry {
788 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000789 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000790}
791
792impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000793 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000794 AuthTokenEntry { auth_token, time_received }
795 }
796
797 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000799 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800800 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
801 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000802 })
803 }
804
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000805 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800806 pub fn auth_token(&self) -> &HardwareAuthToken {
807 &self.auth_token
808 }
809
810 /// Returns the auth token wrapped by the AuthTokenEntry
811 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000812 self.auth_token
813 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800814
815 /// Returns the time that this auth token was received.
816 pub fn time_received(&self) -> MonotonicRawTime {
817 self.time_received
818 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000819
820 /// Returns the challenge value of the auth token.
821 pub fn challenge(&self) -> i64 {
822 self.auth_token.challenge
823 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000824}
825
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800826/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
827/// This object does not allow access to the database connection. But it keeps a database
828/// connection alive in order to keep the in memory per boot database alive.
829pub struct PerBootDbKeepAlive(Connection);
830
Joel Galenson26f4d012020-07-17 14:57:21 -0700831impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800832 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800833 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
834
Seth Moore78c091f2021-04-09 21:38:30 +0000835 /// Name of the file that holds the cross-boot persistent database.
836 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
837
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800838 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
839 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
840 let conn = Connection::open_in_memory()
841 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
842
843 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
844 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
845 Ok(PerBootDbKeepAlive(conn))
846 }
847
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700848 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800849 /// files persistent.sqlite and perboot.sqlite in the given directory.
850 /// It also attempts to initialize all of the tables.
851 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700852 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800853 pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700854 let _wp = wd::watch_millis("KeystoreDB::new", 500);
855
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800856 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800857 let mut persistent_path = db_root.to_path_buf();
Seth Moore78c091f2021-04-09 21:38:30 +0000858 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700859
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800860 // Now convert them to strings prefixed with "file:"
861 let mut persistent_path_str = "file:".to_owned();
862 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800863
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800864 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800865
Janis Danisevskis66784c42021-01-27 08:40:25 -0800866 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
867 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
868
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800869 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800871 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800872 })?;
873 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700874 }
875
Janis Danisevskis66784c42021-01-27 08:40:25 -0800876 fn init_tables(tx: &Transaction) -> Result<()> {
877 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700878 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700879 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800880 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700881 domain INTEGER,
882 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800883 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800884 state INTEGER,
885 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700886 NO_PARAMS,
887 )
888 .context("Failed to initialize \"keyentry\" table.")?;
889
Janis Danisevskis66784c42021-01-27 08:40:25 -0800890 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800891 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
892 ON keyentry(id);",
893 NO_PARAMS,
894 )
895 .context("Failed to create index keyentry_id_index.")?;
896
897 tx.execute(
898 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
899 ON keyentry(domain, namespace, alias);",
900 NO_PARAMS,
901 )
902 .context("Failed to create index keyentry_domain_namespace_index.")?;
903
904 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700905 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
906 id INTEGER PRIMARY KEY,
907 subcomponent_type INTEGER,
908 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800909 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700910 NO_PARAMS,
911 )
912 .context("Failed to initialize \"blobentry\" table.")?;
913
Janis Danisevskis66784c42021-01-27 08:40:25 -0800914 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800915 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
916 ON blobentry(keyentryid);",
917 NO_PARAMS,
918 )
919 .context("Failed to create index blobentry_keyentryid_index.")?;
920
921 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800922 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
923 id INTEGER PRIMARY KEY,
924 blobentryid INTEGER,
925 tag INTEGER,
926 data ANY,
927 UNIQUE (blobentryid, tag));",
928 NO_PARAMS,
929 )
930 .context("Failed to initialize \"blobmetadata\" table.")?;
931
932 tx.execute(
933 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
934 ON blobmetadata(blobentryid);",
935 NO_PARAMS,
936 )
937 .context("Failed to create index blobmetadata_blobentryid_index.")?;
938
939 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700940 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000941 keyentryid INTEGER,
942 tag INTEGER,
943 data ANY,
944 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700945 NO_PARAMS,
946 )
947 .context("Failed to initialize \"keyparameter\" table.")?;
948
Janis Danisevskis66784c42021-01-27 08:40:25 -0800949 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800950 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
951 ON keyparameter(keyentryid);",
952 NO_PARAMS,
953 )
954 .context("Failed to create index keyparameter_keyentryid_index.")?;
955
956 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800957 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
958 keyentryid INTEGER,
959 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000960 data ANY,
961 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800962 NO_PARAMS,
963 )
964 .context("Failed to initialize \"keymetadata\" table.")?;
965
Janis Danisevskis66784c42021-01-27 08:40:25 -0800966 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800967 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
968 ON keymetadata(keyentryid);",
969 NO_PARAMS,
970 )
971 .context("Failed to create index keymetadata_keyentryid_index.")?;
972
973 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800974 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700975 id INTEGER UNIQUE,
976 grantee INTEGER,
977 keyentryid INTEGER,
978 access_vector INTEGER);",
979 NO_PARAMS,
980 )
981 .context("Failed to initialize \"grant\" table.")?;
982
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000983 //TODO: only drop the following two perboot tables if this is the first start up
984 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800985 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000986 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800987 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000988 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
989 id INTEGER PRIMARY KEY,
990 challenge INTEGER,
991 user_id INTEGER,
992 auth_id INTEGER,
993 authenticator_type INTEGER,
994 timestamp INTEGER,
995 mac BLOB,
996 time_received INTEGER,
997 UNIQUE(user_id, auth_id, authenticator_type));",
998 NO_PARAMS,
999 )
1000 .context("Failed to initialize \"authtoken\" table.")?;
1001
Janis Danisevskis66784c42021-01-27 08:40:25 -08001002 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001003 // .context("Failed to drop perboot.metadata table")?;
1004 // metadata table stores certain miscellaneous information required for keystore functioning
1005 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001006 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001007 "CREATE TABLE IF NOT EXISTS perboot.metadata (
1008 key TEXT,
1009 value BLOB,
1010 UNIQUE(key));",
1011 NO_PARAMS,
1012 )
1013 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -07001014 Ok(())
1015 }
1016
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001017 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
1018 let conn =
1019 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1020
Janis Danisevskis66784c42021-01-27 08:40:25 -08001021 loop {
1022 if let Err(e) = conn
1023 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1024 .context("Failed to attach database persistent.")
1025 {
1026 if Self::is_locked_error(&e) {
1027 std::thread::sleep(std::time::Duration::from_micros(500));
1028 continue;
1029 } else {
1030 return Err(e);
1031 }
1032 }
1033 break;
1034 }
1035 loop {
1036 if let Err(e) = conn
1037 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1038 .context("Failed to attach database perboot.")
1039 {
1040 if Self::is_locked_error(&e) {
1041 std::thread::sleep(std::time::Duration::from_micros(500));
1042 continue;
1043 } else {
1044 return Err(e);
1045 }
1046 }
1047 break;
1048 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001049
1050 Ok(conn)
1051 }
1052
Seth Moore78c091f2021-04-09 21:38:30 +00001053 fn do_table_size_query(
1054 &mut self,
1055 storage_type: StatsdStorageType,
1056 query: &str,
1057 params: &[&str],
1058 ) -> Result<Keystore2StorageStats> {
1059 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1060 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1061 .with_context(|| {
1062 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1063 })
1064 .no_gc()
1065 })?;
1066 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1067 }
1068
1069 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1070 self.do_table_size_query(
1071 StatsdStorageType::Database,
1072 "SELECT page_count * page_size, freelist_count * page_size
1073 FROM pragma_page_count('persistent'),
1074 pragma_page_size('persistent'),
1075 persistent.pragma_freelist_count();",
1076 &[],
1077 )
1078 }
1079
1080 fn get_table_size(
1081 &mut self,
1082 storage_type: StatsdStorageType,
1083 schema: &str,
1084 table: &str,
1085 ) -> Result<Keystore2StorageStats> {
1086 self.do_table_size_query(
1087 storage_type,
1088 "SELECT pgsize,unused FROM dbstat(?1)
1089 WHERE name=?2 AND aggregate=TRUE;",
1090 &[schema, table],
1091 )
1092 }
1093
1094 /// Fetches a storage statisitics atom for a given storage type. For storage
1095 /// types that map to a table, information about the table's storage is
1096 /// returned. Requests for storage types that are not DB tables return None.
1097 pub fn get_storage_stat(
1098 &mut self,
1099 storage_type: StatsdStorageType,
1100 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001101 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1102
Seth Moore78c091f2021-04-09 21:38:30 +00001103 match storage_type {
1104 StatsdStorageType::Database => self.get_total_size(),
1105 StatsdStorageType::KeyEntry => {
1106 self.get_table_size(storage_type, "persistent", "keyentry")
1107 }
1108 StatsdStorageType::KeyEntryIdIndex => {
1109 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1110 }
1111 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1112 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1113 }
1114 StatsdStorageType::BlobEntry => {
1115 self.get_table_size(storage_type, "persistent", "blobentry")
1116 }
1117 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1118 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1119 }
1120 StatsdStorageType::KeyParameter => {
1121 self.get_table_size(storage_type, "persistent", "keyparameter")
1122 }
1123 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1124 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1125 }
1126 StatsdStorageType::KeyMetadata => {
1127 self.get_table_size(storage_type, "persistent", "keymetadata")
1128 }
1129 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1130 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1131 }
1132 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1133 StatsdStorageType::AuthToken => {
1134 self.get_table_size(storage_type, "perboot", "authtoken")
1135 }
1136 StatsdStorageType::BlobMetadata => {
1137 self.get_table_size(storage_type, "persistent", "blobmetadata")
1138 }
1139 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1140 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1141 }
1142 _ => Err(anyhow::Error::msg(format!(
1143 "Unsupported storage type: {}",
1144 storage_type as i32
1145 ))),
1146 }
1147 }
1148
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001149 /// This function is intended to be used by the garbage collector.
1150 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1151 /// key blob that might need special handling by the garbage collector.
1152 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1153 /// need special handling and returns None.
1154 pub fn handle_next_superseded_blob(
1155 &mut self,
1156 blob_id_to_delete: Option<i64>,
1157 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001158 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001159 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001160 // Delete the given blob if one was given.
1161 if let Some(blob_id_to_delete) = blob_id_to_delete {
1162 tx.execute(
1163 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1164 params![blob_id_to_delete],
1165 )
1166 .context("Trying to delete blob metadata.")?;
1167 tx.execute(
1168 "DELETE FROM persistent.blobentry WHERE id = ?;",
1169 params![blob_id_to_delete],
1170 )
1171 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001172 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001173
1174 // Find another superseded keyblob load its metadata and return it.
1175 if let Some((blob_id, blob)) = tx
1176 .query_row(
1177 "SELECT id, blob FROM persistent.blobentry
1178 WHERE subcomponent_type = ?
1179 AND (
1180 id NOT IN (
1181 SELECT MAX(id) FROM persistent.blobentry
1182 WHERE subcomponent_type = ?
1183 GROUP BY keyentryid, subcomponent_type
1184 )
1185 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1186 );",
1187 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1188 |row| Ok((row.get(0)?, row.get(1)?)),
1189 )
1190 .optional()
1191 .context("Trying to query superseded blob.")?
1192 {
1193 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1194 .context("Trying to load blob metadata.")?;
1195 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1196 }
1197
1198 // We did not find any superseded key blob, so let's remove other superseded blob in
1199 // one transaction.
1200 tx.execute(
1201 "DELETE FROM persistent.blobentry
1202 WHERE NOT subcomponent_type = ?
1203 AND (
1204 id NOT IN (
1205 SELECT MAX(id) FROM persistent.blobentry
1206 WHERE NOT subcomponent_type = ?
1207 GROUP BY keyentryid, subcomponent_type
1208 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1209 );",
1210 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1211 )
1212 .context("Trying to purge superseded blobs.")?;
1213
1214 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001215 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001216 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001217 }
1218
1219 /// This maintenance function should be called only once before the database is used for the
1220 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1221 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1222 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1223 /// Keystore crashed at some point during key generation. Callers may want to log such
1224 /// occurrences.
1225 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1226 /// it to `KeyLifeCycle::Live` may have grants.
1227 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001228 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1229
Janis Danisevskis66784c42021-01-27 08:40:25 -08001230 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1231 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001232 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1233 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1234 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001235 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001236 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001237 })
1238 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001239 }
1240
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001241 /// Checks if a key exists with given key type and key descriptor properties.
1242 pub fn key_exists(
1243 &mut self,
1244 domain: Domain,
1245 nspace: i64,
1246 alias: &str,
1247 key_type: KeyType,
1248 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001249 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1250
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001251 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1252 let key_descriptor =
1253 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1254 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1255 match result {
1256 Ok(_) => Ok(true),
1257 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1258 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1259 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1260 },
1261 }
1262 .no_gc()
1263 })
1264 .context("In key_exists.")
1265 }
1266
Hasini Gunasingheda895552021-01-27 19:34:37 +00001267 /// Stores a super key in the database.
1268 pub fn store_super_key(
1269 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001270 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001271 key_type: &SuperKeyType,
1272 blob: &[u8],
1273 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001274 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001275 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001276 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1277
Hasini Gunasingheda895552021-01-27 19:34:37 +00001278 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1279 let key_id = Self::insert_with_retry(|id| {
1280 tx.execute(
1281 "INSERT into persistent.keyentry
1282 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001283 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001284 params![
1285 id,
1286 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001287 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001288 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001289 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001290 KeyLifeCycle::Live,
1291 &KEYSTORE_UUID,
1292 ],
1293 )
1294 })
1295 .context("Failed to insert into keyentry table.")?;
1296
Paul Crowley8d5b2532021-03-19 10:53:07 -07001297 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1298
Hasini Gunasingheda895552021-01-27 19:34:37 +00001299 Self::set_blob_internal(
1300 &tx,
1301 key_id,
1302 SubComponentType::KEY_BLOB,
1303 Some(blob),
1304 Some(blob_metadata),
1305 )
1306 .context("Failed to store key blob.")?;
1307
1308 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1309 .context("Trying to load key components.")
1310 .no_gc()
1311 })
1312 .context("In store_super_key.")
1313 }
1314
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001315 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001316 pub fn load_super_key(
1317 &mut self,
1318 key_type: &SuperKeyType,
1319 user_id: u32,
1320 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001321 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1322
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001323 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1324 let key_descriptor = KeyDescriptor {
1325 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001326 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001327 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001328 blob: None,
1329 };
1330 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1331 match id {
1332 Ok(id) => {
1333 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1334 .context("In load_super_key. Failed to load key entry.")?;
1335 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1336 }
1337 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1338 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1339 _ => Err(error).context("In load_super_key."),
1340 },
1341 }
1342 .no_gc()
1343 })
1344 .context("In load_super_key.")
1345 }
1346
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001347 /// Atomically loads a key entry and associated metadata or creates it using the
1348 /// callback create_new_key callback. The callback is called during a database
1349 /// transaction. This means that implementers should be mindful about using
1350 /// blocking operations such as IPC or grabbing mutexes.
1351 pub fn get_or_create_key_with<F>(
1352 &mut self,
1353 domain: Domain,
1354 namespace: i64,
1355 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001356 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001357 create_new_key: F,
1358 ) -> Result<(KeyIdGuard, KeyEntry)>
1359 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001360 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001361 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001362 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1363
Janis Danisevskis66784c42021-01-27 08:40:25 -08001364 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1365 let id = {
1366 let mut stmt = tx
1367 .prepare(
1368 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001369 WHERE
1370 key_type = ?
1371 AND domain = ?
1372 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001373 AND alias = ?
1374 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001375 )
1376 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1377 let mut rows = stmt
1378 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1379 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001380
Janis Danisevskis66784c42021-01-27 08:40:25 -08001381 db_utils::with_rows_extract_one(&mut rows, |row| {
1382 Ok(match row {
1383 Some(r) => r.get(0).context("Failed to unpack id.")?,
1384 None => None,
1385 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001386 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 .context("In get_or_create_key_with.")?
1388 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001389
Janis Danisevskis66784c42021-01-27 08:40:25 -08001390 let (id, entry) = match id {
1391 Some(id) => (
1392 id,
1393 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1394 .context("In get_or_create_key_with.")?,
1395 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001396
Janis Danisevskis66784c42021-01-27 08:40:25 -08001397 None => {
1398 let id = Self::insert_with_retry(|id| {
1399 tx.execute(
1400 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001401 (id, key_type, domain, namespace, alias, state, km_uuid)
1402 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001403 params![
1404 id,
1405 KeyType::Super,
1406 domain.0,
1407 namespace,
1408 alias,
1409 KeyLifeCycle::Live,
1410 km_uuid,
1411 ],
1412 )
1413 })
1414 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001415
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 let (blob, metadata) =
1417 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001418 Self::set_blob_internal(
1419 &tx,
1420 id,
1421 SubComponentType::KEY_BLOB,
1422 Some(&blob),
1423 Some(&metadata),
1424 )
Paul Crowley7a658392021-03-18 17:08:20 -07001425 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001426 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001427 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001428 KeyEntry {
1429 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001430 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001431 pure_cert: false,
1432 ..Default::default()
1433 },
1434 )
1435 }
1436 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001437 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001438 })
1439 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001440 }
1441
Janis Danisevskis66784c42021-01-27 08:40:25 -08001442 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1443 /// waiting for the database file to become available. This makes it
1444 /// impossible to successfully recover from a locked database when the
1445 /// transaction holding the device busy is in the same process on a
1446 /// different connection. As a result the busy handler has to time out and
1447 /// fail in order to make progress.
1448 ///
1449 /// Instead, we set the busy handler to None (return immediately). And catch
1450 /// Busy and Locked errors (the latter occur on in memory databases with
1451 /// shared cache, e.g., the per-boot database.) and restart the transaction
1452 /// after a grace period of half a millisecond.
1453 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001454 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001455 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1456 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001457 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1458 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001459 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001460 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001461 loop {
1462 match self
1463 .conn
1464 .transaction_with_behavior(behavior)
1465 .context("In with_transaction.")
1466 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1467 .and_then(|(result, tx)| {
1468 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1469 Ok(result)
1470 }) {
1471 Ok(result) => break Ok(result),
1472 Err(e) => {
1473 if Self::is_locked_error(&e) {
1474 std::thread::sleep(std::time::Duration::from_micros(500));
1475 continue;
1476 } else {
1477 return Err(e).context("In with_transaction.");
1478 }
1479 }
1480 }
1481 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001482 .map(|(need_gc, result)| {
1483 if need_gc {
1484 if let Some(ref gc) = self.gc {
1485 gc.notify_gc();
1486 }
1487 }
1488 result
1489 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001490 }
1491
1492 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001493 matches!(
1494 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1495 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1496 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1497 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001498 }
1499
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001500 /// Creates a new key entry and allocates a new randomized id for the new key.
1501 /// The key id gets associated with a domain and namespace but not with an alias.
1502 /// To complete key generation `rebind_alias` should be called after all of the
1503 /// key artifacts, i.e., blobs and parameters have been associated with the new
1504 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1505 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001506 pub fn create_key_entry(
1507 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001508 domain: &Domain,
1509 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001510 km_uuid: &Uuid,
1511 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001512 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1513
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001514 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001515 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001516 })
1517 .context("In create_key_entry.")
1518 }
1519
1520 fn create_key_entry_internal(
1521 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001522 domain: &Domain,
1523 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001524 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001526 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001527 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001528 _ => {
1529 return Err(KsError::sys())
1530 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1531 }
1532 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001533 Ok(KEY_ID_LOCK.get(
1534 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001535 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001536 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001537 (id, key_type, domain, namespace, alias, state, km_uuid)
1538 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001539 params![
1540 id,
1541 KeyType::Client,
1542 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001543 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001544 KeyLifeCycle::Existing,
1545 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001546 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001547 )
1548 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001549 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001550 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001551 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001552
Max Bires2b2e6562020-09-22 11:22:36 -07001553 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1554 /// The key id gets associated with a domain and namespace later but not with an alias. The
1555 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1556 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1557 /// a key.
1558 pub fn create_attestation_key_entry(
1559 &mut self,
1560 maced_public_key: &[u8],
1561 raw_public_key: &[u8],
1562 private_key: &[u8],
1563 km_uuid: &Uuid,
1564 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001565 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1566
Max Bires2b2e6562020-09-22 11:22:36 -07001567 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1568 let key_id = KEY_ID_LOCK.get(
1569 Self::insert_with_retry(|id| {
1570 tx.execute(
1571 "INSERT into persistent.keyentry
1572 (id, key_type, domain, namespace, alias, state, km_uuid)
1573 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1574 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1575 )
1576 })
1577 .context("In create_key_entry")?,
1578 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001579 Self::set_blob_internal(
1580 &tx,
1581 key_id.0,
1582 SubComponentType::KEY_BLOB,
1583 Some(private_key),
1584 None,
1585 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001586 let mut metadata = KeyMetaData::new();
1587 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1588 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1589 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001590 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001591 })
1592 .context("In create_attestation_key_entry")
1593 }
1594
Janis Danisevskis377d1002021-01-27 19:07:48 -08001595 /// Set a new blob and associates it with the given key id. Each blob
1596 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001597 /// Each key can have one of each sub component type associated. If more
1598 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001599 /// will get garbage collected.
1600 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1601 /// removed by setting blob to None.
1602 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001603 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001604 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001605 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001606 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001607 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001608 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001609 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1610
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001611 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001612 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001613 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001614 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001615 }
1616
Janis Danisevskiseed69842021-02-18 20:04:10 -08001617 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1618 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1619 /// We use this to insert key blobs into the database which can then be garbage collected
1620 /// lazily by the key garbage collector.
1621 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001622 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1623
Janis Danisevskiseed69842021-02-18 20:04:10 -08001624 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1625 Self::set_blob_internal(
1626 &tx,
1627 Self::UNASSIGNED_KEY_ID,
1628 SubComponentType::KEY_BLOB,
1629 Some(blob),
1630 Some(blob_metadata),
1631 )
1632 .need_gc()
1633 })
1634 .context("In set_deleted_blob.")
1635 }
1636
Janis Danisevskis377d1002021-01-27 19:07:48 -08001637 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001638 tx: &Transaction,
1639 key_id: i64,
1640 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001641 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001642 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001643 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001644 match (blob, sc_type) {
1645 (Some(blob), _) => {
1646 tx.execute(
1647 "INSERT INTO persistent.blobentry
1648 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1649 params![sc_type, key_id, blob],
1650 )
1651 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001652 if let Some(blob_metadata) = blob_metadata {
1653 let blob_id = tx
1654 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1655 row.get(0)
1656 })
1657 .context("In set_blob_internal: Failed to get new blob id.")?;
1658 blob_metadata
1659 .store_in_db(blob_id, tx)
1660 .context("In set_blob_internal: Trying to store blob metadata.")?;
1661 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001662 }
1663 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1664 tx.execute(
1665 "DELETE FROM persistent.blobentry
1666 WHERE subcomponent_type = ? AND keyentryid = ?;",
1667 params![sc_type, key_id],
1668 )
1669 .context("In set_blob_internal: Failed to delete blob.")?;
1670 }
1671 (None, _) => {
1672 return Err(KsError::sys())
1673 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1674 }
1675 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001676 Ok(())
1677 }
1678
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001679 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1680 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001681 #[cfg(test)]
1682 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001683 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001684 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001685 })
1686 .context("In insert_keyparameter.")
1687 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001688
Janis Danisevskis66784c42021-01-27 08:40:25 -08001689 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001690 tx: &Transaction,
1691 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001692 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001693 ) -> Result<()> {
1694 let mut stmt = tx
1695 .prepare(
1696 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1697 VALUES (?, ?, ?, ?);",
1698 )
1699 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1700
Janis Danisevskis66784c42021-01-27 08:40:25 -08001701 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001702 stmt.insert(params![
1703 key_id.0,
1704 p.get_tag().0,
1705 p.key_parameter_value(),
1706 p.security_level().0
1707 ])
1708 .with_context(|| {
1709 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1710 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001711 }
1712 Ok(())
1713 }
1714
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001715 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001716 #[cfg(test)]
1717 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001718 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001719 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001720 })
1721 .context("In insert_key_metadata.")
1722 }
1723
Max Bires2b2e6562020-09-22 11:22:36 -07001724 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1725 /// on the public key.
1726 pub fn store_signed_attestation_certificate_chain(
1727 &mut self,
1728 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001729 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001730 cert_chain: &[u8],
1731 expiration_date: i64,
1732 km_uuid: &Uuid,
1733 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001734 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1735
Max Bires2b2e6562020-09-22 11:22:36 -07001736 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1737 let mut stmt = tx
1738 .prepare(
1739 "SELECT keyentryid
1740 FROM persistent.keymetadata
1741 WHERE tag = ? AND data = ? AND keyentryid IN
1742 (SELECT id
1743 FROM persistent.keyentry
1744 WHERE
1745 alias IS NULL AND
1746 domain IS NULL AND
1747 namespace IS NULL AND
1748 key_type = ? AND
1749 km_uuid = ?);",
1750 )
1751 .context("Failed to store attestation certificate chain.")?;
1752 let mut rows = stmt
1753 .query(params![
1754 KeyMetaData::AttestationRawPubKey,
1755 raw_public_key,
1756 KeyType::Attestation,
1757 km_uuid
1758 ])
1759 .context("Failed to fetch keyid")?;
1760 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1761 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1762 .get(0)
1763 .context("Failed to unpack id.")
1764 })
1765 .context("Failed to get key_id.")?;
1766 let num_updated = tx
1767 .execute(
1768 "UPDATE persistent.keyentry
1769 SET alias = ?
1770 WHERE id = ?;",
1771 params!["signed", key_id],
1772 )
1773 .context("Failed to update alias.")?;
1774 if num_updated != 1 {
1775 return Err(KsError::sys()).context("Alias not updated for the key.");
1776 }
1777 let mut metadata = KeyMetaData::new();
1778 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1779 expiration_date,
1780 )));
1781 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001782 Self::set_blob_internal(
1783 &tx,
1784 key_id,
1785 SubComponentType::CERT_CHAIN,
1786 Some(cert_chain),
1787 None,
1788 )
1789 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001790 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1791 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001792 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001793 })
1794 .context("In store_signed_attestation_certificate_chain: ")
1795 }
1796
1797 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1798 /// currently have a key assigned to it.
1799 pub fn assign_attestation_key(
1800 &mut self,
1801 domain: Domain,
1802 namespace: i64,
1803 km_uuid: &Uuid,
1804 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001805 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1806
Max Bires2b2e6562020-09-22 11:22:36 -07001807 match domain {
1808 Domain::APP | Domain::SELINUX => {}
1809 _ => {
1810 return Err(KsError::sys()).context(format!(
1811 concat!(
1812 "In assign_attestation_key: Domain {:?} ",
1813 "must be either App or SELinux.",
1814 ),
1815 domain
1816 ));
1817 }
1818 }
1819 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1820 let result = tx
1821 .execute(
1822 "UPDATE persistent.keyentry
1823 SET domain=?1, namespace=?2
1824 WHERE
1825 id =
1826 (SELECT MIN(id)
1827 FROM persistent.keyentry
1828 WHERE ALIAS IS NOT NULL
1829 AND domain IS NULL
1830 AND key_type IS ?3
1831 AND state IS ?4
1832 AND km_uuid IS ?5)
1833 AND
1834 (SELECT COUNT(*)
1835 FROM persistent.keyentry
1836 WHERE domain=?1
1837 AND namespace=?2
1838 AND key_type IS ?3
1839 AND state IS ?4
1840 AND km_uuid IS ?5) = 0;",
1841 params![
1842 domain.0 as u32,
1843 namespace,
1844 KeyType::Attestation,
1845 KeyLifeCycle::Live,
1846 km_uuid,
1847 ],
1848 )
1849 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001850 if result == 0 {
1851 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1852 } else if result > 1 {
1853 return Err(KsError::sys())
1854 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001855 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001856 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001857 })
1858 .context("In assign_attestation_key: ")
1859 }
1860
1861 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1862 /// provisioning server, or the maximum number available if there are not num_keys number of
1863 /// entries in the table.
1864 pub fn fetch_unsigned_attestation_keys(
1865 &mut self,
1866 num_keys: i32,
1867 km_uuid: &Uuid,
1868 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001869 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1870
Max Bires2b2e6562020-09-22 11:22:36 -07001871 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1872 let mut stmt = tx
1873 .prepare(
1874 "SELECT data
1875 FROM persistent.keymetadata
1876 WHERE tag = ? AND keyentryid IN
1877 (SELECT id
1878 FROM persistent.keyentry
1879 WHERE
1880 alias IS NULL AND
1881 domain IS NULL AND
1882 namespace IS NULL AND
1883 key_type = ? AND
1884 km_uuid = ?
1885 LIMIT ?);",
1886 )
1887 .context("Failed to prepare statement")?;
1888 let rows = stmt
1889 .query_map(
1890 params![
1891 KeyMetaData::AttestationMacedPublicKey,
1892 KeyType::Attestation,
1893 km_uuid,
1894 num_keys
1895 ],
1896 |row| Ok(row.get(0)?),
1897 )?
1898 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1899 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001900 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001901 })
1902 .context("In fetch_unsigned_attestation_keys")
1903 }
1904
1905 /// Removes any keys that have expired as of the current time. Returns the number of keys
1906 /// marked unreferenced that are bound to be garbage collected.
1907 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001908 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1909
Max Bires2b2e6562020-09-22 11:22:36 -07001910 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1911 let mut stmt = tx
1912 .prepare(
1913 "SELECT keyentryid, data
1914 FROM persistent.keymetadata
1915 WHERE tag = ? AND keyentryid IN
1916 (SELECT id
1917 FROM persistent.keyentry
1918 WHERE key_type = ?);",
1919 )
1920 .context("Failed to prepare query")?;
1921 let key_ids_to_check = stmt
1922 .query_map(
1923 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1924 |row| Ok((row.get(0)?, row.get(1)?)),
1925 )?
1926 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1927 .context("Failed to get date metadata")?;
1928 let curr_time = DateTime::from_millis_epoch(
1929 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1930 );
1931 let mut num_deleted = 0;
1932 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1933 if Self::mark_unreferenced(&tx, id)? {
1934 num_deleted += 1;
1935 }
1936 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001937 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001938 })
1939 .context("In delete_expired_attestation_keys: ")
1940 }
1941
Max Bires60d7ed12021-03-05 15:59:22 -08001942 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1943 /// they are in. This is useful primarily as a testing mechanism.
1944 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001945 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1946
Max Bires60d7ed12021-03-05 15:59:22 -08001947 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1948 let mut stmt = tx
1949 .prepare(
1950 "SELECT id FROM persistent.keyentry
1951 WHERE key_type IS ?;",
1952 )
1953 .context("Failed to prepare statement")?;
1954 let keys_to_delete = stmt
1955 .query_map(params![KeyType::Attestation], |row| Ok(row.get(0)?))?
1956 .collect::<rusqlite::Result<Vec<i64>>>()
1957 .context("Failed to execute statement")?;
1958 let num_deleted = keys_to_delete
1959 .iter()
1960 .map(|id| Self::mark_unreferenced(&tx, *id))
1961 .collect::<Result<Vec<bool>>>()
1962 .context("Failed to execute mark_unreferenced on a keyid")?
1963 .into_iter()
1964 .filter(|result| *result)
1965 .count() as i64;
1966 Ok(num_deleted).do_gc(num_deleted != 0)
1967 })
1968 .context("In delete_all_attestation_keys: ")
1969 }
1970
Max Bires2b2e6562020-09-22 11:22:36 -07001971 /// Counts the number of keys that will expire by the provided epoch date and the number of
1972 /// keys not currently assigned to a domain.
1973 pub fn get_attestation_pool_status(
1974 &mut self,
1975 date: i64,
1976 km_uuid: &Uuid,
1977 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001978 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1979
Max Bires2b2e6562020-09-22 11:22:36 -07001980 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1981 let mut stmt = tx.prepare(
1982 "SELECT data
1983 FROM persistent.keymetadata
1984 WHERE tag = ? AND keyentryid IN
1985 (SELECT id
1986 FROM persistent.keyentry
1987 WHERE alias IS NOT NULL
1988 AND key_type = ?
1989 AND km_uuid = ?
1990 AND state = ?);",
1991 )?;
1992 let times = stmt
1993 .query_map(
1994 params![
1995 KeyMetaData::AttestationExpirationDate,
1996 KeyType::Attestation,
1997 km_uuid,
1998 KeyLifeCycle::Live
1999 ],
2000 |row| Ok(row.get(0)?),
2001 )?
2002 .collect::<rusqlite::Result<Vec<DateTime>>>()
2003 .context("Failed to execute metadata statement")?;
2004 let expiring =
2005 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2006 as i32;
2007 stmt = tx.prepare(
2008 "SELECT alias, domain
2009 FROM persistent.keyentry
2010 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2011 )?;
2012 let rows = stmt
2013 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2014 Ok((row.get(0)?, row.get(1)?))
2015 })?
2016 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2017 .context("Failed to execute keyentry statement")?;
2018 let mut unassigned = 0i32;
2019 let mut attested = 0i32;
2020 let total = rows.len() as i32;
2021 for (alias, domain) in rows {
2022 match (alias, domain) {
2023 (Some(_alias), None) => {
2024 attested += 1;
2025 unassigned += 1;
2026 }
2027 (Some(_alias), Some(_domain)) => {
2028 attested += 1;
2029 }
2030 _ => {}
2031 }
2032 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002033 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002034 })
2035 .context("In get_attestation_pool_status: ")
2036 }
2037
2038 /// Fetches the private key and corresponding certificate chain assigned to a
2039 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2040 /// not assigned, or one CertificateChain.
2041 pub fn retrieve_attestation_key_and_cert_chain(
2042 &mut self,
2043 domain: Domain,
2044 namespace: i64,
2045 km_uuid: &Uuid,
2046 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002047 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2048
Max Bires2b2e6562020-09-22 11:22:36 -07002049 match domain {
2050 Domain::APP | Domain::SELINUX => {}
2051 _ => {
2052 return Err(KsError::sys())
2053 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2054 }
2055 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002056 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2057 let mut stmt = tx.prepare(
2058 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002059 FROM persistent.blobentry
2060 WHERE keyentryid IN
2061 (SELECT id
2062 FROM persistent.keyentry
2063 WHERE key_type = ?
2064 AND domain = ?
2065 AND namespace = ?
2066 AND state = ?
2067 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002068 )?;
2069 let rows = stmt
2070 .query_map(
2071 params![
2072 KeyType::Attestation,
2073 domain.0 as u32,
2074 namespace,
2075 KeyLifeCycle::Live,
2076 km_uuid
2077 ],
2078 |row| Ok((row.get(0)?, row.get(1)?)),
2079 )?
2080 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002081 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 if rows.is_empty() {
2083 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002084 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002085 return Err(KsError::sys()).context(format!(
2086 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002087 "Expected to get a single attestation",
2088 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2089 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002090 rows.len()
2091 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002092 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002093 let mut km_blob: Vec<u8> = Vec::new();
2094 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002095 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002096 for row in rows {
2097 let sub_type: SubComponentType = row.0;
2098 match sub_type {
2099 SubComponentType::KEY_BLOB => {
2100 km_blob = row.1;
2101 }
2102 SubComponentType::CERT_CHAIN => {
2103 cert_chain_blob = row.1;
2104 }
Max Biresb2e1d032021-02-08 21:35:05 -08002105 SubComponentType::CERT => {
2106 batch_cert_blob = row.1;
2107 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002108 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2109 }
2110 }
2111 Ok(Some(CertificateChain {
2112 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002113 batch_cert: batch_cert_blob,
2114 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002115 }))
2116 .no_gc()
2117 })
Max Biresb2e1d032021-02-08 21:35:05 -08002118 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002119 }
2120
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002121 /// Updates the alias column of the given key id `newid` with the given alias,
2122 /// and atomically, removes the alias, domain, and namespace from another row
2123 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002124 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2125 /// collector.
2126 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002128 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002129 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002130 domain: &Domain,
2131 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002132 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002133 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002134 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002135 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002136 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002137 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002138 domain
2139 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002140 }
2141 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002142 let updated = tx
2143 .execute(
2144 "UPDATE persistent.keyentry
2145 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002146 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002147 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2148 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002149 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002150 let result = tx
2151 .execute(
2152 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002153 SET alias = ?, state = ?
2154 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2155 params![
2156 alias,
2157 KeyLifeCycle::Live,
2158 newid.0,
2159 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002160 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002161 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002162 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002163 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002164 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002165 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002166 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002167 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002168 result
2169 ));
2170 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002171 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002172 }
2173
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002174 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2175 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2176 pub fn migrate_key_namespace(
2177 &mut self,
2178 key_id_guard: KeyIdGuard,
2179 destination: &KeyDescriptor,
2180 caller_uid: u32,
2181 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2182 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002183 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2184
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002185 let destination = match destination.domain {
2186 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2187 Domain::SELINUX => (*destination).clone(),
2188 domain => {
2189 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2190 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2191 }
2192 };
2193
2194 // Security critical: Must return immediately on failure. Do not remove the '?';
2195 check_permission(&destination)
2196 .context("In migrate_key_namespace: Trying to check permission.")?;
2197
2198 let alias = destination
2199 .alias
2200 .as_ref()
2201 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2202 .context("In migrate_key_namespace: Alias must be specified.")?;
2203
2204 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2205 // Query the destination location. If there is a key, the migration request fails.
2206 if tx
2207 .query_row(
2208 "SELECT id FROM persistent.keyentry
2209 WHERE alias = ? AND domain = ? AND namespace = ?;",
2210 params![alias, destination.domain.0, destination.nspace],
2211 |_| Ok(()),
2212 )
2213 .optional()
2214 .context("Failed to query destination.")?
2215 .is_some()
2216 {
2217 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2218 .context("Target already exists.");
2219 }
2220
2221 let updated = tx
2222 .execute(
2223 "UPDATE persistent.keyentry
2224 SET alias = ?, domain = ?, namespace = ?
2225 WHERE id = ?;",
2226 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2227 )
2228 .context("Failed to update key entry.")?;
2229
2230 if updated != 1 {
2231 return Err(KsError::sys())
2232 .context(format!("Update succeeded, but {} rows were updated.", updated));
2233 }
2234 Ok(()).no_gc()
2235 })
2236 .context("In migrate_key_namespace:")
2237 }
2238
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002239 /// Store a new key in a single transaction.
2240 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2241 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002242 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2243 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002244 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002245 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002246 key: &KeyDescriptor,
2247 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002248 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002249 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002250 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002251 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002252 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002253 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2254
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002255 let (alias, domain, namespace) = match key {
2256 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2257 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2258 (alias, key.domain, nspace)
2259 }
2260 _ => {
2261 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2262 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2263 }
2264 };
2265 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002266 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002267 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002268 let (blob, blob_metadata) = *blob_info;
2269 Self::set_blob_internal(
2270 tx,
2271 key_id.id(),
2272 SubComponentType::KEY_BLOB,
2273 Some(blob),
2274 Some(&blob_metadata),
2275 )
2276 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002277 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002278 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002279 .context("Trying to insert the certificate.")?;
2280 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002281 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002282 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002283 tx,
2284 key_id.id(),
2285 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002286 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002287 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002288 )
2289 .context("Trying to insert the certificate chain.")?;
2290 }
2291 Self::insert_keyparameter_internal(tx, &key_id, params)
2292 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002293 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002294 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002295 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002296 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002297 })
2298 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002299 }
2300
Janis Danisevskis377d1002021-01-27 19:07:48 -08002301 /// Store a new certificate
2302 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2303 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002304 pub fn store_new_certificate(
2305 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002306 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002307 cert: &[u8],
2308 km_uuid: &Uuid,
2309 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002310 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2311
Janis Danisevskis377d1002021-01-27 19:07:48 -08002312 let (alias, domain, namespace) = match key {
2313 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2314 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2315 (alias, key.domain, nspace)
2316 }
2317 _ => {
2318 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2319 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2320 )
2321 }
2322 };
2323 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002324 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002325 .context("Trying to create new key entry.")?;
2326
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002327 Self::set_blob_internal(
2328 tx,
2329 key_id.id(),
2330 SubComponentType::CERT_CHAIN,
2331 Some(cert),
2332 None,
2333 )
2334 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002335
2336 let mut metadata = KeyMetaData::new();
2337 metadata.add(KeyMetaEntry::CreationDate(
2338 DateTime::now().context("Trying to make creation time.")?,
2339 ));
2340
2341 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2342
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002343 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002344 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002345 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002346 })
2347 .context("In store_new_certificate.")
2348 }
2349
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002350 // Helper function loading the key_id given the key descriptor
2351 // tuple comprising domain, namespace, and alias.
2352 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002353 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002354 let alias = key
2355 .alias
2356 .as_ref()
2357 .map_or_else(|| Err(KsError::sys()), Ok)
2358 .context("In load_key_entry_id: Alias must be specified.")?;
2359 let mut stmt = tx
2360 .prepare(
2361 "SELECT id FROM persistent.keyentry
2362 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002363 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002364 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002365 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002366 AND alias = ?
2367 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002368 )
2369 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2370 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002371 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002372 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002373 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002374 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002375 .get(0)
2376 .context("Failed to unpack id.")
2377 })
2378 .context("In load_key_entry_id.")
2379 }
2380
2381 /// This helper function completes the access tuple of a key, which is required
2382 /// to perform access control. The strategy depends on the `domain` field in the
2383 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002384 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002385 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002386 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002387 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002388 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002389 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002390 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002391 /// `namespace`.
2392 /// In each case the information returned is sufficient to perform the access
2393 /// check and the key id can be used to load further key artifacts.
2394 fn load_access_tuple(
2395 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002396 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002397 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002398 caller_uid: u32,
2399 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2400 match key.domain {
2401 // Domain App or SELinux. In this case we load the key_id from
2402 // the keyentry database for further loading of key components.
2403 // We already have the full access tuple to perform access control.
2404 // The only distinction is that we use the caller_uid instead
2405 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002406 // Domain::APP.
2407 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002408 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002409 if access_key.domain == Domain::APP {
2410 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002411 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002412 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002413 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002414
2415 Ok((key_id, access_key, None))
2416 }
2417
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002418 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002420 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002421 let mut stmt = tx
2422 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002423 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002424 WHERE grantee = ? AND id = ?;",
2425 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002426 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002427 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002428 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002429 .context("Domain:Grant: query failed.")?;
2430 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002431 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002432 let r =
2433 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002434 Ok((
2435 r.get(0).context("Failed to unpack key_id.")?,
2436 r.get(1).context("Failed to unpack access_vector.")?,
2437 ))
2438 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002439 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002440 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002441 }
2442
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002443 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002444 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002445 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002446 let (domain, namespace): (Domain, i64) = {
2447 let mut stmt = tx
2448 .prepare(
2449 "SELECT domain, namespace FROM persistent.keyentry
2450 WHERE
2451 id = ?
2452 AND state = ?;",
2453 )
2454 .context("Domain::KEY_ID: prepare statement failed")?;
2455 let mut rows = stmt
2456 .query(params![key.nspace, KeyLifeCycle::Live])
2457 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002458 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002459 let r =
2460 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002461 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002462 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002463 r.get(1).context("Failed to unpack namespace.")?,
2464 ))
2465 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002466 .context("Domain::KEY_ID.")?
2467 };
2468
2469 // We may use a key by id after loading it by grant.
2470 // In this case we have to check if the caller has a grant for this particular
2471 // key. We can skip this if we already know that the caller is the owner.
2472 // But we cannot know this if domain is anything but App. E.g. in the case
2473 // of Domain::SELINUX we have to speculatively check for grants because we have to
2474 // consult the SEPolicy before we know if the caller is the owner.
2475 let access_vector: Option<KeyPermSet> =
2476 if domain != Domain::APP || namespace != caller_uid as i64 {
2477 let access_vector: Option<i32> = tx
2478 .query_row(
2479 "SELECT access_vector FROM persistent.grant
2480 WHERE grantee = ? AND keyentryid = ?;",
2481 params![caller_uid as i64, key.nspace],
2482 |row| row.get(0),
2483 )
2484 .optional()
2485 .context("Domain::KEY_ID: query grant failed.")?;
2486 access_vector.map(|p| p.into())
2487 } else {
2488 None
2489 };
2490
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002491 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002492 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002493 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002494 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002495
Janis Danisevskis45760022021-01-19 16:34:10 -08002496 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002497 }
2498 _ => Err(anyhow!(KsError::sys())),
2499 }
2500 }
2501
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002502 fn load_blob_components(
2503 key_id: i64,
2504 load_bits: KeyEntryLoadBits,
2505 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002506 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002507 let mut stmt = tx
2508 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002509 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002510 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2511 )
2512 .context("In load_blob_components: prepare statement failed.")?;
2513
2514 let mut rows =
2515 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2516
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002517 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002518 let mut cert_blob: Option<Vec<u8>> = None;
2519 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002520 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002521 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002522 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002523 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002524 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002525 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2526 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002527 key_blob = Some((
2528 row.get(0).context("Failed to extract key blob id.")?,
2529 row.get(2).context("Failed to extract key blob.")?,
2530 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002531 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002532 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002533 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002534 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002535 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002536 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002537 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002538 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002539 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002540 (SubComponentType::CERT, _, _)
2541 | (SubComponentType::CERT_CHAIN, _, _)
2542 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002543 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2544 }
2545 Ok(())
2546 })
2547 .context("In load_blob_components.")?;
2548
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002549 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2550 Ok(Some((
2551 blob,
2552 BlobMetaData::load_from_db(blob_id, tx)
2553 .context("In load_blob_components: Trying to load blob_metadata.")?,
2554 )))
2555 })?;
2556
2557 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002558 }
2559
2560 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2561 let mut stmt = tx
2562 .prepare(
2563 "SELECT tag, data, security_level from persistent.keyparameter
2564 WHERE keyentryid = ?;",
2565 )
2566 .context("In load_key_parameters: prepare statement failed.")?;
2567
2568 let mut parameters: Vec<KeyParameter> = Vec::new();
2569
2570 let mut rows =
2571 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002572 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002573 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2574 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002575 parameters.push(
2576 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2577 .context("Failed to read KeyParameter.")?,
2578 );
2579 Ok(())
2580 })
2581 .context("In load_key_parameters.")?;
2582
2583 Ok(parameters)
2584 }
2585
Qi Wub9433b52020-12-01 14:52:46 +08002586 /// Decrements the usage count of a limited use key. This function first checks whether the
2587 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2588 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2589 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002590 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002591 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2592
Qi Wub9433b52020-12-01 14:52:46 +08002593 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2594 let limit: Option<i32> = tx
2595 .query_row(
2596 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2597 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2598 |row| row.get(0),
2599 )
2600 .optional()
2601 .context("Trying to load usage count")?;
2602
2603 let limit = limit
2604 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2605 .context("The Key no longer exists. Key is exhausted.")?;
2606
2607 tx.execute(
2608 "UPDATE persistent.keyparameter
2609 SET data = data - 1
2610 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2611 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2612 )
2613 .context("Failed to update key usage count.")?;
2614
2615 match limit {
2616 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002617 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002618 .context("Trying to mark limited use key for deletion."),
2619 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002620 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002621 }
2622 })
2623 .context("In check_and_update_key_usage_count.")
2624 }
2625
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002626 /// Load a key entry by the given key descriptor.
2627 /// It uses the `check_permission` callback to verify if the access is allowed
2628 /// given the key access tuple read from the database using `load_access_tuple`.
2629 /// With `load_bits` the caller may specify which blobs shall be loaded from
2630 /// the blob database.
2631 pub fn load_key_entry(
2632 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002633 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002634 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002635 load_bits: KeyEntryLoadBits,
2636 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002637 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2638 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002639 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2640
Janis Danisevskis66784c42021-01-27 08:40:25 -08002641 loop {
2642 match self.load_key_entry_internal(
2643 key,
2644 key_type,
2645 load_bits,
2646 caller_uid,
2647 &check_permission,
2648 ) {
2649 Ok(result) => break Ok(result),
2650 Err(e) => {
2651 if Self::is_locked_error(&e) {
2652 std::thread::sleep(std::time::Duration::from_micros(500));
2653 continue;
2654 } else {
2655 return Err(e).context("In load_key_entry.");
2656 }
2657 }
2658 }
2659 }
2660 }
2661
2662 fn load_key_entry_internal(
2663 &mut self,
2664 key: &KeyDescriptor,
2665 key_type: KeyType,
2666 load_bits: KeyEntryLoadBits,
2667 caller_uid: u32,
2668 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002669 ) -> Result<(KeyIdGuard, KeyEntry)> {
2670 // KEY ID LOCK 1/2
2671 // If we got a key descriptor with a key id we can get the lock right away.
2672 // Otherwise we have to defer it until we know the key id.
2673 let key_id_guard = match key.domain {
2674 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2675 _ => None,
2676 };
2677
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002678 let tx = self
2679 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002680 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002681 .context("In load_key_entry: Failed to initialize transaction.")?;
2682
2683 // Load the key_id and complete the access control tuple.
2684 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002685 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2686 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002687
2688 // Perform access control. It is vital that we return here if the permission is denied.
2689 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002690 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002691
Janis Danisevskisaec14592020-11-12 09:41:49 -08002692 // KEY ID LOCK 2/2
2693 // If we did not get a key id lock by now, it was because we got a key descriptor
2694 // without a key id. At this point we got the key id, so we can try and get a lock.
2695 // However, we cannot block here, because we are in the middle of the transaction.
2696 // So first we try to get the lock non blocking. If that fails, we roll back the
2697 // transaction and block until we get the lock. After we successfully got the lock,
2698 // we start a new transaction and load the access tuple again.
2699 //
2700 // We don't need to perform access control again, because we already established
2701 // that the caller had access to the given key. But we need to make sure that the
2702 // key id still exists. So we have to load the key entry by key id this time.
2703 let (key_id_guard, tx) = match key_id_guard {
2704 None => match KEY_ID_LOCK.try_get(key_id) {
2705 None => {
2706 // Roll back the transaction.
2707 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002708
Janis Danisevskisaec14592020-11-12 09:41:49 -08002709 // Block until we have a key id lock.
2710 let key_id_guard = KEY_ID_LOCK.get(key_id);
2711
2712 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002713 let tx = self
2714 .conn
2715 .unchecked_transaction()
2716 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002717
2718 Self::load_access_tuple(
2719 &tx,
2720 // This time we have to load the key by the retrieved key id, because the
2721 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002722 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002723 domain: Domain::KEY_ID,
2724 nspace: key_id,
2725 ..Default::default()
2726 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002727 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002728 caller_uid,
2729 )
2730 .context("In load_key_entry. (deferred key lock)")?;
2731 (key_id_guard, tx)
2732 }
2733 Some(l) => (l, tx),
2734 },
2735 Some(key_id_guard) => (key_id_guard, tx),
2736 };
2737
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002738 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2739 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002740
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002741 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2742
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002743 Ok((key_id_guard, key_entry))
2744 }
2745
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002746 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002747 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002748 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2749 .context("Trying to delete keyentry.")?;
2750 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2751 .context("Trying to delete keymetadata.")?;
2752 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2753 .context("Trying to delete keyparameters.")?;
2754 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2755 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002756 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002757 }
2758
2759 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002760 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002761 pub fn unbind_key(
2762 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002763 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002764 key_type: KeyType,
2765 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002766 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002767 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002768 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2769
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002770 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2771 let (key_id, access_key_descriptor, access_vector) =
2772 Self::load_access_tuple(tx, key, key_type, caller_uid)
2773 .context("Trying to get access tuple.")?;
2774
2775 // Perform access control. It is vital that we return here if the permission is denied.
2776 // So do not touch that '?' at the end.
2777 check_permission(&access_key_descriptor, access_vector)
2778 .context("While checking permission.")?;
2779
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002780 Self::mark_unreferenced(tx, key_id)
2781 .map(|need_gc| (need_gc, ()))
2782 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002783 })
2784 .context("In unbind_key.")
2785 }
2786
Max Bires8e93d2b2021-01-14 13:17:59 -08002787 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2788 tx.query_row(
2789 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2790 params![key_id],
2791 |row| row.get(0),
2792 )
2793 .context("In get_key_km_uuid.")
2794 }
2795
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002796 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2797 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2798 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002799 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2800
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002801 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2802 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2803 .context("In unbind_keys_for_namespace.");
2804 }
2805 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2806 tx.execute(
2807 "DELETE FROM persistent.keymetadata
2808 WHERE keyentryid IN (
2809 SELECT id FROM persistent.keyentry
2810 WHERE domain = ? AND namespace = ?
2811 );",
2812 params![domain.0, namespace],
2813 )
2814 .context("Trying to delete keymetadata.")?;
2815 tx.execute(
2816 "DELETE FROM persistent.keyparameter
2817 WHERE keyentryid IN (
2818 SELECT id FROM persistent.keyentry
2819 WHERE domain = ? AND namespace = ?
2820 );",
2821 params![domain.0, namespace],
2822 )
2823 .context("Trying to delete keyparameters.")?;
2824 tx.execute(
2825 "DELETE FROM persistent.grant
2826 WHERE keyentryid IN (
2827 SELECT id FROM persistent.keyentry
2828 WHERE domain = ? AND namespace = ?
2829 );",
2830 params![domain.0, namespace],
2831 )
2832 .context("Trying to delete grants.")?;
2833 tx.execute(
2834 "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;",
2835 params![domain.0, namespace],
2836 )
2837 .context("Trying to delete keyentry.")?;
2838 Ok(()).need_gc()
2839 })
2840 .context("In unbind_keys_for_namespace")
2841 }
2842
Hasini Gunasingheda895552021-01-27 19:34:37 +00002843 /// Delete the keys created on behalf of the user, denoted by the user id.
2844 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2845 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2846 /// The caller of this function should notify the gc if the returned value is true.
2847 pub fn unbind_keys_for_user(
2848 &mut self,
2849 user_id: u32,
2850 keep_non_super_encrypted_keys: bool,
2851 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002852 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2853
Hasini Gunasingheda895552021-01-27 19:34:37 +00002854 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2855 let mut stmt = tx
2856 .prepare(&format!(
2857 "SELECT id from persistent.keyentry
2858 WHERE (
2859 key_type = ?
2860 AND domain = ?
2861 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2862 AND state = ?
2863 ) OR (
2864 key_type = ?
2865 AND namespace = ?
2866 AND alias = ?
2867 AND state = ?
2868 );",
2869 aid_user_offset = AID_USER_OFFSET
2870 ))
2871 .context(concat!(
2872 "In unbind_keys_for_user. ",
2873 "Failed to prepare the query to find the keys created by apps."
2874 ))?;
2875
2876 let mut rows = stmt
2877 .query(params![
2878 // WHERE client key:
2879 KeyType::Client,
2880 Domain::APP.0 as u32,
2881 user_id,
2882 KeyLifeCycle::Live,
2883 // OR super key:
2884 KeyType::Super,
2885 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002886 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002887 KeyLifeCycle::Live
2888 ])
2889 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2890
2891 let mut key_ids: Vec<i64> = Vec::new();
2892 db_utils::with_rows_extract_all(&mut rows, |row| {
2893 key_ids
2894 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2895 Ok(())
2896 })
2897 .context("In unbind_keys_for_user.")?;
2898
2899 let mut notify_gc = false;
2900 for key_id in key_ids {
2901 if keep_non_super_encrypted_keys {
2902 // Load metadata and filter out non-super-encrypted keys.
2903 if let (_, Some((_, blob_metadata)), _, _) =
2904 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2905 .context("In unbind_keys_for_user: Trying to load blob info.")?
2906 {
2907 if blob_metadata.encrypted_by().is_none() {
2908 continue;
2909 }
2910 }
2911 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002912 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002913 .context("In unbind_keys_for_user.")?
2914 || notify_gc;
2915 }
2916 Ok(()).do_gc(notify_gc)
2917 })
2918 .context("In unbind_keys_for_user.")
2919 }
2920
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002921 fn load_key_components(
2922 tx: &Transaction,
2923 load_bits: KeyEntryLoadBits,
2924 key_id: i64,
2925 ) -> Result<KeyEntry> {
2926 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2927
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002928 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002929 Self::load_blob_components(key_id, load_bits, &tx)
2930 .context("In load_key_components.")?;
2931
Max Bires8e93d2b2021-01-14 13:17:59 -08002932 let parameters = Self::load_key_parameters(key_id, &tx)
2933 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002934
Max Bires8e93d2b2021-01-14 13:17:59 -08002935 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2936 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002937
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002938 Ok(KeyEntry {
2939 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002940 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002941 cert: cert_blob,
2942 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002943 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002944 parameters,
2945 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002946 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002947 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002948 }
2949
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002950 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2951 /// The key descriptors will have the domain, nspace, and alias field set.
2952 /// Domain must be APP or SELINUX, the caller must make sure of that.
2953 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002954 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2955
Janis Danisevskis66784c42021-01-27 08:40:25 -08002956 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2957 let mut stmt = tx
2958 .prepare(
2959 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002960 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002961 )
2962 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002963
Janis Danisevskis66784c42021-01-27 08:40:25 -08002964 let mut rows = stmt
2965 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2966 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002967
Janis Danisevskis66784c42021-01-27 08:40:25 -08002968 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2969 db_utils::with_rows_extract_all(&mut rows, |row| {
2970 descriptors.push(KeyDescriptor {
2971 domain,
2972 nspace: namespace,
2973 alias: Some(row.get(0).context("Trying to extract alias.")?),
2974 blob: None,
2975 });
2976 Ok(())
2977 })
2978 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002979 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002980 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002981 }
2982
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002983 /// Adds a grant to the grant table.
2984 /// Like `load_key_entry` this function loads the access tuple before
2985 /// it uses the callback for a permission check. Upon success,
2986 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2987 /// grant table. The new row will have a randomized id, which is used as
2988 /// grant id in the namespace field of the resulting KeyDescriptor.
2989 pub fn grant(
2990 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002991 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002992 caller_uid: u32,
2993 grantee_uid: u32,
2994 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002995 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002996 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002997 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2998
Janis Danisevskis66784c42021-01-27 08:40:25 -08002999 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3000 // Load the key_id and complete the access control tuple.
3001 // We ignore the access vector here because grants cannot be granted.
3002 // The access vector returned here expresses the permissions the
3003 // grantee has if key.domain == Domain::GRANT. But this vector
3004 // cannot include the grant permission by design, so there is no way the
3005 // subsequent permission check can pass.
3006 // We could check key.domain == Domain::GRANT and fail early.
3007 // But even if we load the access tuple by grant here, the permission
3008 // check denies the attempt to create a grant by grant descriptor.
3009 let (key_id, access_key_descriptor, _) =
3010 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3011 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003012
Janis Danisevskis66784c42021-01-27 08:40:25 -08003013 // Perform access control. It is vital that we return here if the permission
3014 // was denied. So do not touch that '?' at the end of the line.
3015 // This permission check checks if the caller has the grant permission
3016 // for the given key and in addition to all of the permissions
3017 // expressed in `access_vector`.
3018 check_permission(&access_key_descriptor, &access_vector)
3019 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003020
Janis Danisevskis66784c42021-01-27 08:40:25 -08003021 let grant_id = if let Some(grant_id) = tx
3022 .query_row(
3023 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003024 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003025 params![key_id, grantee_uid],
3026 |row| row.get(0),
3027 )
3028 .optional()
3029 .context("In grant: Failed get optional existing grant id.")?
3030 {
3031 tx.execute(
3032 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003033 SET access_vector = ?
3034 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003035 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003036 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003037 .context("In grant: Failed to update existing grant.")?;
3038 grant_id
3039 } else {
3040 Self::insert_with_retry(|id| {
3041 tx.execute(
3042 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3043 VALUES (?, ?, ?, ?);",
3044 params![id, grantee_uid, key_id, i32::from(access_vector)],
3045 )
3046 })
3047 .context("In grant")?
3048 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003049
Janis Danisevskis66784c42021-01-27 08:40:25 -08003050 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003051 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003052 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003053 }
3054
3055 /// This function checks permissions like `grant` and `load_key_entry`
3056 /// before removing a grant from the grant table.
3057 pub fn ungrant(
3058 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003059 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003060 caller_uid: u32,
3061 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003062 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003063 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003064 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3065
Janis Danisevskis66784c42021-01-27 08:40:25 -08003066 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3067 // Load the key_id and complete the access control tuple.
3068 // We ignore the access vector here because grants cannot be granted.
3069 let (key_id, access_key_descriptor, _) =
3070 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3071 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003072
Janis Danisevskis66784c42021-01-27 08:40:25 -08003073 // Perform access control. We must return here if the permission
3074 // was denied. So do not touch the '?' at the end of this line.
3075 check_permission(&access_key_descriptor)
3076 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003077
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 tx.execute(
3079 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003080 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003081 params![key_id, grantee_uid],
3082 )
3083 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003084
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003085 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003086 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003087 }
3088
Joel Galenson845f74b2020-09-09 14:11:55 -07003089 // Generates a random id and passes it to the given function, which will
3090 // try to insert it into a database. If that insertion fails, retry;
3091 // otherwise return the id.
3092 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3093 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003094 let newid: i64 = match random() {
3095 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3096 i => i,
3097 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003098 match inserter(newid) {
3099 // If the id already existed, try again.
3100 Err(rusqlite::Error::SqliteFailure(
3101 libsqlite3_sys::Error {
3102 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3103 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3104 },
3105 _,
3106 )) => (),
3107 Err(e) => {
3108 return Err(e).context("In insert_with_retry: failed to insert into database.")
3109 }
3110 _ => return Ok(newid),
3111 }
3112 }
3113 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003114
3115 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
3116 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003117 let _wp = wd::watch_millis("KeystoreDB::insert_auth_token", 500);
3118
Janis Danisevskis66784c42021-01-27 08:40:25 -08003119 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3120 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003121 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
3122 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
3123 params![
3124 auth_token.challenge,
3125 auth_token.userId,
3126 auth_token.authenticatorId,
3127 auth_token.authenticatorType.0 as i32,
3128 auth_token.timestamp.milliSeconds as i64,
3129 auth_token.mac,
3130 MonotonicRawTime::now(),
3131 ],
3132 )
3133 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003134 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003135 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003136 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003137
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003138 /// Find the newest auth token matching the given predicate.
3139 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003140 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003141 p: F,
3142 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
3143 where
3144 F: Fn(&AuthTokenEntry) -> bool,
3145 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003146 let _wp = wd::watch_millis("KeystoreDB::find_auth_token_entry", 500);
3147
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003148 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3149 let mut stmt = tx
3150 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
3151 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003152
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003153 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003154
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003155 while let Some(row) = rows.next().context("Failed to get next row.")? {
3156 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003157 HardwareAuthToken {
3158 challenge: row.get(1)?,
3159 userId: row.get(2)?,
3160 authenticatorId: row.get(3)?,
3161 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3162 timestamp: Timestamp { milliSeconds: row.get(5)? },
3163 mac: row.get(6)?,
3164 },
3165 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003166 );
3167 if p(&entry) {
3168 return Ok(Some((
3169 entry,
3170 Self::get_last_off_body(tx)
3171 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003172 )))
3173 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003174 }
3175 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003176 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003177 })
3178 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003179 }
3180
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003181 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003182 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003183 let _wp = wd::watch_millis("KeystoreDB::insert_last_off_body", 500);
3184
Janis Danisevskis66784c42021-01-27 08:40:25 -08003185 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3186 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003187 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3188 params!["last_off_body", last_off_body],
3189 )
3190 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003191 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003192 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003193 }
3194
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003195 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003196 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003197 let _wp = wd::watch_millis("KeystoreDB::update_last_off_body", 500);
3198
Janis Danisevskis66784c42021-01-27 08:40:25 -08003199 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3200 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003201 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3202 params![last_off_body, "last_off_body"],
3203 )
3204 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003205 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003206 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003207 }
3208
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003209 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003210 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003211 let _wp = wd::watch_millis("KeystoreDB::get_last_off_body", 500);
3212
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003213 tx.query_row(
3214 "SELECT value from perboot.metadata WHERE key = ?;",
3215 params!["last_off_body"],
3216 |row| Ok(row.get(0)?),
3217 )
3218 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003219 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003220}
3221
3222#[cfg(test)]
3223mod tests {
3224
3225 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003226 use crate::key_parameter::{
3227 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3228 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3229 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003230 use crate::key_perm_set;
3231 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003232 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003233 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003234 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3235 HardwareAuthToken::HardwareAuthToken,
3236 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003237 };
3238 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003239 Timestamp::Timestamp,
3240 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003241 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003242 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003243 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003244 use std::collections::BTreeMap;
3245 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003246 use std::sync::atomic::{AtomicU8, Ordering};
3247 use std::sync::Arc;
3248 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003249 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003250 #[cfg(disabled)]
3251 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003252
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003253 fn new_test_db() -> Result<KeystoreDB> {
3254 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3255
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003256 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003257 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003258 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003259 })?;
3260 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003261 }
3262
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003263 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3264 where
3265 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3266 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003267 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003268
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003269 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003270 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003271
3272 KeystoreDB::new(path, Some(gc))
3273 }
3274
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003275 fn rebind_alias(
3276 db: &mut KeystoreDB,
3277 newid: &KeyIdGuard,
3278 alias: &str,
3279 domain: Domain,
3280 namespace: i64,
3281 ) -> Result<bool> {
3282 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003283 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003284 })
3285 .context("In rebind_alias.")
3286 }
3287
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003288 #[test]
3289 fn datetime() -> Result<()> {
3290 let conn = Connection::open_in_memory()?;
3291 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3292 let now = SystemTime::now();
3293 let duration = Duration::from_secs(1000);
3294 let then = now.checked_sub(duration).unwrap();
3295 let soon = now.checked_add(duration).unwrap();
3296 conn.execute(
3297 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3298 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3299 )?;
3300 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3301 let mut rows = stmt.query(NO_PARAMS)?;
3302 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3303 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3304 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3305 assert!(rows.next()?.is_none());
3306 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3307 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3308 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3309 Ok(())
3310 }
3311
Joel Galenson0891bc12020-07-20 10:37:03 -07003312 // Ensure that we're using the "injected" random function, not the real one.
3313 #[test]
3314 fn test_mocked_random() {
3315 let rand1 = random();
3316 let rand2 = random();
3317 let rand3 = random();
3318 if rand1 == rand2 {
3319 assert_eq!(rand2 + 1, rand3);
3320 } else {
3321 assert_eq!(rand1 + 1, rand2);
3322 assert_eq!(rand2, rand3);
3323 }
3324 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003325
Joel Galenson26f4d012020-07-17 14:57:21 -07003326 // Test that we have the correct tables.
3327 #[test]
3328 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003329 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003330 let tables = db
3331 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003332 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003333 .query_map(params![], |row| row.get(0))?
3334 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003335 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003336 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003337 assert_eq!(tables[1], "blobmetadata");
3338 assert_eq!(tables[2], "grant");
3339 assert_eq!(tables[3], "keyentry");
3340 assert_eq!(tables[4], "keymetadata");
3341 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003342 let tables = db
3343 .conn
3344 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3345 .query_map(params![], |row| row.get(0))?
3346 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003347
3348 assert_eq!(tables.len(), 2);
3349 assert_eq!(tables[0], "authtoken");
3350 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003351 Ok(())
3352 }
3353
3354 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003355 fn test_auth_token_table_invariant() -> Result<()> {
3356 let mut db = new_test_db()?;
3357 let auth_token1 = HardwareAuthToken {
3358 challenge: i64::MAX,
3359 userId: 200,
3360 authenticatorId: 200,
3361 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3362 timestamp: Timestamp { milliSeconds: 500 },
3363 mac: String::from("mac").into_bytes(),
3364 };
3365 db.insert_auth_token(&auth_token1)?;
3366 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3367 assert_eq!(auth_tokens_returned.len(), 1);
3368
3369 // insert another auth token with the same values for the columns in the UNIQUE constraint
3370 // of the auth token table and different value for timestamp
3371 let auth_token2 = HardwareAuthToken {
3372 challenge: i64::MAX,
3373 userId: 200,
3374 authenticatorId: 200,
3375 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3376 timestamp: Timestamp { milliSeconds: 600 },
3377 mac: String::from("mac").into_bytes(),
3378 };
3379
3380 db.insert_auth_token(&auth_token2)?;
3381 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3382 assert_eq!(auth_tokens_returned.len(), 1);
3383
3384 if let Some(auth_token) = auth_tokens_returned.pop() {
3385 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3386 }
3387
3388 // insert another auth token with the different values for the columns in the UNIQUE
3389 // constraint of the auth token table
3390 let auth_token3 = HardwareAuthToken {
3391 challenge: i64::MAX,
3392 userId: 201,
3393 authenticatorId: 200,
3394 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3395 timestamp: Timestamp { milliSeconds: 600 },
3396 mac: String::from("mac").into_bytes(),
3397 };
3398
3399 db.insert_auth_token(&auth_token3)?;
3400 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3401 assert_eq!(auth_tokens_returned.len(), 2);
3402
3403 Ok(())
3404 }
3405
3406 // utility function for test_auth_token_table_invariant()
3407 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3408 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3409
3410 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3411 .query_map(NO_PARAMS, |row| {
3412 Ok(AuthTokenEntry::new(
3413 HardwareAuthToken {
3414 challenge: row.get(1)?,
3415 userId: row.get(2)?,
3416 authenticatorId: row.get(3)?,
3417 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3418 timestamp: Timestamp { milliSeconds: row.get(5)? },
3419 mac: row.get(6)?,
3420 },
3421 row.get(7)?,
3422 ))
3423 })?
3424 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3425 Ok(auth_token_entries)
3426 }
3427
3428 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003429 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003430 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003431 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003432
Janis Danisevskis66784c42021-01-27 08:40:25 -08003433 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003434 let entries = get_keyentry(&db)?;
3435 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003436
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003437 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003438
3439 let entries_new = get_keyentry(&db)?;
3440 assert_eq!(entries, entries_new);
3441 Ok(())
3442 }
3443
3444 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003445 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003446 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3447 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003448 }
3449
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003450 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003451
Janis Danisevskis66784c42021-01-27 08:40:25 -08003452 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3453 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003454
3455 let entries = get_keyentry(&db)?;
3456 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003457 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3458 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003459
3460 // Test that we must pass in a valid Domain.
3461 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003462 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003463 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003464 );
3465 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003466 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003467 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003468 );
3469 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003470 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003471 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003472 );
3473
3474 Ok(())
3475 }
3476
Joel Galenson33c04ad2020-08-03 11:04:38 -07003477 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003478 fn test_add_unsigned_key() -> Result<()> {
3479 let mut db = new_test_db()?;
3480 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3481 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3482 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3483 db.create_attestation_key_entry(
3484 &public_key,
3485 &raw_public_key,
3486 &private_key,
3487 &KEYSTORE_UUID,
3488 )?;
3489 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3490 assert_eq!(keys.len(), 1);
3491 assert_eq!(keys[0], public_key);
3492 Ok(())
3493 }
3494
3495 #[test]
3496 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3497 let mut db = new_test_db()?;
3498 let expiration_date: i64 = 20;
3499 let namespace: i64 = 30;
3500 let base_byte: u8 = 1;
3501 let loaded_values =
3502 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3503 let chain =
3504 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3505 assert_eq!(true, chain.is_some());
3506 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003507 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003508 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3509 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003510 Ok(())
3511 }
3512
3513 #[test]
3514 fn test_get_attestation_pool_status() -> Result<()> {
3515 let mut db = new_test_db()?;
3516 let namespace: i64 = 30;
3517 load_attestation_key_pool(
3518 &mut db, 10, /* expiration */
3519 namespace, 0x01, /* base_byte */
3520 )?;
3521 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3522 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3523 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3524 assert_eq!(status.expiring, 0);
3525 assert_eq!(status.attested, 3);
3526 assert_eq!(status.unassigned, 0);
3527 assert_eq!(status.total, 3);
3528 assert_eq!(
3529 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3530 1
3531 );
3532 assert_eq!(
3533 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3534 2
3535 );
3536 assert_eq!(
3537 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3538 3
3539 );
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 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003544 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003545 db.create_attestation_key_entry(
3546 &public_key,
3547 &raw_public_key,
3548 &private_key,
3549 &KEYSTORE_UUID,
3550 )?;
3551 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3552 assert_eq!(status.attested, 3);
3553 assert_eq!(status.unassigned, 0);
3554 assert_eq!(status.total, 4);
3555 db.store_signed_attestation_certificate_chain(
3556 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003557 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003558 &cert_chain,
3559 20,
3560 &KEYSTORE_UUID,
3561 )?;
3562 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3563 assert_eq!(status.attested, 4);
3564 assert_eq!(status.unassigned, 1);
3565 assert_eq!(status.total, 4);
3566 Ok(())
3567 }
3568
3569 #[test]
3570 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003571 let temp_dir =
3572 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3573 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003574 let expiration_date: i64 =
3575 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3576 let namespace: i64 = 30;
3577 let namespace_del1: i64 = 45;
3578 let namespace_del2: i64 = 60;
3579 let entry_values = load_attestation_key_pool(
3580 &mut db,
3581 expiration_date,
3582 namespace,
3583 0x01, /* base_byte */
3584 )?;
3585 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3586 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003587
3588 let blob_entry_row_count: u32 = db
3589 .conn
3590 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3591 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003592 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3593 // one key, one certificate chain, and one certificate.
3594 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003595
Max Bires2b2e6562020-09-22 11:22:36 -07003596 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3597
3598 let mut cert_chain =
3599 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003600 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003601 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003602 assert_eq!(entry_values.batch_cert, value.batch_cert);
3603 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003604 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003605
3606 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3607 Domain::APP,
3608 namespace_del1,
3609 &KEYSTORE_UUID,
3610 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003611 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003612 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3613 Domain::APP,
3614 namespace_del2,
3615 &KEYSTORE_UUID,
3616 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003617 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003618
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003619 // Give the garbage collector half a second to catch up.
3620 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003621
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003622 let blob_entry_row_count: u32 = db
3623 .conn
3624 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3625 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003626 // There shound be 3 blob entries left, because we deleted two of the attestation
3627 // key entries with three blobs each.
3628 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003629
Max Bires2b2e6562020-09-22 11:22:36 -07003630 Ok(())
3631 }
3632
3633 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003634 fn test_delete_all_attestation_keys() -> Result<()> {
3635 let mut db = new_test_db()?;
3636 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3637 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3638 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3639 let result = db.delete_all_attestation_keys()?;
3640
3641 // Give the garbage collector half a second to catch up.
3642 std::thread::sleep(Duration::from_millis(500));
3643
3644 // Attestation keys should be deleted, and the regular key should remain.
3645 assert_eq!(result, 2);
3646
3647 Ok(())
3648 }
3649
3650 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003651 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003652 fn extractor(
3653 ke: &KeyEntryRow,
3654 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3655 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003656 }
3657
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003658 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003659 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3660 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003661 let entries = get_keyentry(&db)?;
3662 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003663 assert_eq!(
3664 extractor(&entries[0]),
3665 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3666 );
3667 assert_eq!(
3668 extractor(&entries[1]),
3669 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3670 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003671
3672 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003673 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003674 let entries = get_keyentry(&db)?;
3675 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003676 assert_eq!(
3677 extractor(&entries[0]),
3678 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3679 );
3680 assert_eq!(
3681 extractor(&entries[1]),
3682 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3683 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003684
3685 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003686 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003687 let entries = get_keyentry(&db)?;
3688 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003689 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3690 assert_eq!(
3691 extractor(&entries[1]),
3692 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3693 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003694
3695 // Test that we must pass in a valid Domain.
3696 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003697 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003698 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003699 );
3700 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003701 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003702 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003703 );
3704 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003705 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003706 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003707 );
3708
3709 // Test that we correctly handle setting an alias for something that does not exist.
3710 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003711 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003712 "Expected to update a single entry but instead updated 0",
3713 );
3714 // Test that we correctly abort the transaction in this case.
3715 let entries = get_keyentry(&db)?;
3716 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003717 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3718 assert_eq!(
3719 extractor(&entries[1]),
3720 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3721 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003722
3723 Ok(())
3724 }
3725
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003726 #[test]
3727 fn test_grant_ungrant() -> Result<()> {
3728 const CALLER_UID: u32 = 15;
3729 const GRANTEE_UID: u32 = 12;
3730 const SELINUX_NAMESPACE: i64 = 7;
3731
3732 let mut db = new_test_db()?;
3733 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003734 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3735 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3736 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003737 )?;
3738 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003739 domain: super::Domain::APP,
3740 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003741 alias: Some("key".to_string()),
3742 blob: None,
3743 };
3744 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3745 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3746
3747 // Reset totally predictable random number generator in case we
3748 // are not the first test running on this thread.
3749 reset_random();
3750 let next_random = 0i64;
3751
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003752 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003753 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754 assert_eq!(*a, PVEC1);
3755 assert_eq!(
3756 *k,
3757 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003758 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003759 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003760 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003761 alias: Some("key".to_string()),
3762 blob: None,
3763 }
3764 );
3765 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003766 })
3767 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003768
3769 assert_eq!(
3770 app_granted_key,
3771 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003772 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003773 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003774 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775 alias: None,
3776 blob: None,
3777 }
3778 );
3779
3780 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003781 domain: super::Domain::SELINUX,
3782 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003783 alias: Some("yek".to_string()),
3784 blob: None,
3785 };
3786
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003787 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003788 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003789 assert_eq!(*a, PVEC1);
3790 assert_eq!(
3791 *k,
3792 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003793 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003794 // namespace must be the supplied SELinux
3795 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003796 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003797 alias: Some("yek".to_string()),
3798 blob: None,
3799 }
3800 );
3801 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003802 })
3803 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003804
3805 assert_eq!(
3806 selinux_granted_key,
3807 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003808 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003809 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003810 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003811 alias: None,
3812 blob: None,
3813 }
3814 );
3815
3816 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003817 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003818 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003819 assert_eq!(*a, PVEC2);
3820 assert_eq!(
3821 *k,
3822 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003823 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003824 // namespace must be the supplied SELinux
3825 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003826 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003827 alias: Some("yek".to_string()),
3828 blob: None,
3829 }
3830 );
3831 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003832 })
3833 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003834
3835 assert_eq!(
3836 selinux_granted_key,
3837 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003838 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003839 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003840 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003841 alias: None,
3842 blob: None,
3843 }
3844 );
3845
3846 {
3847 // Limiting scope of stmt, because it borrows db.
3848 let mut stmt = db
3849 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003850 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003851 let mut rows =
3852 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3853 Ok((
3854 row.get(0)?,
3855 row.get(1)?,
3856 row.get(2)?,
3857 KeyPermSet::from(row.get::<_, i32>(3)?),
3858 ))
3859 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003860
3861 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003862 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003863 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003864 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003865 assert!(rows.next().is_none());
3866 }
3867
3868 debug_dump_keyentry_table(&mut db)?;
3869 println!("app_key {:?}", app_key);
3870 println!("selinux_key {:?}", selinux_key);
3871
Janis Danisevskis66784c42021-01-27 08:40:25 -08003872 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3873 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003874
3875 Ok(())
3876 }
3877
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003878 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003879 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3880 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3881
3882 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003883 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003884 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003885 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003886 let mut blob_metadata = BlobMetaData::new();
3887 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3888 db.set_blob(
3889 &key_id,
3890 SubComponentType::KEY_BLOB,
3891 Some(TEST_KEY_BLOB),
3892 Some(&blob_metadata),
3893 )?;
3894 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3895 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003896 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003897
3898 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003899 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003900 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003901 )?;
3902 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003903 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3904 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003905 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003906 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003907 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003908 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003909 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003910 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003911 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003912
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003913 drop(rows);
3914 drop(stmt);
3915
3916 assert_eq!(
3917 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3918 BlobMetaData::load_from_db(id, tx).no_gc()
3919 })
3920 .expect("Should find blob metadata."),
3921 blob_metadata
3922 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003923 Ok(())
3924 }
3925
3926 static TEST_ALIAS: &str = "my super duper key";
3927
3928 #[test]
3929 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3930 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003931 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003932 .context("test_insert_and_load_full_keyentry_domain_app")?
3933 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003934 let (_key_guard, key_entry) = db
3935 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003936 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003937 domain: Domain::APP,
3938 nspace: 0,
3939 alias: Some(TEST_ALIAS.to_string()),
3940 blob: None,
3941 },
3942 KeyType::Client,
3943 KeyEntryLoadBits::BOTH,
3944 1,
3945 |_k, _av| Ok(()),
3946 )
3947 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003948 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003949
3950 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003951 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003952 domain: Domain::APP,
3953 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003954 alias: Some(TEST_ALIAS.to_string()),
3955 blob: None,
3956 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003957 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003958 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003959 |_, _| Ok(()),
3960 )
3961 .unwrap();
3962
3963 assert_eq!(
3964 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3965 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003966 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003967 domain: Domain::APP,
3968 nspace: 0,
3969 alias: Some(TEST_ALIAS.to_string()),
3970 blob: None,
3971 },
3972 KeyType::Client,
3973 KeyEntryLoadBits::NONE,
3974 1,
3975 |_k, _av| Ok(()),
3976 )
3977 .unwrap_err()
3978 .root_cause()
3979 .downcast_ref::<KsError>()
3980 );
3981
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003982 Ok(())
3983 }
3984
3985 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003986 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3987 let mut db = new_test_db()?;
3988
3989 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003990 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003991 domain: Domain::APP,
3992 nspace: 1,
3993 alias: Some(TEST_ALIAS.to_string()),
3994 blob: None,
3995 },
3996 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003997 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003998 )
3999 .expect("Trying to insert cert.");
4000
4001 let (_key_guard, mut key_entry) = db
4002 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004003 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004004 domain: Domain::APP,
4005 nspace: 1,
4006 alias: Some(TEST_ALIAS.to_string()),
4007 blob: None,
4008 },
4009 KeyType::Client,
4010 KeyEntryLoadBits::PUBLIC,
4011 1,
4012 |_k, _av| Ok(()),
4013 )
4014 .expect("Trying to read certificate entry.");
4015
4016 assert!(key_entry.pure_cert());
4017 assert!(key_entry.cert().is_none());
4018 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4019
4020 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004021 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004022 domain: Domain::APP,
4023 nspace: 1,
4024 alias: Some(TEST_ALIAS.to_string()),
4025 blob: None,
4026 },
4027 KeyType::Client,
4028 1,
4029 |_, _| Ok(()),
4030 )
4031 .unwrap();
4032
4033 assert_eq!(
4034 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4035 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004036 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004037 domain: Domain::APP,
4038 nspace: 1,
4039 alias: Some(TEST_ALIAS.to_string()),
4040 blob: None,
4041 },
4042 KeyType::Client,
4043 KeyEntryLoadBits::NONE,
4044 1,
4045 |_k, _av| Ok(()),
4046 )
4047 .unwrap_err()
4048 .root_cause()
4049 .downcast_ref::<KsError>()
4050 );
4051
4052 Ok(())
4053 }
4054
4055 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004056 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4057 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004058 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004059 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4060 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004061 let (_key_guard, key_entry) = db
4062 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004063 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004064 domain: Domain::SELINUX,
4065 nspace: 1,
4066 alias: Some(TEST_ALIAS.to_string()),
4067 blob: None,
4068 },
4069 KeyType::Client,
4070 KeyEntryLoadBits::BOTH,
4071 1,
4072 |_k, _av| Ok(()),
4073 )
4074 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004075 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004076
4077 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004078 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004079 domain: Domain::SELINUX,
4080 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004081 alias: Some(TEST_ALIAS.to_string()),
4082 blob: None,
4083 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004084 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004085 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004086 |_, _| Ok(()),
4087 )
4088 .unwrap();
4089
4090 assert_eq!(
4091 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4092 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004093 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004094 domain: Domain::SELINUX,
4095 nspace: 1,
4096 alias: Some(TEST_ALIAS.to_string()),
4097 blob: None,
4098 },
4099 KeyType::Client,
4100 KeyEntryLoadBits::NONE,
4101 1,
4102 |_k, _av| Ok(()),
4103 )
4104 .unwrap_err()
4105 .root_cause()
4106 .downcast_ref::<KsError>()
4107 );
4108
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004109 Ok(())
4110 }
4111
4112 #[test]
4113 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4114 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004115 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004116 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4117 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004118 let (_, key_entry) = db
4119 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004120 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004121 KeyType::Client,
4122 KeyEntryLoadBits::BOTH,
4123 1,
4124 |_k, _av| Ok(()),
4125 )
4126 .unwrap();
4127
Qi Wub9433b52020-12-01 14:52:46 +08004128 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004129
4130 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004131 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004132 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004133 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004134 |_, _| Ok(()),
4135 )
4136 .unwrap();
4137
4138 assert_eq!(
4139 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4140 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004141 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004142 KeyType::Client,
4143 KeyEntryLoadBits::NONE,
4144 1,
4145 |_k, _av| Ok(()),
4146 )
4147 .unwrap_err()
4148 .root_cause()
4149 .downcast_ref::<KsError>()
4150 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004151
4152 Ok(())
4153 }
4154
4155 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004156 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4157 let mut db = new_test_db()?;
4158 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4159 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4160 .0;
4161 // Update the usage count of the limited use key.
4162 db.check_and_update_key_usage_count(key_id)?;
4163
4164 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004165 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004166 KeyType::Client,
4167 KeyEntryLoadBits::BOTH,
4168 1,
4169 |_k, _av| Ok(()),
4170 )?;
4171
4172 // The usage count is decremented now.
4173 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4174
4175 Ok(())
4176 }
4177
4178 #[test]
4179 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4180 let mut db = new_test_db()?;
4181 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4182 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4183 .0;
4184 // Update the usage count of the limited use key.
4185 db.check_and_update_key_usage_count(key_id).expect(concat!(
4186 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4187 "This should succeed."
4188 ));
4189
4190 // Try to update the exhausted limited use key.
4191 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4192 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4193 "This should fail."
4194 ));
4195 assert_eq!(
4196 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4197 e.root_cause().downcast_ref::<KsError>().unwrap()
4198 );
4199
4200 Ok(())
4201 }
4202
4203 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004204 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4205 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004206 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004207 .context("test_insert_and_load_full_keyentry_from_grant")?
4208 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004209
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004210 let granted_key = db
4211 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004212 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004213 domain: Domain::APP,
4214 nspace: 0,
4215 alias: Some(TEST_ALIAS.to_string()),
4216 blob: None,
4217 },
4218 1,
4219 2,
4220 key_perm_set![KeyPerm::use_()],
4221 |_k, _av| Ok(()),
4222 )
4223 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004224
4225 debug_dump_grant_table(&mut db)?;
4226
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004227 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004228 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4229 assert_eq!(Domain::GRANT, k.domain);
4230 assert!(av.unwrap().includes(KeyPerm::use_()));
4231 Ok(())
4232 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004233 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004234
Qi Wub9433b52020-12-01 14:52:46 +08004235 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004236
Janis Danisevskis66784c42021-01-27 08:40:25 -08004237 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004238
4239 assert_eq!(
4240 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4241 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004242 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004243 KeyType::Client,
4244 KeyEntryLoadBits::NONE,
4245 2,
4246 |_k, _av| Ok(()),
4247 )
4248 .unwrap_err()
4249 .root_cause()
4250 .downcast_ref::<KsError>()
4251 );
4252
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004253 Ok(())
4254 }
4255
Janis Danisevskis45760022021-01-19 16:34:10 -08004256 // This test attempts to load a key by key id while the caller is not the owner
4257 // but a grant exists for the given key and the caller.
4258 #[test]
4259 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4260 let mut db = new_test_db()?;
4261 const OWNER_UID: u32 = 1u32;
4262 const GRANTEE_UID: u32 = 2u32;
4263 const SOMEONE_ELSE_UID: u32 = 3u32;
4264 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4265 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4266 .0;
4267
4268 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004269 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004270 domain: Domain::APP,
4271 nspace: 0,
4272 alias: Some(TEST_ALIAS.to_string()),
4273 blob: None,
4274 },
4275 OWNER_UID,
4276 GRANTEE_UID,
4277 key_perm_set![KeyPerm::use_()],
4278 |_k, _av| Ok(()),
4279 )
4280 .unwrap();
4281
4282 debug_dump_grant_table(&mut db)?;
4283
4284 let id_descriptor =
4285 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4286
4287 let (_, key_entry) = db
4288 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004289 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004290 KeyType::Client,
4291 KeyEntryLoadBits::BOTH,
4292 GRANTEE_UID,
4293 |k, av| {
4294 assert_eq!(Domain::APP, k.domain);
4295 assert_eq!(OWNER_UID as i64, k.nspace);
4296 assert!(av.unwrap().includes(KeyPerm::use_()));
4297 Ok(())
4298 },
4299 )
4300 .unwrap();
4301
4302 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4303
4304 let (_, key_entry) = db
4305 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004306 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004307 KeyType::Client,
4308 KeyEntryLoadBits::BOTH,
4309 SOMEONE_ELSE_UID,
4310 |k, av| {
4311 assert_eq!(Domain::APP, k.domain);
4312 assert_eq!(OWNER_UID as i64, k.nspace);
4313 assert!(av.is_none());
4314 Ok(())
4315 },
4316 )
4317 .unwrap();
4318
4319 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4320
Janis Danisevskis66784c42021-01-27 08:40:25 -08004321 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004322
4323 assert_eq!(
4324 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4325 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004326 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004327 KeyType::Client,
4328 KeyEntryLoadBits::NONE,
4329 GRANTEE_UID,
4330 |_k, _av| Ok(()),
4331 )
4332 .unwrap_err()
4333 .root_cause()
4334 .downcast_ref::<KsError>()
4335 );
4336
4337 Ok(())
4338 }
4339
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004340 // Creates a key migrates it to a different location and then tries to access it by the old
4341 // and new location.
4342 #[test]
4343 fn test_migrate_key_app_to_app() -> Result<()> {
4344 let mut db = new_test_db()?;
4345 const SOURCE_UID: u32 = 1u32;
4346 const DESTINATION_UID: u32 = 2u32;
4347 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4348 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4349 let key_id_guard =
4350 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4351 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4352
4353 let source_descriptor: KeyDescriptor = KeyDescriptor {
4354 domain: Domain::APP,
4355 nspace: -1,
4356 alias: Some(SOURCE_ALIAS.to_string()),
4357 blob: None,
4358 };
4359
4360 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4361 domain: Domain::APP,
4362 nspace: -1,
4363 alias: Some(DESTINATION_ALIAS.to_string()),
4364 blob: None,
4365 };
4366
4367 let key_id = key_id_guard.id();
4368
4369 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4370 Ok(())
4371 })
4372 .unwrap();
4373
4374 let (_, key_entry) = db
4375 .load_key_entry(
4376 &destination_descriptor,
4377 KeyType::Client,
4378 KeyEntryLoadBits::BOTH,
4379 DESTINATION_UID,
4380 |k, av| {
4381 assert_eq!(Domain::APP, k.domain);
4382 assert_eq!(DESTINATION_UID as i64, k.nspace);
4383 assert!(av.is_none());
4384 Ok(())
4385 },
4386 )
4387 .unwrap();
4388
4389 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4390
4391 assert_eq!(
4392 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4393 db.load_key_entry(
4394 &source_descriptor,
4395 KeyType::Client,
4396 KeyEntryLoadBits::NONE,
4397 SOURCE_UID,
4398 |_k, _av| Ok(()),
4399 )
4400 .unwrap_err()
4401 .root_cause()
4402 .downcast_ref::<KsError>()
4403 );
4404
4405 Ok(())
4406 }
4407
4408 // Creates a key migrates it to a different location and then tries to access it by the old
4409 // and new location.
4410 #[test]
4411 fn test_migrate_key_app_to_selinux() -> Result<()> {
4412 let mut db = new_test_db()?;
4413 const SOURCE_UID: u32 = 1u32;
4414 const DESTINATION_UID: u32 = 2u32;
4415 const DESTINATION_NAMESPACE: i64 = 1000i64;
4416 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4417 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4418 let key_id_guard =
4419 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4420 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4421
4422 let source_descriptor: KeyDescriptor = KeyDescriptor {
4423 domain: Domain::APP,
4424 nspace: -1,
4425 alias: Some(SOURCE_ALIAS.to_string()),
4426 blob: None,
4427 };
4428
4429 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4430 domain: Domain::SELINUX,
4431 nspace: DESTINATION_NAMESPACE,
4432 alias: Some(DESTINATION_ALIAS.to_string()),
4433 blob: None,
4434 };
4435
4436 let key_id = key_id_guard.id();
4437
4438 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4439 Ok(())
4440 })
4441 .unwrap();
4442
4443 let (_, key_entry) = db
4444 .load_key_entry(
4445 &destination_descriptor,
4446 KeyType::Client,
4447 KeyEntryLoadBits::BOTH,
4448 DESTINATION_UID,
4449 |k, av| {
4450 assert_eq!(Domain::SELINUX, k.domain);
4451 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4452 assert!(av.is_none());
4453 Ok(())
4454 },
4455 )
4456 .unwrap();
4457
4458 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4459
4460 assert_eq!(
4461 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4462 db.load_key_entry(
4463 &source_descriptor,
4464 KeyType::Client,
4465 KeyEntryLoadBits::NONE,
4466 SOURCE_UID,
4467 |_k, _av| Ok(()),
4468 )
4469 .unwrap_err()
4470 .root_cause()
4471 .downcast_ref::<KsError>()
4472 );
4473
4474 Ok(())
4475 }
4476
4477 // Creates two keys and tries to migrate the first to the location of the second which
4478 // is expected to fail.
4479 #[test]
4480 fn test_migrate_key_destination_occupied() -> Result<()> {
4481 let mut db = new_test_db()?;
4482 const SOURCE_UID: u32 = 1u32;
4483 const DESTINATION_UID: u32 = 2u32;
4484 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4485 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4486 let key_id_guard =
4487 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4488 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4489 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4490 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4491
4492 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4493 domain: Domain::APP,
4494 nspace: -1,
4495 alias: Some(DESTINATION_ALIAS.to_string()),
4496 blob: None,
4497 };
4498
4499 assert_eq!(
4500 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4501 db.migrate_key_namespace(
4502 key_id_guard,
4503 &destination_descriptor,
4504 DESTINATION_UID,
4505 |_k| Ok(())
4506 )
4507 .unwrap_err()
4508 .root_cause()
4509 .downcast_ref::<KsError>()
4510 );
4511
4512 Ok(())
4513 }
4514
Janis Danisevskisaec14592020-11-12 09:41:49 -08004515 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4516
Janis Danisevskisaec14592020-11-12 09:41:49 -08004517 #[test]
4518 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4519 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004520 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4521 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004522 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004523 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004524 .context("test_insert_and_load_full_keyentry_domain_app")?
4525 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004526 let (_key_guard, key_entry) = db
4527 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004528 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004529 domain: Domain::APP,
4530 nspace: 0,
4531 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4532 blob: None,
4533 },
4534 KeyType::Client,
4535 KeyEntryLoadBits::BOTH,
4536 33,
4537 |_k, _av| Ok(()),
4538 )
4539 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004540 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004541 let state = Arc::new(AtomicU8::new(1));
4542 let state2 = state.clone();
4543
4544 // Spawning a second thread that attempts to acquire the key id lock
4545 // for the same key as the primary thread. The primary thread then
4546 // waits, thereby forcing the secondary thread into the second stage
4547 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4548 // The test succeeds if the secondary thread observes the transition
4549 // of `state` from 1 to 2, despite having a whole second to overtake
4550 // the primary thread.
4551 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004552 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004553 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004554 assert!(db
4555 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004556 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004557 domain: Domain::APP,
4558 nspace: 0,
4559 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4560 blob: None,
4561 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004562 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004563 KeyEntryLoadBits::BOTH,
4564 33,
4565 |_k, _av| Ok(()),
4566 )
4567 .is_ok());
4568 // We should only see a 2 here because we can only return
4569 // from load_key_entry when the `_key_guard` expires,
4570 // which happens at the end of the scope.
4571 assert_eq!(2, state2.load(Ordering::Relaxed));
4572 });
4573
4574 thread::sleep(std::time::Duration::from_millis(1000));
4575
4576 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4577
4578 // Return the handle from this scope so we can join with the
4579 // secondary thread after the key id lock has expired.
4580 handle
4581 // This is where the `_key_guard` goes out of scope,
4582 // which is the reason for concurrent load_key_entry on the same key
4583 // to unblock.
4584 };
4585 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4586 // main test thread. We will not see failing asserts in secondary threads otherwise.
4587 handle.join().unwrap();
4588 Ok(())
4589 }
4590
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004591 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004592 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004593 let temp_dir =
4594 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4595
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004596 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4597 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004598
4599 let _tx1 = db1
4600 .conn
4601 .transaction_with_behavior(TransactionBehavior::Immediate)
4602 .expect("Failed to create first transaction.");
4603
4604 let error = db2
4605 .conn
4606 .transaction_with_behavior(TransactionBehavior::Immediate)
4607 .context("Transaction begin failed.")
4608 .expect_err("This should fail.");
4609 let root_cause = error.root_cause();
4610 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4611 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4612 {
4613 return;
4614 }
4615 panic!(
4616 "Unexpected error {:?} \n{:?} \n{:?}",
4617 error,
4618 root_cause,
4619 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4620 )
4621 }
4622
4623 #[cfg(disabled)]
4624 #[test]
4625 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4626 let temp_dir = Arc::new(
4627 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4628 .expect("Failed to create temp dir."),
4629 );
4630
4631 let test_begin = Instant::now();
4632
4633 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4634 const KEY_COUNT: u32 = 500u32;
4635 const OPEN_DB_COUNT: u32 = 50u32;
4636
4637 let mut actual_key_count = KEY_COUNT;
4638 // First insert KEY_COUNT keys.
4639 for count in 0..KEY_COUNT {
4640 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4641 actual_key_count = count;
4642 break;
4643 }
4644 let alias = format!("test_alias_{}", count);
4645 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4646 .expect("Failed to make key entry.");
4647 }
4648
4649 // Insert more keys from a different thread and into a different namespace.
4650 let temp_dir1 = temp_dir.clone();
4651 let handle1 = thread::spawn(move || {
4652 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4653
4654 for count in 0..actual_key_count {
4655 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4656 return;
4657 }
4658 let alias = format!("test_alias_{}", count);
4659 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4660 .expect("Failed to make key entry.");
4661 }
4662
4663 // then unbind them again.
4664 for count in 0..actual_key_count {
4665 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4666 return;
4667 }
4668 let key = KeyDescriptor {
4669 domain: Domain::APP,
4670 nspace: -1,
4671 alias: Some(format!("test_alias_{}", count)),
4672 blob: None,
4673 };
4674 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4675 }
4676 });
4677
4678 // And start unbinding the first set of keys.
4679 let temp_dir2 = temp_dir.clone();
4680 let handle2 = thread::spawn(move || {
4681 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4682
4683 for count in 0..actual_key_count {
4684 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4685 return;
4686 }
4687 let key = KeyDescriptor {
4688 domain: Domain::APP,
4689 nspace: -1,
4690 alias: Some(format!("test_alias_{}", count)),
4691 blob: None,
4692 };
4693 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4694 }
4695 });
4696
4697 let stop_deleting = Arc::new(AtomicU8::new(0));
4698 let stop_deleting2 = stop_deleting.clone();
4699
4700 // And delete anything that is unreferenced keys.
4701 let temp_dir3 = temp_dir.clone();
4702 let handle3 = thread::spawn(move || {
4703 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4704
4705 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4706 while let Some((key_guard, _key)) =
4707 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4708 {
4709 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4710 return;
4711 }
4712 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4713 }
4714 std::thread::sleep(std::time::Duration::from_millis(100));
4715 }
4716 });
4717
4718 // While a lot of inserting and deleting is going on we have to open database connections
4719 // successfully and use them.
4720 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4721 // out of scope.
4722 #[allow(clippy::redundant_clone)]
4723 let temp_dir4 = temp_dir.clone();
4724 let handle4 = thread::spawn(move || {
4725 for count in 0..OPEN_DB_COUNT {
4726 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4727 return;
4728 }
4729 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4730
4731 let alias = format!("test_alias_{}", count);
4732 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4733 .expect("Failed to make key entry.");
4734 let key = KeyDescriptor {
4735 domain: Domain::APP,
4736 nspace: -1,
4737 alias: Some(alias),
4738 blob: None,
4739 };
4740 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4741 }
4742 });
4743
4744 handle1.join().expect("Thread 1 panicked.");
4745 handle2.join().expect("Thread 2 panicked.");
4746 handle4.join().expect("Thread 4 panicked.");
4747
4748 stop_deleting.store(1, Ordering::Relaxed);
4749 handle3.join().expect("Thread 3 panicked.");
4750
4751 Ok(())
4752 }
4753
4754 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004755 fn list() -> Result<()> {
4756 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004757 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004758 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4759 (Domain::APP, 1, "test1"),
4760 (Domain::APP, 1, "test2"),
4761 (Domain::APP, 1, "test3"),
4762 (Domain::APP, 1, "test4"),
4763 (Domain::APP, 1, "test5"),
4764 (Domain::APP, 1, "test6"),
4765 (Domain::APP, 1, "test7"),
4766 (Domain::APP, 2, "test1"),
4767 (Domain::APP, 2, "test2"),
4768 (Domain::APP, 2, "test3"),
4769 (Domain::APP, 2, "test4"),
4770 (Domain::APP, 2, "test5"),
4771 (Domain::APP, 2, "test6"),
4772 (Domain::APP, 2, "test8"),
4773 (Domain::SELINUX, 100, "test1"),
4774 (Domain::SELINUX, 100, "test2"),
4775 (Domain::SELINUX, 100, "test3"),
4776 (Domain::SELINUX, 100, "test4"),
4777 (Domain::SELINUX, 100, "test5"),
4778 (Domain::SELINUX, 100, "test6"),
4779 (Domain::SELINUX, 100, "test9"),
4780 ];
4781
4782 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4783 .iter()
4784 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004785 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4786 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004787 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4788 });
4789 (entry.id(), *ns)
4790 })
4791 .collect();
4792
4793 for (domain, namespace) in
4794 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4795 {
4796 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4797 .iter()
4798 .filter_map(|(domain, ns, alias)| match ns {
4799 ns if *ns == *namespace => Some(KeyDescriptor {
4800 domain: *domain,
4801 nspace: *ns,
4802 alias: Some(alias.to_string()),
4803 blob: None,
4804 }),
4805 _ => None,
4806 })
4807 .collect();
4808 list_o_descriptors.sort();
4809 let mut list_result = db.list(*domain, *namespace)?;
4810 list_result.sort();
4811 assert_eq!(list_o_descriptors, list_result);
4812
4813 let mut list_o_ids: Vec<i64> = list_o_descriptors
4814 .into_iter()
4815 .map(|d| {
4816 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004817 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004818 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004819 KeyType::Client,
4820 KeyEntryLoadBits::NONE,
4821 *namespace as u32,
4822 |_, _| Ok(()),
4823 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004824 .unwrap();
4825 entry.id()
4826 })
4827 .collect();
4828 list_o_ids.sort_unstable();
4829 let mut loaded_entries: Vec<i64> = list_o_keys
4830 .iter()
4831 .filter_map(|(id, ns)| match ns {
4832 ns if *ns == *namespace => Some(*id),
4833 _ => None,
4834 })
4835 .collect();
4836 loaded_entries.sort_unstable();
4837 assert_eq!(list_o_ids, loaded_entries);
4838 }
4839 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4840
4841 Ok(())
4842 }
4843
Joel Galenson0891bc12020-07-20 10:37:03 -07004844 // Helpers
4845
4846 // Checks that the given result is an error containing the given string.
4847 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4848 let error_str = format!(
4849 "{:#?}",
4850 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4851 );
4852 assert!(
4853 error_str.contains(target),
4854 "The string \"{}\" should contain \"{}\"",
4855 error_str,
4856 target
4857 );
4858 }
4859
Joel Galenson2aab4432020-07-22 15:27:57 -07004860 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004861 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004862 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004863 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004864 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004865 namespace: Option<i64>,
4866 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004867 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004868 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004869 }
4870
4871 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4872 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004873 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004874 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004875 Ok(KeyEntryRow {
4876 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004877 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004878 domain: match row.get(2)? {
4879 Some(i) => Some(Domain(i)),
4880 None => None,
4881 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004882 namespace: row.get(3)?,
4883 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004884 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004885 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004886 })
4887 })?
4888 .map(|r| r.context("Could not read keyentry row."))
4889 .collect::<Result<Vec<_>>>()
4890 }
4891
Max Biresb2e1d032021-02-08 21:35:05 -08004892 struct RemoteProvValues {
4893 cert_chain: Vec<u8>,
4894 priv_key: Vec<u8>,
4895 batch_cert: Vec<u8>,
4896 }
4897
Max Bires2b2e6562020-09-22 11:22:36 -07004898 fn load_attestation_key_pool(
4899 db: &mut KeystoreDB,
4900 expiration_date: i64,
4901 namespace: i64,
4902 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004903 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004904 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4905 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4906 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4907 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004908 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004909 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4910 db.store_signed_attestation_certificate_chain(
4911 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004912 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004913 &cert_chain,
4914 expiration_date,
4915 &KEYSTORE_UUID,
4916 )?;
4917 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004918 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004919 }
4920
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004921 // Note: The parameters and SecurityLevel associations are nonsensical. This
4922 // collection is only used to check if the parameters are preserved as expected by the
4923 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004924 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4925 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004926 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4927 KeyParameter::new(
4928 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4929 SecurityLevel::TRUSTED_ENVIRONMENT,
4930 ),
4931 KeyParameter::new(
4932 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4933 SecurityLevel::TRUSTED_ENVIRONMENT,
4934 ),
4935 KeyParameter::new(
4936 KeyParameterValue::Algorithm(Algorithm::RSA),
4937 SecurityLevel::TRUSTED_ENVIRONMENT,
4938 ),
4939 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4940 KeyParameter::new(
4941 KeyParameterValue::BlockMode(BlockMode::ECB),
4942 SecurityLevel::TRUSTED_ENVIRONMENT,
4943 ),
4944 KeyParameter::new(
4945 KeyParameterValue::BlockMode(BlockMode::GCM),
4946 SecurityLevel::TRUSTED_ENVIRONMENT,
4947 ),
4948 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4949 KeyParameter::new(
4950 KeyParameterValue::Digest(Digest::MD5),
4951 SecurityLevel::TRUSTED_ENVIRONMENT,
4952 ),
4953 KeyParameter::new(
4954 KeyParameterValue::Digest(Digest::SHA_2_224),
4955 SecurityLevel::TRUSTED_ENVIRONMENT,
4956 ),
4957 KeyParameter::new(
4958 KeyParameterValue::Digest(Digest::SHA_2_256),
4959 SecurityLevel::STRONGBOX,
4960 ),
4961 KeyParameter::new(
4962 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4963 SecurityLevel::TRUSTED_ENVIRONMENT,
4964 ),
4965 KeyParameter::new(
4966 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4967 SecurityLevel::TRUSTED_ENVIRONMENT,
4968 ),
4969 KeyParameter::new(
4970 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4971 SecurityLevel::STRONGBOX,
4972 ),
4973 KeyParameter::new(
4974 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4975 SecurityLevel::TRUSTED_ENVIRONMENT,
4976 ),
4977 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4978 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4979 KeyParameter::new(
4980 KeyParameterValue::EcCurve(EcCurve::P_224),
4981 SecurityLevel::TRUSTED_ENVIRONMENT,
4982 ),
4983 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4984 KeyParameter::new(
4985 KeyParameterValue::EcCurve(EcCurve::P_384),
4986 SecurityLevel::TRUSTED_ENVIRONMENT,
4987 ),
4988 KeyParameter::new(
4989 KeyParameterValue::EcCurve(EcCurve::P_521),
4990 SecurityLevel::TRUSTED_ENVIRONMENT,
4991 ),
4992 KeyParameter::new(
4993 KeyParameterValue::RSAPublicExponent(3),
4994 SecurityLevel::TRUSTED_ENVIRONMENT,
4995 ),
4996 KeyParameter::new(
4997 KeyParameterValue::IncludeUniqueID,
4998 SecurityLevel::TRUSTED_ENVIRONMENT,
4999 ),
5000 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5001 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5002 KeyParameter::new(
5003 KeyParameterValue::ActiveDateTime(1234567890),
5004 SecurityLevel::STRONGBOX,
5005 ),
5006 KeyParameter::new(
5007 KeyParameterValue::OriginationExpireDateTime(1234567890),
5008 SecurityLevel::TRUSTED_ENVIRONMENT,
5009 ),
5010 KeyParameter::new(
5011 KeyParameterValue::UsageExpireDateTime(1234567890),
5012 SecurityLevel::TRUSTED_ENVIRONMENT,
5013 ),
5014 KeyParameter::new(
5015 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5016 SecurityLevel::TRUSTED_ENVIRONMENT,
5017 ),
5018 KeyParameter::new(
5019 KeyParameterValue::MaxUsesPerBoot(1234567890),
5020 SecurityLevel::TRUSTED_ENVIRONMENT,
5021 ),
5022 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5023 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5024 KeyParameter::new(
5025 KeyParameterValue::NoAuthRequired,
5026 SecurityLevel::TRUSTED_ENVIRONMENT,
5027 ),
5028 KeyParameter::new(
5029 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5030 SecurityLevel::TRUSTED_ENVIRONMENT,
5031 ),
5032 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5033 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5034 KeyParameter::new(
5035 KeyParameterValue::TrustedUserPresenceRequired,
5036 SecurityLevel::TRUSTED_ENVIRONMENT,
5037 ),
5038 KeyParameter::new(
5039 KeyParameterValue::TrustedConfirmationRequired,
5040 SecurityLevel::TRUSTED_ENVIRONMENT,
5041 ),
5042 KeyParameter::new(
5043 KeyParameterValue::UnlockedDeviceRequired,
5044 SecurityLevel::TRUSTED_ENVIRONMENT,
5045 ),
5046 KeyParameter::new(
5047 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5048 SecurityLevel::SOFTWARE,
5049 ),
5050 KeyParameter::new(
5051 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5052 SecurityLevel::SOFTWARE,
5053 ),
5054 KeyParameter::new(
5055 KeyParameterValue::CreationDateTime(12345677890),
5056 SecurityLevel::SOFTWARE,
5057 ),
5058 KeyParameter::new(
5059 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5060 SecurityLevel::TRUSTED_ENVIRONMENT,
5061 ),
5062 KeyParameter::new(
5063 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5064 SecurityLevel::TRUSTED_ENVIRONMENT,
5065 ),
5066 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5067 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5068 KeyParameter::new(
5069 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5070 SecurityLevel::SOFTWARE,
5071 ),
5072 KeyParameter::new(
5073 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5074 SecurityLevel::TRUSTED_ENVIRONMENT,
5075 ),
5076 KeyParameter::new(
5077 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5078 SecurityLevel::TRUSTED_ENVIRONMENT,
5079 ),
5080 KeyParameter::new(
5081 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5082 SecurityLevel::TRUSTED_ENVIRONMENT,
5083 ),
5084 KeyParameter::new(
5085 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5086 SecurityLevel::TRUSTED_ENVIRONMENT,
5087 ),
5088 KeyParameter::new(
5089 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5090 SecurityLevel::TRUSTED_ENVIRONMENT,
5091 ),
5092 KeyParameter::new(
5093 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5094 SecurityLevel::TRUSTED_ENVIRONMENT,
5095 ),
5096 KeyParameter::new(
5097 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5098 SecurityLevel::TRUSTED_ENVIRONMENT,
5099 ),
5100 KeyParameter::new(
5101 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5102 SecurityLevel::TRUSTED_ENVIRONMENT,
5103 ),
5104 KeyParameter::new(
5105 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5106 SecurityLevel::TRUSTED_ENVIRONMENT,
5107 ),
5108 KeyParameter::new(
5109 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5110 SecurityLevel::TRUSTED_ENVIRONMENT,
5111 ),
5112 KeyParameter::new(
5113 KeyParameterValue::VendorPatchLevel(3),
5114 SecurityLevel::TRUSTED_ENVIRONMENT,
5115 ),
5116 KeyParameter::new(
5117 KeyParameterValue::BootPatchLevel(4),
5118 SecurityLevel::TRUSTED_ENVIRONMENT,
5119 ),
5120 KeyParameter::new(
5121 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5122 SecurityLevel::TRUSTED_ENVIRONMENT,
5123 ),
5124 KeyParameter::new(
5125 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5126 SecurityLevel::TRUSTED_ENVIRONMENT,
5127 ),
5128 KeyParameter::new(
5129 KeyParameterValue::MacLength(256),
5130 SecurityLevel::TRUSTED_ENVIRONMENT,
5131 ),
5132 KeyParameter::new(
5133 KeyParameterValue::ResetSinceIdRotation,
5134 SecurityLevel::TRUSTED_ENVIRONMENT,
5135 ),
5136 KeyParameter::new(
5137 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5138 SecurityLevel::TRUSTED_ENVIRONMENT,
5139 ),
Qi Wub9433b52020-12-01 14:52:46 +08005140 ];
5141 if let Some(value) = max_usage_count {
5142 params.push(KeyParameter::new(
5143 KeyParameterValue::UsageCountLimit(value),
5144 SecurityLevel::SOFTWARE,
5145 ));
5146 }
5147 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005148 }
5149
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005150 fn make_test_key_entry(
5151 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005152 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005153 namespace: i64,
5154 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005155 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005156 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005157 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005158 let mut blob_metadata = BlobMetaData::new();
5159 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5160 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5161 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5162 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5163 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5164
5165 db.set_blob(
5166 &key_id,
5167 SubComponentType::KEY_BLOB,
5168 Some(TEST_KEY_BLOB),
5169 Some(&blob_metadata),
5170 )?;
5171 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5172 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005173
5174 let params = make_test_params(max_usage_count);
5175 db.insert_keyparameter(&key_id, &params)?;
5176
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005177 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005178 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005179 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005180 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005181 Ok(key_id)
5182 }
5183
Qi Wub9433b52020-12-01 14:52:46 +08005184 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5185 let params = make_test_params(max_usage_count);
5186
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005187 let mut blob_metadata = BlobMetaData::new();
5188 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5189 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5190 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5191 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5192 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5193
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005194 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005195 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005196
5197 KeyEntry {
5198 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005199 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005200 cert: Some(TEST_CERT_BLOB.to_vec()),
5201 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005202 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005203 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005204 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005205 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005206 }
5207 }
5208
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005209 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005210 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005211 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005212 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005213 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005214 NO_PARAMS,
5215 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005216 Ok((
5217 row.get(0)?,
5218 row.get(1)?,
5219 row.get(2)?,
5220 row.get(3)?,
5221 row.get(4)?,
5222 row.get(5)?,
5223 row.get(6)?,
5224 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005225 },
5226 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005227
5228 println!("Key entry table rows:");
5229 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005230 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005231 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005232 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5233 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005234 );
5235 }
5236 Ok(())
5237 }
5238
5239 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005240 let mut stmt = db
5241 .conn
5242 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005243 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5244 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5245 })?;
5246
5247 println!("Grant table rows:");
5248 for r in rows {
5249 let (id, gt, ki, av) = r.unwrap();
5250 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5251 }
5252 Ok(())
5253 }
5254
Joel Galenson0891bc12020-07-20 10:37:03 -07005255 // Use a custom random number generator that repeats each number once.
5256 // This allows us to test repeated elements.
5257
5258 thread_local! {
5259 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5260 }
5261
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005262 fn reset_random() {
5263 RANDOM_COUNTER.with(|counter| {
5264 *counter.borrow_mut() = 0;
5265 })
5266 }
5267
Joel Galenson0891bc12020-07-20 10:37:03 -07005268 pub fn random() -> i64 {
5269 RANDOM_COUNTER.with(|counter| {
5270 let result = *counter.borrow() / 2;
5271 *counter.borrow_mut() += 1;
5272 result
5273 })
5274 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005275
5276 #[test]
5277 fn test_last_off_body() -> Result<()> {
5278 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005279 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005280 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5281 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5282 tx.commit()?;
5283 let one_second = Duration::from_secs(1);
5284 thread::sleep(one_second);
5285 db.update_last_off_body(MonotonicRawTime::now())?;
5286 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5287 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5288 tx2.commit()?;
5289 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5290 Ok(())
5291 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005292
5293 #[test]
5294 fn test_unbind_keys_for_user() -> Result<()> {
5295 let mut db = new_test_db()?;
5296 db.unbind_keys_for_user(1, false)?;
5297
5298 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5299 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5300 db.unbind_keys_for_user(2, false)?;
5301
5302 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5303 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5304
5305 db.unbind_keys_for_user(1, true)?;
5306 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5307
5308 Ok(())
5309 }
5310
5311 #[test]
5312 fn test_store_super_key() -> Result<()> {
5313 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005314 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005315 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005316 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005317 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005318 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005319
5320 let (encrypted_super_key, metadata) =
5321 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005322 db.store_super_key(
5323 1,
5324 &USER_SUPER_KEY,
5325 &encrypted_super_key,
5326 &metadata,
5327 &KeyMetaData::new(),
5328 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005329
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005330 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005331 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005332
Paul Crowley7a658392021-03-18 17:08:20 -07005333 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005334 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5335 USER_SUPER_KEY.algorithm,
5336 key_entry,
5337 &pw,
5338 None,
5339 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005340
Paul Crowley7a658392021-03-18 17:08:20 -07005341 let decrypted_secret_bytes =
5342 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5343 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005344 Ok(())
5345 }
Seth Moore78c091f2021-04-09 21:38:30 +00005346
5347 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5348 vec![
5349 StatsdStorageType::KeyEntry,
5350 StatsdStorageType::KeyEntryIdIndex,
5351 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5352 StatsdStorageType::BlobEntry,
5353 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5354 StatsdStorageType::KeyParameter,
5355 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5356 StatsdStorageType::KeyMetadata,
5357 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5358 StatsdStorageType::Grant,
5359 StatsdStorageType::AuthToken,
5360 StatsdStorageType::BlobMetadata,
5361 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5362 ]
5363 }
5364
5365 /// Perform a simple check to ensure that we can query all the storage types
5366 /// that are supported by the DB. Check for reasonable values.
5367 #[test]
5368 fn test_query_all_valid_table_sizes() -> Result<()> {
5369 const PAGE_SIZE: i64 = 4096;
5370
5371 let mut db = new_test_db()?;
5372
5373 for t in get_valid_statsd_storage_types() {
5374 let stat = db.get_storage_stat(t)?;
5375 assert!(stat.size >= PAGE_SIZE);
5376 assert!(stat.size >= stat.unused_size);
5377 }
5378
5379 Ok(())
5380 }
5381
5382 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5383 get_valid_statsd_storage_types()
5384 .into_iter()
5385 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5386 .collect()
5387 }
5388
5389 fn assert_storage_increased(
5390 db: &mut KeystoreDB,
5391 increased_storage_types: Vec<StatsdStorageType>,
5392 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5393 ) {
5394 for storage in increased_storage_types {
5395 // Verify the expected storage increased.
5396 let new = db.get_storage_stat(storage).unwrap();
5397 let storage = storage as i32;
5398 let old = &baseline[&storage];
5399 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5400 assert!(
5401 new.unused_size <= old.unused_size,
5402 "{}: {} <= {}",
5403 storage,
5404 new.unused_size,
5405 old.unused_size
5406 );
5407
5408 // Update the baseline with the new value so that it succeeds in the
5409 // later comparison.
5410 baseline.insert(storage, new);
5411 }
5412
5413 // Get an updated map of the storage and verify there were no unexpected changes.
5414 let updated_stats = get_storage_stats_map(db);
5415 assert_eq!(updated_stats.len(), baseline.len());
5416
5417 for &k in baseline.keys() {
5418 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5419 let mut s = String::new();
5420 for &k in map.keys() {
5421 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5422 .expect("string concat failed");
5423 }
5424 s
5425 };
5426
5427 assert!(
5428 updated_stats[&k].size == baseline[&k].size
5429 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5430 "updated_stats:\n{}\nbaseline:\n{}",
5431 stringify(&updated_stats),
5432 stringify(&baseline)
5433 );
5434 }
5435 }
5436
5437 #[test]
5438 fn test_verify_key_table_size_reporting() -> Result<()> {
5439 let mut db = new_test_db()?;
5440 let mut working_stats = get_storage_stats_map(&mut db);
5441
5442 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5443 assert_storage_increased(
5444 &mut db,
5445 vec![
5446 StatsdStorageType::KeyEntry,
5447 StatsdStorageType::KeyEntryIdIndex,
5448 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5449 ],
5450 &mut working_stats,
5451 );
5452
5453 let mut blob_metadata = BlobMetaData::new();
5454 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5455 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5456 assert_storage_increased(
5457 &mut db,
5458 vec![
5459 StatsdStorageType::BlobEntry,
5460 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5461 StatsdStorageType::BlobMetadata,
5462 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5463 ],
5464 &mut working_stats,
5465 );
5466
5467 let params = make_test_params(None);
5468 db.insert_keyparameter(&key_id, &params)?;
5469 assert_storage_increased(
5470 &mut db,
5471 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5472 &mut working_stats,
5473 );
5474
5475 let mut metadata = KeyMetaData::new();
5476 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5477 db.insert_key_metadata(&key_id, &metadata)?;
5478 assert_storage_increased(
5479 &mut db,
5480 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5481 &mut working_stats,
5482 );
5483
5484 let mut sum = 0;
5485 for stat in working_stats.values() {
5486 sum += stat.size;
5487 }
5488 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5489 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5490
5491 Ok(())
5492 }
5493
5494 #[test]
5495 fn test_verify_auth_table_size_reporting() -> Result<()> {
5496 let mut db = new_test_db()?;
5497 let mut working_stats = get_storage_stats_map(&mut db);
5498 db.insert_auth_token(&HardwareAuthToken {
5499 challenge: 123,
5500 userId: 456,
5501 authenticatorId: 789,
5502 authenticatorType: kmhw_authenticator_type::ANY,
5503 timestamp: Timestamp { milliSeconds: 10 },
5504 mac: b"mac".to_vec(),
5505 })?;
5506 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5507 Ok(())
5508 }
5509
5510 #[test]
5511 fn test_verify_grant_table_size_reporting() -> Result<()> {
5512 const OWNER: i64 = 1;
5513 let mut db = new_test_db()?;
5514 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5515
5516 let mut working_stats = get_storage_stats_map(&mut db);
5517 db.grant(
5518 &KeyDescriptor {
5519 domain: Domain::APP,
5520 nspace: 0,
5521 alias: Some(TEST_ALIAS.to_string()),
5522 blob: None,
5523 },
5524 OWNER as u32,
5525 123,
5526 key_perm_set![KeyPerm::use_()],
5527 |_, _| Ok(()),
5528 )?;
5529
5530 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5531
5532 Ok(())
5533 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005534}