blob: 32e2c986e232f83bf142f81905713aa2a56742d1 [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;
Hasini Gunasingheda895552021-01-27 19:34:37 +000049use crate::utils::{get_current_time_in_seconds, 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 Danisevskisb00ebd02021-02-02 21:52:24 -0800854 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800855 let mut persistent_path = db_root.to_path_buf();
Seth Moore78c091f2021-04-09 21:38:30 +0000856 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700857
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800858 // Now convert them to strings prefixed with "file:"
859 let mut persistent_path_str = "file:".to_owned();
860 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800861
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800862 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800863
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
865 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
866
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800867 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800868 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800869 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 })?;
871 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700872 }
873
Janis Danisevskis66784c42021-01-27 08:40:25 -0800874 fn init_tables(tx: &Transaction) -> Result<()> {
875 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700876 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700877 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800878 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700879 domain INTEGER,
880 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800881 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800882 state INTEGER,
883 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700884 NO_PARAMS,
885 )
886 .context("Failed to initialize \"keyentry\" table.")?;
887
Janis Danisevskis66784c42021-01-27 08:40:25 -0800888 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800889 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
890 ON keyentry(id);",
891 NO_PARAMS,
892 )
893 .context("Failed to create index keyentry_id_index.")?;
894
895 tx.execute(
896 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
897 ON keyentry(domain, namespace, alias);",
898 NO_PARAMS,
899 )
900 .context("Failed to create index keyentry_domain_namespace_index.")?;
901
902 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700903 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
904 id INTEGER PRIMARY KEY,
905 subcomponent_type INTEGER,
906 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800907 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700908 NO_PARAMS,
909 )
910 .context("Failed to initialize \"blobentry\" table.")?;
911
Janis Danisevskis66784c42021-01-27 08:40:25 -0800912 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800913 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
914 ON blobentry(keyentryid);",
915 NO_PARAMS,
916 )
917 .context("Failed to create index blobentry_keyentryid_index.")?;
918
919 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800920 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
921 id INTEGER PRIMARY KEY,
922 blobentryid INTEGER,
923 tag INTEGER,
924 data ANY,
925 UNIQUE (blobentryid, tag));",
926 NO_PARAMS,
927 )
928 .context("Failed to initialize \"blobmetadata\" table.")?;
929
930 tx.execute(
931 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
932 ON blobmetadata(blobentryid);",
933 NO_PARAMS,
934 )
935 .context("Failed to create index blobmetadata_blobentryid_index.")?;
936
937 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700938 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000939 keyentryid INTEGER,
940 tag INTEGER,
941 data ANY,
942 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700943 NO_PARAMS,
944 )
945 .context("Failed to initialize \"keyparameter\" table.")?;
946
Janis Danisevskis66784c42021-01-27 08:40:25 -0800947 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800948 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
949 ON keyparameter(keyentryid);",
950 NO_PARAMS,
951 )
952 .context("Failed to create index keyparameter_keyentryid_index.")?;
953
954 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800955 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
956 keyentryid INTEGER,
957 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000958 data ANY,
959 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800960 NO_PARAMS,
961 )
962 .context("Failed to initialize \"keymetadata\" table.")?;
963
Janis Danisevskis66784c42021-01-27 08:40:25 -0800964 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800965 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
966 ON keymetadata(keyentryid);",
967 NO_PARAMS,
968 )
969 .context("Failed to create index keymetadata_keyentryid_index.")?;
970
971 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800972 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700973 id INTEGER UNIQUE,
974 grantee INTEGER,
975 keyentryid INTEGER,
976 access_vector INTEGER);",
977 NO_PARAMS,
978 )
979 .context("Failed to initialize \"grant\" table.")?;
980
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000981 //TODO: only drop the following two perboot tables if this is the first start up
982 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800983 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000984 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800985 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000986 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
987 id INTEGER PRIMARY KEY,
988 challenge INTEGER,
989 user_id INTEGER,
990 auth_id INTEGER,
991 authenticator_type INTEGER,
992 timestamp INTEGER,
993 mac BLOB,
994 time_received INTEGER,
995 UNIQUE(user_id, auth_id, authenticator_type));",
996 NO_PARAMS,
997 )
998 .context("Failed to initialize \"authtoken\" table.")?;
999
Janis Danisevskis66784c42021-01-27 08:40:25 -08001000 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001001 // .context("Failed to drop perboot.metadata table")?;
1002 // metadata table stores certain miscellaneous information required for keystore functioning
1003 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001004 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001005 "CREATE TABLE IF NOT EXISTS perboot.metadata (
1006 key TEXT,
1007 value BLOB,
1008 UNIQUE(key));",
1009 NO_PARAMS,
1010 )
1011 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -07001012 Ok(())
1013 }
1014
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001015 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
1016 let conn =
1017 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1018
Janis Danisevskis66784c42021-01-27 08:40:25 -08001019 loop {
1020 if let Err(e) = conn
1021 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1022 .context("Failed to attach database persistent.")
1023 {
1024 if Self::is_locked_error(&e) {
1025 std::thread::sleep(std::time::Duration::from_micros(500));
1026 continue;
1027 } else {
1028 return Err(e);
1029 }
1030 }
1031 break;
1032 }
1033 loop {
1034 if let Err(e) = conn
1035 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1036 .context("Failed to attach database perboot.")
1037 {
1038 if Self::is_locked_error(&e) {
1039 std::thread::sleep(std::time::Duration::from_micros(500));
1040 continue;
1041 } else {
1042 return Err(e);
1043 }
1044 }
1045 break;
1046 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047
1048 Ok(conn)
1049 }
1050
Seth Moore78c091f2021-04-09 21:38:30 +00001051 fn do_table_size_query(
1052 &mut self,
1053 storage_type: StatsdStorageType,
1054 query: &str,
1055 params: &[&str],
1056 ) -> Result<Keystore2StorageStats> {
1057 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1058 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1059 .with_context(|| {
1060 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1061 })
1062 .no_gc()
1063 })?;
1064 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1065 }
1066
1067 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1068 self.do_table_size_query(
1069 StatsdStorageType::Database,
1070 "SELECT page_count * page_size, freelist_count * page_size
1071 FROM pragma_page_count('persistent'),
1072 pragma_page_size('persistent'),
1073 persistent.pragma_freelist_count();",
1074 &[],
1075 )
1076 }
1077
1078 fn get_table_size(
1079 &mut self,
1080 storage_type: StatsdStorageType,
1081 schema: &str,
1082 table: &str,
1083 ) -> Result<Keystore2StorageStats> {
1084 self.do_table_size_query(
1085 storage_type,
1086 "SELECT pgsize,unused FROM dbstat(?1)
1087 WHERE name=?2 AND aggregate=TRUE;",
1088 &[schema, table],
1089 )
1090 }
1091
1092 /// Fetches a storage statisitics atom for a given storage type. For storage
1093 /// types that map to a table, information about the table's storage is
1094 /// returned. Requests for storage types that are not DB tables return None.
1095 pub fn get_storage_stat(
1096 &mut self,
1097 storage_type: StatsdStorageType,
1098 ) -> Result<Keystore2StorageStats> {
1099 match storage_type {
1100 StatsdStorageType::Database => self.get_total_size(),
1101 StatsdStorageType::KeyEntry => {
1102 self.get_table_size(storage_type, "persistent", "keyentry")
1103 }
1104 StatsdStorageType::KeyEntryIdIndex => {
1105 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1106 }
1107 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1108 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1109 }
1110 StatsdStorageType::BlobEntry => {
1111 self.get_table_size(storage_type, "persistent", "blobentry")
1112 }
1113 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1114 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1115 }
1116 StatsdStorageType::KeyParameter => {
1117 self.get_table_size(storage_type, "persistent", "keyparameter")
1118 }
1119 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1120 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1121 }
1122 StatsdStorageType::KeyMetadata => {
1123 self.get_table_size(storage_type, "persistent", "keymetadata")
1124 }
1125 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1126 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1127 }
1128 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1129 StatsdStorageType::AuthToken => {
1130 self.get_table_size(storage_type, "perboot", "authtoken")
1131 }
1132 StatsdStorageType::BlobMetadata => {
1133 self.get_table_size(storage_type, "persistent", "blobmetadata")
1134 }
1135 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1136 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1137 }
1138 _ => Err(anyhow::Error::msg(format!(
1139 "Unsupported storage type: {}",
1140 storage_type as i32
1141 ))),
1142 }
1143 }
1144
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001145 /// This function is intended to be used by the garbage collector.
1146 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1147 /// key blob that might need special handling by the garbage collector.
1148 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1149 /// need special handling and returns None.
1150 pub fn handle_next_superseded_blob(
1151 &mut self,
1152 blob_id_to_delete: Option<i64>,
1153 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001154 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001155 // Delete the given blob if one was given.
1156 if let Some(blob_id_to_delete) = blob_id_to_delete {
1157 tx.execute(
1158 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1159 params![blob_id_to_delete],
1160 )
1161 .context("Trying to delete blob metadata.")?;
1162 tx.execute(
1163 "DELETE FROM persistent.blobentry WHERE id = ?;",
1164 params![blob_id_to_delete],
1165 )
1166 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001167 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001168
1169 // Find another superseded keyblob load its metadata and return it.
1170 if let Some((blob_id, blob)) = tx
1171 .query_row(
1172 "SELECT id, blob FROM persistent.blobentry
1173 WHERE subcomponent_type = ?
1174 AND (
1175 id NOT IN (
1176 SELECT MAX(id) FROM persistent.blobentry
1177 WHERE subcomponent_type = ?
1178 GROUP BY keyentryid, subcomponent_type
1179 )
1180 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1181 );",
1182 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1183 |row| Ok((row.get(0)?, row.get(1)?)),
1184 )
1185 .optional()
1186 .context("Trying to query superseded blob.")?
1187 {
1188 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1189 .context("Trying to load blob metadata.")?;
1190 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1191 }
1192
1193 // We did not find any superseded key blob, so let's remove other superseded blob in
1194 // one transaction.
1195 tx.execute(
1196 "DELETE FROM persistent.blobentry
1197 WHERE NOT subcomponent_type = ?
1198 AND (
1199 id NOT IN (
1200 SELECT MAX(id) FROM persistent.blobentry
1201 WHERE NOT subcomponent_type = ?
1202 GROUP BY keyentryid, subcomponent_type
1203 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1204 );",
1205 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1206 )
1207 .context("Trying to purge superseded blobs.")?;
1208
1209 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001210 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001211 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001212 }
1213
1214 /// This maintenance function should be called only once before the database is used for the
1215 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1216 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1217 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1218 /// Keystore crashed at some point during key generation. Callers may want to log such
1219 /// occurrences.
1220 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1221 /// it to `KeyLifeCycle::Live` may have grants.
1222 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001223 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1224 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001225 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1226 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1227 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001228 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001229 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001230 })
1231 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001232 }
1233
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001234 /// Checks if a key exists with given key type and key descriptor properties.
1235 pub fn key_exists(
1236 &mut self,
1237 domain: Domain,
1238 nspace: i64,
1239 alias: &str,
1240 key_type: KeyType,
1241 ) -> Result<bool> {
1242 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1243 let key_descriptor =
1244 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1245 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1246 match result {
1247 Ok(_) => Ok(true),
1248 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1249 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1250 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1251 },
1252 }
1253 .no_gc()
1254 })
1255 .context("In key_exists.")
1256 }
1257
Hasini Gunasingheda895552021-01-27 19:34:37 +00001258 /// Stores a super key in the database.
1259 pub fn store_super_key(
1260 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001261 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001262 key_type: &SuperKeyType,
1263 blob: &[u8],
1264 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001265 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001266 ) -> Result<KeyEntry> {
1267 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1268 let key_id = Self::insert_with_retry(|id| {
1269 tx.execute(
1270 "INSERT into persistent.keyentry
1271 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001272 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001273 params![
1274 id,
1275 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001276 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001277 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001278 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001279 KeyLifeCycle::Live,
1280 &KEYSTORE_UUID,
1281 ],
1282 )
1283 })
1284 .context("Failed to insert into keyentry table.")?;
1285
Paul Crowley8d5b2532021-03-19 10:53:07 -07001286 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1287
Hasini Gunasingheda895552021-01-27 19:34:37 +00001288 Self::set_blob_internal(
1289 &tx,
1290 key_id,
1291 SubComponentType::KEY_BLOB,
1292 Some(blob),
1293 Some(blob_metadata),
1294 )
1295 .context("Failed to store key blob.")?;
1296
1297 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1298 .context("Trying to load key components.")
1299 .no_gc()
1300 })
1301 .context("In store_super_key.")
1302 }
1303
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001304 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001305 pub fn load_super_key(
1306 &mut self,
1307 key_type: &SuperKeyType,
1308 user_id: u32,
1309 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001310 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1311 let key_descriptor = KeyDescriptor {
1312 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001313 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001314 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001315 blob: None,
1316 };
1317 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1318 match id {
1319 Ok(id) => {
1320 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1321 .context("In load_super_key. Failed to load key entry.")?;
1322 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1323 }
1324 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1325 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1326 _ => Err(error).context("In load_super_key."),
1327 },
1328 }
1329 .no_gc()
1330 })
1331 .context("In load_super_key.")
1332 }
1333
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001334 /// Atomically loads a key entry and associated metadata or creates it using the
1335 /// callback create_new_key callback. The callback is called during a database
1336 /// transaction. This means that implementers should be mindful about using
1337 /// blocking operations such as IPC or grabbing mutexes.
1338 pub fn get_or_create_key_with<F>(
1339 &mut self,
1340 domain: Domain,
1341 namespace: i64,
1342 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001343 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001344 create_new_key: F,
1345 ) -> Result<(KeyIdGuard, KeyEntry)>
1346 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001347 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001348 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001349 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1350 let id = {
1351 let mut stmt = tx
1352 .prepare(
1353 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001354 WHERE
1355 key_type = ?
1356 AND domain = ?
1357 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001358 AND alias = ?
1359 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001360 )
1361 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1362 let mut rows = stmt
1363 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1364 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001365
Janis Danisevskis66784c42021-01-27 08:40:25 -08001366 db_utils::with_rows_extract_one(&mut rows, |row| {
1367 Ok(match row {
1368 Some(r) => r.get(0).context("Failed to unpack id.")?,
1369 None => None,
1370 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001371 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001372 .context("In get_or_create_key_with.")?
1373 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001374
Janis Danisevskis66784c42021-01-27 08:40:25 -08001375 let (id, entry) = match id {
1376 Some(id) => (
1377 id,
1378 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1379 .context("In get_or_create_key_with.")?,
1380 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001381
Janis Danisevskis66784c42021-01-27 08:40:25 -08001382 None => {
1383 let id = Self::insert_with_retry(|id| {
1384 tx.execute(
1385 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001386 (id, key_type, domain, namespace, alias, state, km_uuid)
1387 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001388 params![
1389 id,
1390 KeyType::Super,
1391 domain.0,
1392 namespace,
1393 alias,
1394 KeyLifeCycle::Live,
1395 km_uuid,
1396 ],
1397 )
1398 })
1399 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001400
Janis Danisevskis66784c42021-01-27 08:40:25 -08001401 let (blob, metadata) =
1402 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001403 Self::set_blob_internal(
1404 &tx,
1405 id,
1406 SubComponentType::KEY_BLOB,
1407 Some(&blob),
1408 Some(&metadata),
1409 )
Paul Crowley7a658392021-03-18 17:08:20 -07001410 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001411 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001412 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 KeyEntry {
1414 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001415 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 pure_cert: false,
1417 ..Default::default()
1418 },
1419 )
1420 }
1421 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001422 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001423 })
1424 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001425 }
1426
Janis Danisevskis66784c42021-01-27 08:40:25 -08001427 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1428 /// waiting for the database file to become available. This makes it
1429 /// impossible to successfully recover from a locked database when the
1430 /// transaction holding the device busy is in the same process on a
1431 /// different connection. As a result the busy handler has to time out and
1432 /// fail in order to make progress.
1433 ///
1434 /// Instead, we set the busy handler to None (return immediately). And catch
1435 /// Busy and Locked errors (the latter occur on in memory databases with
1436 /// shared cache, e.g., the per-boot database.) and restart the transaction
1437 /// after a grace period of half a millisecond.
1438 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001439 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001440 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1441 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001442 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1443 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001444 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001445 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001446 loop {
1447 match self
1448 .conn
1449 .transaction_with_behavior(behavior)
1450 .context("In with_transaction.")
1451 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1452 .and_then(|(result, tx)| {
1453 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1454 Ok(result)
1455 }) {
1456 Ok(result) => break Ok(result),
1457 Err(e) => {
1458 if Self::is_locked_error(&e) {
1459 std::thread::sleep(std::time::Duration::from_micros(500));
1460 continue;
1461 } else {
1462 return Err(e).context("In with_transaction.");
1463 }
1464 }
1465 }
1466 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001467 .map(|(need_gc, result)| {
1468 if need_gc {
1469 if let Some(ref gc) = self.gc {
1470 gc.notify_gc();
1471 }
1472 }
1473 result
1474 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001475 }
1476
1477 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001478 matches!(
1479 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1480 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1481 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1482 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001483 }
1484
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001485 /// Creates a new key entry and allocates a new randomized id for the new key.
1486 /// The key id gets associated with a domain and namespace but not with an alias.
1487 /// To complete key generation `rebind_alias` should be called after all of the
1488 /// key artifacts, i.e., blobs and parameters have been associated with the new
1489 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1490 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001491 pub fn create_key_entry(
1492 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001493 domain: &Domain,
1494 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001495 km_uuid: &Uuid,
1496 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001497 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001498 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001499 })
1500 .context("In create_key_entry.")
1501 }
1502
1503 fn create_key_entry_internal(
1504 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001505 domain: &Domain,
1506 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001507 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001508 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001509 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001510 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001511 _ => {
1512 return Err(KsError::sys())
1513 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1514 }
1515 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001516 Ok(KEY_ID_LOCK.get(
1517 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001518 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001519 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001520 (id, key_type, domain, namespace, alias, state, km_uuid)
1521 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001522 params![
1523 id,
1524 KeyType::Client,
1525 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001526 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001527 KeyLifeCycle::Existing,
1528 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001529 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001530 )
1531 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001532 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001533 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001534 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001535
Max Bires2b2e6562020-09-22 11:22:36 -07001536 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1537 /// The key id gets associated with a domain and namespace later but not with an alias. The
1538 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1539 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1540 /// a key.
1541 pub fn create_attestation_key_entry(
1542 &mut self,
1543 maced_public_key: &[u8],
1544 raw_public_key: &[u8],
1545 private_key: &[u8],
1546 km_uuid: &Uuid,
1547 ) -> Result<()> {
1548 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1549 let key_id = KEY_ID_LOCK.get(
1550 Self::insert_with_retry(|id| {
1551 tx.execute(
1552 "INSERT into persistent.keyentry
1553 (id, key_type, domain, namespace, alias, state, km_uuid)
1554 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1555 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1556 )
1557 })
1558 .context("In create_key_entry")?,
1559 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001560 Self::set_blob_internal(
1561 &tx,
1562 key_id.0,
1563 SubComponentType::KEY_BLOB,
1564 Some(private_key),
1565 None,
1566 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001567 let mut metadata = KeyMetaData::new();
1568 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1569 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1570 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001571 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001572 })
1573 .context("In create_attestation_key_entry")
1574 }
1575
Janis Danisevskis377d1002021-01-27 19:07:48 -08001576 /// Set a new blob and associates it with the given key id. Each blob
1577 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001578 /// Each key can have one of each sub component type associated. If more
1579 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001580 /// will get garbage collected.
1581 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1582 /// removed by setting blob to None.
1583 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001584 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001585 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001586 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001587 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001588 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001589 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001590 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001591 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001592 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001593 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001594 }
1595
Janis Danisevskiseed69842021-02-18 20:04:10 -08001596 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1597 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1598 /// We use this to insert key blobs into the database which can then be garbage collected
1599 /// lazily by the key garbage collector.
1600 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
1601 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1602 Self::set_blob_internal(
1603 &tx,
1604 Self::UNASSIGNED_KEY_ID,
1605 SubComponentType::KEY_BLOB,
1606 Some(blob),
1607 Some(blob_metadata),
1608 )
1609 .need_gc()
1610 })
1611 .context("In set_deleted_blob.")
1612 }
1613
Janis Danisevskis377d1002021-01-27 19:07:48 -08001614 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001615 tx: &Transaction,
1616 key_id: i64,
1617 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001618 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001619 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001620 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001621 match (blob, sc_type) {
1622 (Some(blob), _) => {
1623 tx.execute(
1624 "INSERT INTO persistent.blobentry
1625 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1626 params![sc_type, key_id, blob],
1627 )
1628 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001629 if let Some(blob_metadata) = blob_metadata {
1630 let blob_id = tx
1631 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1632 row.get(0)
1633 })
1634 .context("In set_blob_internal: Failed to get new blob id.")?;
1635 blob_metadata
1636 .store_in_db(blob_id, tx)
1637 .context("In set_blob_internal: Trying to store blob metadata.")?;
1638 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001639 }
1640 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1641 tx.execute(
1642 "DELETE FROM persistent.blobentry
1643 WHERE subcomponent_type = ? AND keyentryid = ?;",
1644 params![sc_type, key_id],
1645 )
1646 .context("In set_blob_internal: Failed to delete blob.")?;
1647 }
1648 (None, _) => {
1649 return Err(KsError::sys())
1650 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1651 }
1652 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001653 Ok(())
1654 }
1655
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001656 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1657 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001658 #[cfg(test)]
1659 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001660 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001661 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001662 })
1663 .context("In insert_keyparameter.")
1664 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001665
Janis Danisevskis66784c42021-01-27 08:40:25 -08001666 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001667 tx: &Transaction,
1668 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001669 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001670 ) -> Result<()> {
1671 let mut stmt = tx
1672 .prepare(
1673 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1674 VALUES (?, ?, ?, ?);",
1675 )
1676 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1677
Janis Danisevskis66784c42021-01-27 08:40:25 -08001678 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001679 stmt.insert(params![
1680 key_id.0,
1681 p.get_tag().0,
1682 p.key_parameter_value(),
1683 p.security_level().0
1684 ])
1685 .with_context(|| {
1686 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1687 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001688 }
1689 Ok(())
1690 }
1691
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001692 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001693 #[cfg(test)]
1694 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001695 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001696 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001697 })
1698 .context("In insert_key_metadata.")
1699 }
1700
Max Bires2b2e6562020-09-22 11:22:36 -07001701 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1702 /// on the public key.
1703 pub fn store_signed_attestation_certificate_chain(
1704 &mut self,
1705 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001706 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001707 cert_chain: &[u8],
1708 expiration_date: i64,
1709 km_uuid: &Uuid,
1710 ) -> Result<()> {
1711 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1712 let mut stmt = tx
1713 .prepare(
1714 "SELECT keyentryid
1715 FROM persistent.keymetadata
1716 WHERE tag = ? AND data = ? AND keyentryid IN
1717 (SELECT id
1718 FROM persistent.keyentry
1719 WHERE
1720 alias IS NULL AND
1721 domain IS NULL AND
1722 namespace IS NULL AND
1723 key_type = ? AND
1724 km_uuid = ?);",
1725 )
1726 .context("Failed to store attestation certificate chain.")?;
1727 let mut rows = stmt
1728 .query(params![
1729 KeyMetaData::AttestationRawPubKey,
1730 raw_public_key,
1731 KeyType::Attestation,
1732 km_uuid
1733 ])
1734 .context("Failed to fetch keyid")?;
1735 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1736 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1737 .get(0)
1738 .context("Failed to unpack id.")
1739 })
1740 .context("Failed to get key_id.")?;
1741 let num_updated = tx
1742 .execute(
1743 "UPDATE persistent.keyentry
1744 SET alias = ?
1745 WHERE id = ?;",
1746 params!["signed", key_id],
1747 )
1748 .context("Failed to update alias.")?;
1749 if num_updated != 1 {
1750 return Err(KsError::sys()).context("Alias not updated for the key.");
1751 }
1752 let mut metadata = KeyMetaData::new();
1753 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1754 expiration_date,
1755 )));
1756 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001757 Self::set_blob_internal(
1758 &tx,
1759 key_id,
1760 SubComponentType::CERT_CHAIN,
1761 Some(cert_chain),
1762 None,
1763 )
1764 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001765 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1766 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001767 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001768 })
1769 .context("In store_signed_attestation_certificate_chain: ")
1770 }
1771
1772 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1773 /// currently have a key assigned to it.
1774 pub fn assign_attestation_key(
1775 &mut self,
1776 domain: Domain,
1777 namespace: i64,
1778 km_uuid: &Uuid,
1779 ) -> Result<()> {
1780 match domain {
1781 Domain::APP | Domain::SELINUX => {}
1782 _ => {
1783 return Err(KsError::sys()).context(format!(
1784 concat!(
1785 "In assign_attestation_key: Domain {:?} ",
1786 "must be either App or SELinux.",
1787 ),
1788 domain
1789 ));
1790 }
1791 }
1792 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1793 let result = tx
1794 .execute(
1795 "UPDATE persistent.keyentry
1796 SET domain=?1, namespace=?2
1797 WHERE
1798 id =
1799 (SELECT MIN(id)
1800 FROM persistent.keyentry
1801 WHERE ALIAS IS NOT NULL
1802 AND domain IS NULL
1803 AND key_type IS ?3
1804 AND state IS ?4
1805 AND km_uuid IS ?5)
1806 AND
1807 (SELECT COUNT(*)
1808 FROM persistent.keyentry
1809 WHERE domain=?1
1810 AND namespace=?2
1811 AND key_type IS ?3
1812 AND state IS ?4
1813 AND km_uuid IS ?5) = 0;",
1814 params![
1815 domain.0 as u32,
1816 namespace,
1817 KeyType::Attestation,
1818 KeyLifeCycle::Live,
1819 km_uuid,
1820 ],
1821 )
1822 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001823 if result == 0 {
1824 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1825 } else if result > 1 {
1826 return Err(KsError::sys())
1827 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001828 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001829 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001830 })
1831 .context("In assign_attestation_key: ")
1832 }
1833
1834 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1835 /// provisioning server, or the maximum number available if there are not num_keys number of
1836 /// entries in the table.
1837 pub fn fetch_unsigned_attestation_keys(
1838 &mut self,
1839 num_keys: i32,
1840 km_uuid: &Uuid,
1841 ) -> Result<Vec<Vec<u8>>> {
1842 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1843 let mut stmt = tx
1844 .prepare(
1845 "SELECT data
1846 FROM persistent.keymetadata
1847 WHERE tag = ? AND keyentryid IN
1848 (SELECT id
1849 FROM persistent.keyentry
1850 WHERE
1851 alias IS NULL AND
1852 domain IS NULL AND
1853 namespace IS NULL AND
1854 key_type = ? AND
1855 km_uuid = ?
1856 LIMIT ?);",
1857 )
1858 .context("Failed to prepare statement")?;
1859 let rows = stmt
1860 .query_map(
1861 params![
1862 KeyMetaData::AttestationMacedPublicKey,
1863 KeyType::Attestation,
1864 km_uuid,
1865 num_keys
1866 ],
1867 |row| Ok(row.get(0)?),
1868 )?
1869 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1870 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001871 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001872 })
1873 .context("In fetch_unsigned_attestation_keys")
1874 }
1875
1876 /// Removes any keys that have expired as of the current time. Returns the number of keys
1877 /// marked unreferenced that are bound to be garbage collected.
1878 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
1879 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1880 let mut stmt = tx
1881 .prepare(
1882 "SELECT keyentryid, data
1883 FROM persistent.keymetadata
1884 WHERE tag = ? AND keyentryid IN
1885 (SELECT id
1886 FROM persistent.keyentry
1887 WHERE key_type = ?);",
1888 )
1889 .context("Failed to prepare query")?;
1890 let key_ids_to_check = stmt
1891 .query_map(
1892 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1893 |row| Ok((row.get(0)?, row.get(1)?)),
1894 )?
1895 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1896 .context("Failed to get date metadata")?;
1897 let curr_time = DateTime::from_millis_epoch(
1898 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1899 );
1900 let mut num_deleted = 0;
1901 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1902 if Self::mark_unreferenced(&tx, id)? {
1903 num_deleted += 1;
1904 }
1905 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001906 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001907 })
1908 .context("In delete_expired_attestation_keys: ")
1909 }
1910
Max Bires60d7ed12021-03-05 15:59:22 -08001911 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1912 /// they are in. This is useful primarily as a testing mechanism.
1913 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
1914 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1915 let mut stmt = tx
1916 .prepare(
1917 "SELECT id FROM persistent.keyentry
1918 WHERE key_type IS ?;",
1919 )
1920 .context("Failed to prepare statement")?;
1921 let keys_to_delete = stmt
1922 .query_map(params![KeyType::Attestation], |row| Ok(row.get(0)?))?
1923 .collect::<rusqlite::Result<Vec<i64>>>()
1924 .context("Failed to execute statement")?;
1925 let num_deleted = keys_to_delete
1926 .iter()
1927 .map(|id| Self::mark_unreferenced(&tx, *id))
1928 .collect::<Result<Vec<bool>>>()
1929 .context("Failed to execute mark_unreferenced on a keyid")?
1930 .into_iter()
1931 .filter(|result| *result)
1932 .count() as i64;
1933 Ok(num_deleted).do_gc(num_deleted != 0)
1934 })
1935 .context("In delete_all_attestation_keys: ")
1936 }
1937
Max Bires2b2e6562020-09-22 11:22:36 -07001938 /// Counts the number of keys that will expire by the provided epoch date and the number of
1939 /// keys not currently assigned to a domain.
1940 pub fn get_attestation_pool_status(
1941 &mut self,
1942 date: i64,
1943 km_uuid: &Uuid,
1944 ) -> Result<AttestationPoolStatus> {
1945 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1946 let mut stmt = tx.prepare(
1947 "SELECT data
1948 FROM persistent.keymetadata
1949 WHERE tag = ? AND keyentryid IN
1950 (SELECT id
1951 FROM persistent.keyentry
1952 WHERE alias IS NOT NULL
1953 AND key_type = ?
1954 AND km_uuid = ?
1955 AND state = ?);",
1956 )?;
1957 let times = stmt
1958 .query_map(
1959 params![
1960 KeyMetaData::AttestationExpirationDate,
1961 KeyType::Attestation,
1962 km_uuid,
1963 KeyLifeCycle::Live
1964 ],
1965 |row| Ok(row.get(0)?),
1966 )?
1967 .collect::<rusqlite::Result<Vec<DateTime>>>()
1968 .context("Failed to execute metadata statement")?;
1969 let expiring =
1970 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1971 as i32;
1972 stmt = tx.prepare(
1973 "SELECT alias, domain
1974 FROM persistent.keyentry
1975 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1976 )?;
1977 let rows = stmt
1978 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1979 Ok((row.get(0)?, row.get(1)?))
1980 })?
1981 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1982 .context("Failed to execute keyentry statement")?;
1983 let mut unassigned = 0i32;
1984 let mut attested = 0i32;
1985 let total = rows.len() as i32;
1986 for (alias, domain) in rows {
1987 match (alias, domain) {
1988 (Some(_alias), None) => {
1989 attested += 1;
1990 unassigned += 1;
1991 }
1992 (Some(_alias), Some(_domain)) => {
1993 attested += 1;
1994 }
1995 _ => {}
1996 }
1997 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001998 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001999 })
2000 .context("In get_attestation_pool_status: ")
2001 }
2002
2003 /// Fetches the private key and corresponding certificate chain assigned to a
2004 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2005 /// not assigned, or one CertificateChain.
2006 pub fn retrieve_attestation_key_and_cert_chain(
2007 &mut self,
2008 domain: Domain,
2009 namespace: i64,
2010 km_uuid: &Uuid,
2011 ) -> Result<Option<CertificateChain>> {
2012 match domain {
2013 Domain::APP | Domain::SELINUX => {}
2014 _ => {
2015 return Err(KsError::sys())
2016 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2017 }
2018 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002019 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2020 let mut stmt = tx.prepare(
2021 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002022 FROM persistent.blobentry
2023 WHERE keyentryid IN
2024 (SELECT id
2025 FROM persistent.keyentry
2026 WHERE key_type = ?
2027 AND domain = ?
2028 AND namespace = ?
2029 AND state = ?
2030 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002031 )?;
2032 let rows = stmt
2033 .query_map(
2034 params![
2035 KeyType::Attestation,
2036 domain.0 as u32,
2037 namespace,
2038 KeyLifeCycle::Live,
2039 km_uuid
2040 ],
2041 |row| Ok((row.get(0)?, row.get(1)?)),
2042 )?
2043 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002044 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002045 if rows.is_empty() {
2046 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002047 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002048 return Err(KsError::sys()).context(format!(
2049 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002050 "Expected to get a single attestation",
2051 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2052 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002053 rows.len()
2054 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002055 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002056 let mut km_blob: Vec<u8> = Vec::new();
2057 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002058 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002059 for row in rows {
2060 let sub_type: SubComponentType = row.0;
2061 match sub_type {
2062 SubComponentType::KEY_BLOB => {
2063 km_blob = row.1;
2064 }
2065 SubComponentType::CERT_CHAIN => {
2066 cert_chain_blob = row.1;
2067 }
Max Biresb2e1d032021-02-08 21:35:05 -08002068 SubComponentType::CERT => {
2069 batch_cert_blob = row.1;
2070 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002071 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2072 }
2073 }
2074 Ok(Some(CertificateChain {
2075 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002076 batch_cert: batch_cert_blob,
2077 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002078 }))
2079 .no_gc()
2080 })
Max Biresb2e1d032021-02-08 21:35:05 -08002081 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002082 }
2083
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002084 /// Updates the alias column of the given key id `newid` with the given alias,
2085 /// and atomically, removes the alias, domain, and namespace from another row
2086 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002087 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2088 /// collector.
2089 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002090 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002091 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002092 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002093 domain: &Domain,
2094 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002095 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002096 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002097 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002098 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002099 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002100 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002101 domain
2102 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002103 }
2104 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002105 let updated = tx
2106 .execute(
2107 "UPDATE persistent.keyentry
2108 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002109 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002110 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2111 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002112 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002113 let result = tx
2114 .execute(
2115 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002116 SET alias = ?, state = ?
2117 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2118 params![
2119 alias,
2120 KeyLifeCycle::Live,
2121 newid.0,
2122 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002123 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002124 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002125 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002126 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002127 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002128 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002129 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002130 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002131 result
2132 ));
2133 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002134 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002135 }
2136
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002137 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2138 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2139 pub fn migrate_key_namespace(
2140 &mut self,
2141 key_id_guard: KeyIdGuard,
2142 destination: &KeyDescriptor,
2143 caller_uid: u32,
2144 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2145 ) -> Result<()> {
2146 let destination = match destination.domain {
2147 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2148 Domain::SELINUX => (*destination).clone(),
2149 domain => {
2150 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2151 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2152 }
2153 };
2154
2155 // Security critical: Must return immediately on failure. Do not remove the '?';
2156 check_permission(&destination)
2157 .context("In migrate_key_namespace: Trying to check permission.")?;
2158
2159 let alias = destination
2160 .alias
2161 .as_ref()
2162 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2163 .context("In migrate_key_namespace: Alias must be specified.")?;
2164
2165 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2166 // Query the destination location. If there is a key, the migration request fails.
2167 if tx
2168 .query_row(
2169 "SELECT id FROM persistent.keyentry
2170 WHERE alias = ? AND domain = ? AND namespace = ?;",
2171 params![alias, destination.domain.0, destination.nspace],
2172 |_| Ok(()),
2173 )
2174 .optional()
2175 .context("Failed to query destination.")?
2176 .is_some()
2177 {
2178 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2179 .context("Target already exists.");
2180 }
2181
2182 let updated = tx
2183 .execute(
2184 "UPDATE persistent.keyentry
2185 SET alias = ?, domain = ?, namespace = ?
2186 WHERE id = ?;",
2187 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2188 )
2189 .context("Failed to update key entry.")?;
2190
2191 if updated != 1 {
2192 return Err(KsError::sys())
2193 .context(format!("Update succeeded, but {} rows were updated.", updated));
2194 }
2195 Ok(()).no_gc()
2196 })
2197 .context("In migrate_key_namespace:")
2198 }
2199
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002200 /// Store a new key in a single transaction.
2201 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2202 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002203 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2204 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002205 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002206 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002207 key: &KeyDescriptor,
2208 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002209 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002210 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002211 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002212 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002213 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002214 let (alias, domain, namespace) = match key {
2215 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2216 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2217 (alias, key.domain, nspace)
2218 }
2219 _ => {
2220 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2221 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2222 }
2223 };
2224 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002225 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002226 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002227 let (blob, blob_metadata) = *blob_info;
2228 Self::set_blob_internal(
2229 tx,
2230 key_id.id(),
2231 SubComponentType::KEY_BLOB,
2232 Some(blob),
2233 Some(&blob_metadata),
2234 )
2235 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002236 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002237 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002238 .context("Trying to insert the certificate.")?;
2239 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002240 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002241 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002242 tx,
2243 key_id.id(),
2244 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002245 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002246 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002247 )
2248 .context("Trying to insert the certificate chain.")?;
2249 }
2250 Self::insert_keyparameter_internal(tx, &key_id, params)
2251 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002252 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002253 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002254 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002255 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002256 })
2257 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002258 }
2259
Janis Danisevskis377d1002021-01-27 19:07:48 -08002260 /// Store a new certificate
2261 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2262 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002263 pub fn store_new_certificate(
2264 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002265 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002266 cert: &[u8],
2267 km_uuid: &Uuid,
2268 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002269 let (alias, domain, namespace) = match key {
2270 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2271 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2272 (alias, key.domain, nspace)
2273 }
2274 _ => {
2275 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2276 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2277 )
2278 }
2279 };
2280 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002281 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002282 .context("Trying to create new key entry.")?;
2283
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002284 Self::set_blob_internal(
2285 tx,
2286 key_id.id(),
2287 SubComponentType::CERT_CHAIN,
2288 Some(cert),
2289 None,
2290 )
2291 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002292
2293 let mut metadata = KeyMetaData::new();
2294 metadata.add(KeyMetaEntry::CreationDate(
2295 DateTime::now().context("Trying to make creation time.")?,
2296 ));
2297
2298 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2299
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002300 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002301 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002302 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002303 })
2304 .context("In store_new_certificate.")
2305 }
2306
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002307 // Helper function loading the key_id given the key descriptor
2308 // tuple comprising domain, namespace, and alias.
2309 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002310 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002311 let alias = key
2312 .alias
2313 .as_ref()
2314 .map_or_else(|| Err(KsError::sys()), Ok)
2315 .context("In load_key_entry_id: Alias must be specified.")?;
2316 let mut stmt = tx
2317 .prepare(
2318 "SELECT id FROM persistent.keyentry
2319 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002320 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002321 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002322 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002323 AND alias = ?
2324 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002325 )
2326 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2327 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002328 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002329 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002330 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002331 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002332 .get(0)
2333 .context("Failed to unpack id.")
2334 })
2335 .context("In load_key_entry_id.")
2336 }
2337
2338 /// This helper function completes the access tuple of a key, which is required
2339 /// to perform access control. The strategy depends on the `domain` field in the
2340 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002341 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002342 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002343 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002344 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002345 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002346 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002347 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002348 /// `namespace`.
2349 /// In each case the information returned is sufficient to perform the access
2350 /// check and the key id can be used to load further key artifacts.
2351 fn load_access_tuple(
2352 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002353 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002354 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002355 caller_uid: u32,
2356 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2357 match key.domain {
2358 // Domain App or SELinux. In this case we load the key_id from
2359 // the keyentry database for further loading of key components.
2360 // We already have the full access tuple to perform access control.
2361 // The only distinction is that we use the caller_uid instead
2362 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002363 // Domain::APP.
2364 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002365 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002366 if access_key.domain == Domain::APP {
2367 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002368 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002369 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002370 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002371
2372 Ok((key_id, access_key, None))
2373 }
2374
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002375 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002376 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002377 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002378 let mut stmt = tx
2379 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002380 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002381 WHERE grantee = ? AND id = ?;",
2382 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002383 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002384 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002385 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002386 .context("Domain:Grant: query failed.")?;
2387 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002388 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002389 let r =
2390 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002391 Ok((
2392 r.get(0).context("Failed to unpack key_id.")?,
2393 r.get(1).context("Failed to unpack access_vector.")?,
2394 ))
2395 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002396 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002397 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002398 }
2399
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002400 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002401 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002402 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002403 let (domain, namespace): (Domain, i64) = {
2404 let mut stmt = tx
2405 .prepare(
2406 "SELECT domain, namespace FROM persistent.keyentry
2407 WHERE
2408 id = ?
2409 AND state = ?;",
2410 )
2411 .context("Domain::KEY_ID: prepare statement failed")?;
2412 let mut rows = stmt
2413 .query(params![key.nspace, KeyLifeCycle::Live])
2414 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002415 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002416 let r =
2417 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002418 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002419 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002420 r.get(1).context("Failed to unpack namespace.")?,
2421 ))
2422 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002423 .context("Domain::KEY_ID.")?
2424 };
2425
2426 // We may use a key by id after loading it by grant.
2427 // In this case we have to check if the caller has a grant for this particular
2428 // key. We can skip this if we already know that the caller is the owner.
2429 // But we cannot know this if domain is anything but App. E.g. in the case
2430 // of Domain::SELINUX we have to speculatively check for grants because we have to
2431 // consult the SEPolicy before we know if the caller is the owner.
2432 let access_vector: Option<KeyPermSet> =
2433 if domain != Domain::APP || namespace != caller_uid as i64 {
2434 let access_vector: Option<i32> = tx
2435 .query_row(
2436 "SELECT access_vector FROM persistent.grant
2437 WHERE grantee = ? AND keyentryid = ?;",
2438 params![caller_uid as i64, key.nspace],
2439 |row| row.get(0),
2440 )
2441 .optional()
2442 .context("Domain::KEY_ID: query grant failed.")?;
2443 access_vector.map(|p| p.into())
2444 } else {
2445 None
2446 };
2447
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002448 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002449 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002450 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002451 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002452
Janis Danisevskis45760022021-01-19 16:34:10 -08002453 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002454 }
2455 _ => Err(anyhow!(KsError::sys())),
2456 }
2457 }
2458
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002459 fn load_blob_components(
2460 key_id: i64,
2461 load_bits: KeyEntryLoadBits,
2462 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002463 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002464 let mut stmt = tx
2465 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002466 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002467 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2468 )
2469 .context("In load_blob_components: prepare statement failed.")?;
2470
2471 let mut rows =
2472 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2473
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002474 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002475 let mut cert_blob: Option<Vec<u8>> = None;
2476 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002477 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002478 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002479 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002480 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002481 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002482 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2483 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002484 key_blob = Some((
2485 row.get(0).context("Failed to extract key blob id.")?,
2486 row.get(2).context("Failed to extract key blob.")?,
2487 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002488 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002489 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002490 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002491 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002492 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002493 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002494 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002495 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002496 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002497 (SubComponentType::CERT, _, _)
2498 | (SubComponentType::CERT_CHAIN, _, _)
2499 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002500 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2501 }
2502 Ok(())
2503 })
2504 .context("In load_blob_components.")?;
2505
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002506 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2507 Ok(Some((
2508 blob,
2509 BlobMetaData::load_from_db(blob_id, tx)
2510 .context("In load_blob_components: Trying to load blob_metadata.")?,
2511 )))
2512 })?;
2513
2514 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002515 }
2516
2517 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2518 let mut stmt = tx
2519 .prepare(
2520 "SELECT tag, data, security_level from persistent.keyparameter
2521 WHERE keyentryid = ?;",
2522 )
2523 .context("In load_key_parameters: prepare statement failed.")?;
2524
2525 let mut parameters: Vec<KeyParameter> = Vec::new();
2526
2527 let mut rows =
2528 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002529 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002530 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2531 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002532 parameters.push(
2533 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2534 .context("Failed to read KeyParameter.")?,
2535 );
2536 Ok(())
2537 })
2538 .context("In load_key_parameters.")?;
2539
2540 Ok(parameters)
2541 }
2542
Qi Wub9433b52020-12-01 14:52:46 +08002543 /// Decrements the usage count of a limited use key. This function first checks whether the
2544 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2545 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2546 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002547 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002548 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2549 let limit: Option<i32> = tx
2550 .query_row(
2551 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2552 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2553 |row| row.get(0),
2554 )
2555 .optional()
2556 .context("Trying to load usage count")?;
2557
2558 let limit = limit
2559 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2560 .context("The Key no longer exists. Key is exhausted.")?;
2561
2562 tx.execute(
2563 "UPDATE persistent.keyparameter
2564 SET data = data - 1
2565 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2566 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2567 )
2568 .context("Failed to update key usage count.")?;
2569
2570 match limit {
2571 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002572 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002573 .context("Trying to mark limited use key for deletion."),
2574 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002575 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002576 }
2577 })
2578 .context("In check_and_update_key_usage_count.")
2579 }
2580
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002581 /// Load a key entry by the given key descriptor.
2582 /// It uses the `check_permission` callback to verify if the access is allowed
2583 /// given the key access tuple read from the database using `load_access_tuple`.
2584 /// With `load_bits` the caller may specify which blobs shall be loaded from
2585 /// the blob database.
2586 pub fn load_key_entry(
2587 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002588 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002589 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002590 load_bits: KeyEntryLoadBits,
2591 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002592 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2593 ) -> Result<(KeyIdGuard, KeyEntry)> {
2594 loop {
2595 match self.load_key_entry_internal(
2596 key,
2597 key_type,
2598 load_bits,
2599 caller_uid,
2600 &check_permission,
2601 ) {
2602 Ok(result) => break Ok(result),
2603 Err(e) => {
2604 if Self::is_locked_error(&e) {
2605 std::thread::sleep(std::time::Duration::from_micros(500));
2606 continue;
2607 } else {
2608 return Err(e).context("In load_key_entry.");
2609 }
2610 }
2611 }
2612 }
2613 }
2614
2615 fn load_key_entry_internal(
2616 &mut self,
2617 key: &KeyDescriptor,
2618 key_type: KeyType,
2619 load_bits: KeyEntryLoadBits,
2620 caller_uid: u32,
2621 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002622 ) -> Result<(KeyIdGuard, KeyEntry)> {
2623 // KEY ID LOCK 1/2
2624 // If we got a key descriptor with a key id we can get the lock right away.
2625 // Otherwise we have to defer it until we know the key id.
2626 let key_id_guard = match key.domain {
2627 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2628 _ => None,
2629 };
2630
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002631 let tx = self
2632 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002633 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002634 .context("In load_key_entry: Failed to initialize transaction.")?;
2635
2636 // Load the key_id and complete the access control tuple.
2637 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002638 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2639 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002640
2641 // Perform access control. It is vital that we return here if the permission is denied.
2642 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002643 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002644
Janis Danisevskisaec14592020-11-12 09:41:49 -08002645 // KEY ID LOCK 2/2
2646 // If we did not get a key id lock by now, it was because we got a key descriptor
2647 // without a key id. At this point we got the key id, so we can try and get a lock.
2648 // However, we cannot block here, because we are in the middle of the transaction.
2649 // So first we try to get the lock non blocking. If that fails, we roll back the
2650 // transaction and block until we get the lock. After we successfully got the lock,
2651 // we start a new transaction and load the access tuple again.
2652 //
2653 // We don't need to perform access control again, because we already established
2654 // that the caller had access to the given key. But we need to make sure that the
2655 // key id still exists. So we have to load the key entry by key id this time.
2656 let (key_id_guard, tx) = match key_id_guard {
2657 None => match KEY_ID_LOCK.try_get(key_id) {
2658 None => {
2659 // Roll back the transaction.
2660 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002661
Janis Danisevskisaec14592020-11-12 09:41:49 -08002662 // Block until we have a key id lock.
2663 let key_id_guard = KEY_ID_LOCK.get(key_id);
2664
2665 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002666 let tx = self
2667 .conn
2668 .unchecked_transaction()
2669 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002670
2671 Self::load_access_tuple(
2672 &tx,
2673 // This time we have to load the key by the retrieved key id, because the
2674 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002675 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002676 domain: Domain::KEY_ID,
2677 nspace: key_id,
2678 ..Default::default()
2679 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002680 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002681 caller_uid,
2682 )
2683 .context("In load_key_entry. (deferred key lock)")?;
2684 (key_id_guard, tx)
2685 }
2686 Some(l) => (l, tx),
2687 },
2688 Some(key_id_guard) => (key_id_guard, tx),
2689 };
2690
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002691 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2692 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002693
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002694 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2695
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002696 Ok((key_id_guard, key_entry))
2697 }
2698
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002699 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002700 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002701 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2702 .context("Trying to delete keyentry.")?;
2703 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2704 .context("Trying to delete keymetadata.")?;
2705 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2706 .context("Trying to delete keyparameters.")?;
2707 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2708 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002709 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002710 }
2711
2712 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002713 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002714 pub fn unbind_key(
2715 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002716 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002717 key_type: KeyType,
2718 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002719 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002720 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002721 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2722 let (key_id, access_key_descriptor, access_vector) =
2723 Self::load_access_tuple(tx, key, key_type, caller_uid)
2724 .context("Trying to get access tuple.")?;
2725
2726 // Perform access control. It is vital that we return here if the permission is denied.
2727 // So do not touch that '?' at the end.
2728 check_permission(&access_key_descriptor, access_vector)
2729 .context("While checking permission.")?;
2730
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002731 Self::mark_unreferenced(tx, key_id)
2732 .map(|need_gc| (need_gc, ()))
2733 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002734 })
2735 .context("In unbind_key.")
2736 }
2737
Max Bires8e93d2b2021-01-14 13:17:59 -08002738 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2739 tx.query_row(
2740 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2741 params![key_id],
2742 |row| row.get(0),
2743 )
2744 .context("In get_key_km_uuid.")
2745 }
2746
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002747 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2748 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2749 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
2750 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2751 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2752 .context("In unbind_keys_for_namespace.");
2753 }
2754 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2755 tx.execute(
2756 "DELETE FROM persistent.keymetadata
2757 WHERE keyentryid IN (
2758 SELECT id FROM persistent.keyentry
2759 WHERE domain = ? AND namespace = ?
2760 );",
2761 params![domain.0, namespace],
2762 )
2763 .context("Trying to delete keymetadata.")?;
2764 tx.execute(
2765 "DELETE FROM persistent.keyparameter
2766 WHERE keyentryid IN (
2767 SELECT id FROM persistent.keyentry
2768 WHERE domain = ? AND namespace = ?
2769 );",
2770 params![domain.0, namespace],
2771 )
2772 .context("Trying to delete keyparameters.")?;
2773 tx.execute(
2774 "DELETE FROM persistent.grant
2775 WHERE keyentryid IN (
2776 SELECT id FROM persistent.keyentry
2777 WHERE domain = ? AND namespace = ?
2778 );",
2779 params![domain.0, namespace],
2780 )
2781 .context("Trying to delete grants.")?;
2782 tx.execute(
2783 "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;",
2784 params![domain.0, namespace],
2785 )
2786 .context("Trying to delete keyentry.")?;
2787 Ok(()).need_gc()
2788 })
2789 .context("In unbind_keys_for_namespace")
2790 }
2791
Hasini Gunasingheda895552021-01-27 19:34:37 +00002792 /// Delete the keys created on behalf of the user, denoted by the user id.
2793 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2794 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2795 /// The caller of this function should notify the gc if the returned value is true.
2796 pub fn unbind_keys_for_user(
2797 &mut self,
2798 user_id: u32,
2799 keep_non_super_encrypted_keys: bool,
2800 ) -> Result<()> {
2801 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2802 let mut stmt = tx
2803 .prepare(&format!(
2804 "SELECT id from persistent.keyentry
2805 WHERE (
2806 key_type = ?
2807 AND domain = ?
2808 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2809 AND state = ?
2810 ) OR (
2811 key_type = ?
2812 AND namespace = ?
2813 AND alias = ?
2814 AND state = ?
2815 );",
2816 aid_user_offset = AID_USER_OFFSET
2817 ))
2818 .context(concat!(
2819 "In unbind_keys_for_user. ",
2820 "Failed to prepare the query to find the keys created by apps."
2821 ))?;
2822
2823 let mut rows = stmt
2824 .query(params![
2825 // WHERE client key:
2826 KeyType::Client,
2827 Domain::APP.0 as u32,
2828 user_id,
2829 KeyLifeCycle::Live,
2830 // OR super key:
2831 KeyType::Super,
2832 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002833 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002834 KeyLifeCycle::Live
2835 ])
2836 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2837
2838 let mut key_ids: Vec<i64> = Vec::new();
2839 db_utils::with_rows_extract_all(&mut rows, |row| {
2840 key_ids
2841 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2842 Ok(())
2843 })
2844 .context("In unbind_keys_for_user.")?;
2845
2846 let mut notify_gc = false;
2847 for key_id in key_ids {
2848 if keep_non_super_encrypted_keys {
2849 // Load metadata and filter out non-super-encrypted keys.
2850 if let (_, Some((_, blob_metadata)), _, _) =
2851 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2852 .context("In unbind_keys_for_user: Trying to load blob info.")?
2853 {
2854 if blob_metadata.encrypted_by().is_none() {
2855 continue;
2856 }
2857 }
2858 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002859 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002860 .context("In unbind_keys_for_user.")?
2861 || notify_gc;
2862 }
2863 Ok(()).do_gc(notify_gc)
2864 })
2865 .context("In unbind_keys_for_user.")
2866 }
2867
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002868 fn load_key_components(
2869 tx: &Transaction,
2870 load_bits: KeyEntryLoadBits,
2871 key_id: i64,
2872 ) -> Result<KeyEntry> {
2873 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2874
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002875 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002876 Self::load_blob_components(key_id, load_bits, &tx)
2877 .context("In load_key_components.")?;
2878
Max Bires8e93d2b2021-01-14 13:17:59 -08002879 let parameters = Self::load_key_parameters(key_id, &tx)
2880 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002881
Max Bires8e93d2b2021-01-14 13:17:59 -08002882 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2883 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002884
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002885 Ok(KeyEntry {
2886 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002887 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002888 cert: cert_blob,
2889 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002890 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002891 parameters,
2892 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002893 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002894 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002895 }
2896
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002897 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2898 /// The key descriptors will have the domain, nspace, and alias field set.
2899 /// Domain must be APP or SELINUX, the caller must make sure of that.
2900 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002901 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2902 let mut stmt = tx
2903 .prepare(
2904 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002905 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002906 )
2907 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002908
Janis Danisevskis66784c42021-01-27 08:40:25 -08002909 let mut rows = stmt
2910 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2911 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002912
Janis Danisevskis66784c42021-01-27 08:40:25 -08002913 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2914 db_utils::with_rows_extract_all(&mut rows, |row| {
2915 descriptors.push(KeyDescriptor {
2916 domain,
2917 nspace: namespace,
2918 alias: Some(row.get(0).context("Trying to extract alias.")?),
2919 blob: None,
2920 });
2921 Ok(())
2922 })
2923 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002924 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002925 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002926 }
2927
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002928 /// Adds a grant to the grant table.
2929 /// Like `load_key_entry` this function loads the access tuple before
2930 /// it uses the callback for a permission check. Upon success,
2931 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2932 /// grant table. The new row will have a randomized id, which is used as
2933 /// grant id in the namespace field of the resulting KeyDescriptor.
2934 pub fn grant(
2935 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002936 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002937 caller_uid: u32,
2938 grantee_uid: u32,
2939 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002940 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002941 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002942 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2943 // Load the key_id and complete the access control tuple.
2944 // We ignore the access vector here because grants cannot be granted.
2945 // The access vector returned here expresses the permissions the
2946 // grantee has if key.domain == Domain::GRANT. But this vector
2947 // cannot include the grant permission by design, so there is no way the
2948 // subsequent permission check can pass.
2949 // We could check key.domain == Domain::GRANT and fail early.
2950 // But even if we load the access tuple by grant here, the permission
2951 // check denies the attempt to create a grant by grant descriptor.
2952 let (key_id, access_key_descriptor, _) =
2953 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2954 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002955
Janis Danisevskis66784c42021-01-27 08:40:25 -08002956 // Perform access control. It is vital that we return here if the permission
2957 // was denied. So do not touch that '?' at the end of the line.
2958 // This permission check checks if the caller has the grant permission
2959 // for the given key and in addition to all of the permissions
2960 // expressed in `access_vector`.
2961 check_permission(&access_key_descriptor, &access_vector)
2962 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002963
Janis Danisevskis66784c42021-01-27 08:40:25 -08002964 let grant_id = if let Some(grant_id) = tx
2965 .query_row(
2966 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002967 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002968 params![key_id, grantee_uid],
2969 |row| row.get(0),
2970 )
2971 .optional()
2972 .context("In grant: Failed get optional existing grant id.")?
2973 {
2974 tx.execute(
2975 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002976 SET access_vector = ?
2977 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002978 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002979 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002980 .context("In grant: Failed to update existing grant.")?;
2981 grant_id
2982 } else {
2983 Self::insert_with_retry(|id| {
2984 tx.execute(
2985 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2986 VALUES (?, ?, ?, ?);",
2987 params![id, grantee_uid, key_id, i32::from(access_vector)],
2988 )
2989 })
2990 .context("In grant")?
2991 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002992
Janis Danisevskis66784c42021-01-27 08:40:25 -08002993 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002994 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002995 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002996 }
2997
2998 /// This function checks permissions like `grant` and `load_key_entry`
2999 /// before removing a grant from the grant table.
3000 pub fn ungrant(
3001 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003002 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003003 caller_uid: u32,
3004 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003005 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003006 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08003007 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3008 // Load the key_id and complete the access control tuple.
3009 // We ignore the access vector here because grants cannot be granted.
3010 let (key_id, access_key_descriptor, _) =
3011 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3012 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003013
Janis Danisevskis66784c42021-01-27 08:40:25 -08003014 // Perform access control. We must return here if the permission
3015 // was denied. So do not touch the '?' at the end of this line.
3016 check_permission(&access_key_descriptor)
3017 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003018
Janis Danisevskis66784c42021-01-27 08:40:25 -08003019 tx.execute(
3020 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003021 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003022 params![key_id, grantee_uid],
3023 )
3024 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003025
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003026 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003027 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003028 }
3029
Joel Galenson845f74b2020-09-09 14:11:55 -07003030 // Generates a random id and passes it to the given function, which will
3031 // try to insert it into a database. If that insertion fails, retry;
3032 // otherwise return the id.
3033 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3034 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003035 let newid: i64 = match random() {
3036 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3037 i => i,
3038 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003039 match inserter(newid) {
3040 // If the id already existed, try again.
3041 Err(rusqlite::Error::SqliteFailure(
3042 libsqlite3_sys::Error {
3043 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3044 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3045 },
3046 _,
3047 )) => (),
3048 Err(e) => {
3049 return Err(e).context("In insert_with_retry: failed to insert into database.")
3050 }
3051 _ => return Ok(newid),
3052 }
3053 }
3054 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003055
3056 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
3057 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08003058 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3059 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003060 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
3061 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
3062 params![
3063 auth_token.challenge,
3064 auth_token.userId,
3065 auth_token.authenticatorId,
3066 auth_token.authenticatorType.0 as i32,
3067 auth_token.timestamp.milliSeconds as i64,
3068 auth_token.mac,
3069 MonotonicRawTime::now(),
3070 ],
3071 )
3072 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003073 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003074 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003075 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003076
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003077 /// Find the newest auth token matching the given predicate.
3078 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003079 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003080 p: F,
3081 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
3082 where
3083 F: Fn(&AuthTokenEntry) -> bool,
3084 {
3085 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3086 let mut stmt = tx
3087 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
3088 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003089
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003090 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003091
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003092 while let Some(row) = rows.next().context("Failed to get next row.")? {
3093 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003094 HardwareAuthToken {
3095 challenge: row.get(1)?,
3096 userId: row.get(2)?,
3097 authenticatorId: row.get(3)?,
3098 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3099 timestamp: Timestamp { milliSeconds: row.get(5)? },
3100 mac: row.get(6)?,
3101 },
3102 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003103 );
3104 if p(&entry) {
3105 return Ok(Some((
3106 entry,
3107 Self::get_last_off_body(tx)
3108 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003109 )))
3110 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003111 }
3112 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003113 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003114 })
3115 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003116 }
3117
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003118 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003119 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
3120 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3121 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003122 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3123 params!["last_off_body", last_off_body],
3124 )
3125 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003126 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003127 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003128 }
3129
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003130 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003131 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
3132 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3133 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003134 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3135 params![last_off_body, "last_off_body"],
3136 )
3137 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003138 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003139 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003140 }
3141
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003142 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003143 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003144 tx.query_row(
3145 "SELECT value from perboot.metadata WHERE key = ?;",
3146 params!["last_off_body"],
3147 |row| Ok(row.get(0)?),
3148 )
3149 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003150 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003151}
3152
3153#[cfg(test)]
3154mod tests {
3155
3156 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003157 use crate::key_parameter::{
3158 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3159 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3160 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003161 use crate::key_perm_set;
3162 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003163 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003164 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003165 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3166 HardwareAuthToken::HardwareAuthToken,
3167 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003168 };
3169 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003170 Timestamp::Timestamp,
3171 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003172 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003173 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003174 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003175 use std::collections::BTreeMap;
3176 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003177 use std::sync::atomic::{AtomicU8, Ordering};
3178 use std::sync::Arc;
3179 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003180 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003181 #[cfg(disabled)]
3182 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003183
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003184 fn new_test_db() -> Result<KeystoreDB> {
3185 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3186
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003187 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003188 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003189 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003190 })?;
3191 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003192 }
3193
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003194 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3195 where
3196 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3197 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003198 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003199
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003200 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003201 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003202
3203 KeystoreDB::new(path, Some(gc))
3204 }
3205
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003206 fn rebind_alias(
3207 db: &mut KeystoreDB,
3208 newid: &KeyIdGuard,
3209 alias: &str,
3210 domain: Domain,
3211 namespace: i64,
3212 ) -> Result<bool> {
3213 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003214 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003215 })
3216 .context("In rebind_alias.")
3217 }
3218
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003219 #[test]
3220 fn datetime() -> Result<()> {
3221 let conn = Connection::open_in_memory()?;
3222 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3223 let now = SystemTime::now();
3224 let duration = Duration::from_secs(1000);
3225 let then = now.checked_sub(duration).unwrap();
3226 let soon = now.checked_add(duration).unwrap();
3227 conn.execute(
3228 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3229 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3230 )?;
3231 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3232 let mut rows = stmt.query(NO_PARAMS)?;
3233 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3234 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3235 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3236 assert!(rows.next()?.is_none());
3237 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3238 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3239 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3240 Ok(())
3241 }
3242
Joel Galenson0891bc12020-07-20 10:37:03 -07003243 // Ensure that we're using the "injected" random function, not the real one.
3244 #[test]
3245 fn test_mocked_random() {
3246 let rand1 = random();
3247 let rand2 = random();
3248 let rand3 = random();
3249 if rand1 == rand2 {
3250 assert_eq!(rand2 + 1, rand3);
3251 } else {
3252 assert_eq!(rand1 + 1, rand2);
3253 assert_eq!(rand2, rand3);
3254 }
3255 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003256
Joel Galenson26f4d012020-07-17 14:57:21 -07003257 // Test that we have the correct tables.
3258 #[test]
3259 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003260 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003261 let tables = db
3262 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003263 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003264 .query_map(params![], |row| row.get(0))?
3265 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003266 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003267 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003268 assert_eq!(tables[1], "blobmetadata");
3269 assert_eq!(tables[2], "grant");
3270 assert_eq!(tables[3], "keyentry");
3271 assert_eq!(tables[4], "keymetadata");
3272 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003273 let tables = db
3274 .conn
3275 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3276 .query_map(params![], |row| row.get(0))?
3277 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003278
3279 assert_eq!(tables.len(), 2);
3280 assert_eq!(tables[0], "authtoken");
3281 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003282 Ok(())
3283 }
3284
3285 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003286 fn test_auth_token_table_invariant() -> Result<()> {
3287 let mut db = new_test_db()?;
3288 let auth_token1 = HardwareAuthToken {
3289 challenge: i64::MAX,
3290 userId: 200,
3291 authenticatorId: 200,
3292 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3293 timestamp: Timestamp { milliSeconds: 500 },
3294 mac: String::from("mac").into_bytes(),
3295 };
3296 db.insert_auth_token(&auth_token1)?;
3297 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3298 assert_eq!(auth_tokens_returned.len(), 1);
3299
3300 // insert another auth token with the same values for the columns in the UNIQUE constraint
3301 // of the auth token table and different value for timestamp
3302 let auth_token2 = HardwareAuthToken {
3303 challenge: i64::MAX,
3304 userId: 200,
3305 authenticatorId: 200,
3306 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3307 timestamp: Timestamp { milliSeconds: 600 },
3308 mac: String::from("mac").into_bytes(),
3309 };
3310
3311 db.insert_auth_token(&auth_token2)?;
3312 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3313 assert_eq!(auth_tokens_returned.len(), 1);
3314
3315 if let Some(auth_token) = auth_tokens_returned.pop() {
3316 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3317 }
3318
3319 // insert another auth token with the different values for the columns in the UNIQUE
3320 // constraint of the auth token table
3321 let auth_token3 = HardwareAuthToken {
3322 challenge: i64::MAX,
3323 userId: 201,
3324 authenticatorId: 200,
3325 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3326 timestamp: Timestamp { milliSeconds: 600 },
3327 mac: String::from("mac").into_bytes(),
3328 };
3329
3330 db.insert_auth_token(&auth_token3)?;
3331 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3332 assert_eq!(auth_tokens_returned.len(), 2);
3333
3334 Ok(())
3335 }
3336
3337 // utility function for test_auth_token_table_invariant()
3338 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3339 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3340
3341 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3342 .query_map(NO_PARAMS, |row| {
3343 Ok(AuthTokenEntry::new(
3344 HardwareAuthToken {
3345 challenge: row.get(1)?,
3346 userId: row.get(2)?,
3347 authenticatorId: row.get(3)?,
3348 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3349 timestamp: Timestamp { milliSeconds: row.get(5)? },
3350 mac: row.get(6)?,
3351 },
3352 row.get(7)?,
3353 ))
3354 })?
3355 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3356 Ok(auth_token_entries)
3357 }
3358
3359 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003360 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003361 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003362 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003363
Janis Danisevskis66784c42021-01-27 08:40:25 -08003364 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003365 let entries = get_keyentry(&db)?;
3366 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003367
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003368 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003369
3370 let entries_new = get_keyentry(&db)?;
3371 assert_eq!(entries, entries_new);
3372 Ok(())
3373 }
3374
3375 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003376 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003377 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3378 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003379 }
3380
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003381 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003382
Janis Danisevskis66784c42021-01-27 08:40:25 -08003383 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3384 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003385
3386 let entries = get_keyentry(&db)?;
3387 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003388 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3389 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003390
3391 // Test that we must pass in a valid Domain.
3392 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003393 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003394 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003395 );
3396 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003397 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003398 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003399 );
3400 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003401 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003402 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003403 );
3404
3405 Ok(())
3406 }
3407
Joel Galenson33c04ad2020-08-03 11:04:38 -07003408 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003409 fn test_add_unsigned_key() -> Result<()> {
3410 let mut db = new_test_db()?;
3411 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3412 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3413 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3414 db.create_attestation_key_entry(
3415 &public_key,
3416 &raw_public_key,
3417 &private_key,
3418 &KEYSTORE_UUID,
3419 )?;
3420 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3421 assert_eq!(keys.len(), 1);
3422 assert_eq!(keys[0], public_key);
3423 Ok(())
3424 }
3425
3426 #[test]
3427 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3428 let mut db = new_test_db()?;
3429 let expiration_date: i64 = 20;
3430 let namespace: i64 = 30;
3431 let base_byte: u8 = 1;
3432 let loaded_values =
3433 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3434 let chain =
3435 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3436 assert_eq!(true, chain.is_some());
3437 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003438 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003439 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3440 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003441 Ok(())
3442 }
3443
3444 #[test]
3445 fn test_get_attestation_pool_status() -> Result<()> {
3446 let mut db = new_test_db()?;
3447 let namespace: i64 = 30;
3448 load_attestation_key_pool(
3449 &mut db, 10, /* expiration */
3450 namespace, 0x01, /* base_byte */
3451 )?;
3452 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3453 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3454 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3455 assert_eq!(status.expiring, 0);
3456 assert_eq!(status.attested, 3);
3457 assert_eq!(status.unassigned, 0);
3458 assert_eq!(status.total, 3);
3459 assert_eq!(
3460 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3461 1
3462 );
3463 assert_eq!(
3464 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3465 2
3466 );
3467 assert_eq!(
3468 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3469 3
3470 );
3471 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3472 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3473 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3474 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003475 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003476 db.create_attestation_key_entry(
3477 &public_key,
3478 &raw_public_key,
3479 &private_key,
3480 &KEYSTORE_UUID,
3481 )?;
3482 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3483 assert_eq!(status.attested, 3);
3484 assert_eq!(status.unassigned, 0);
3485 assert_eq!(status.total, 4);
3486 db.store_signed_attestation_certificate_chain(
3487 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003488 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003489 &cert_chain,
3490 20,
3491 &KEYSTORE_UUID,
3492 )?;
3493 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3494 assert_eq!(status.attested, 4);
3495 assert_eq!(status.unassigned, 1);
3496 assert_eq!(status.total, 4);
3497 Ok(())
3498 }
3499
3500 #[test]
3501 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003502 let temp_dir =
3503 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3504 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003505 let expiration_date: i64 =
3506 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3507 let namespace: i64 = 30;
3508 let namespace_del1: i64 = 45;
3509 let namespace_del2: i64 = 60;
3510 let entry_values = load_attestation_key_pool(
3511 &mut db,
3512 expiration_date,
3513 namespace,
3514 0x01, /* base_byte */
3515 )?;
3516 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3517 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003518
3519 let blob_entry_row_count: u32 = db
3520 .conn
3521 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3522 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003523 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3524 // one key, one certificate chain, and one certificate.
3525 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003526
Max Bires2b2e6562020-09-22 11:22:36 -07003527 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3528
3529 let mut cert_chain =
3530 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003531 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003532 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003533 assert_eq!(entry_values.batch_cert, value.batch_cert);
3534 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003535 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003536
3537 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3538 Domain::APP,
3539 namespace_del1,
3540 &KEYSTORE_UUID,
3541 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003542 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003543 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3544 Domain::APP,
3545 namespace_del2,
3546 &KEYSTORE_UUID,
3547 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003548 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003549
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003550 // Give the garbage collector half a second to catch up.
3551 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003552
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003553 let blob_entry_row_count: u32 = db
3554 .conn
3555 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3556 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003557 // There shound be 3 blob entries left, because we deleted two of the attestation
3558 // key entries with three blobs each.
3559 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003560
Max Bires2b2e6562020-09-22 11:22:36 -07003561 Ok(())
3562 }
3563
3564 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003565 fn test_delete_all_attestation_keys() -> Result<()> {
3566 let mut db = new_test_db()?;
3567 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3568 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3569 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3570 let result = db.delete_all_attestation_keys()?;
3571
3572 // Give the garbage collector half a second to catch up.
3573 std::thread::sleep(Duration::from_millis(500));
3574
3575 // Attestation keys should be deleted, and the regular key should remain.
3576 assert_eq!(result, 2);
3577
3578 Ok(())
3579 }
3580
3581 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003582 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003583 fn extractor(
3584 ke: &KeyEntryRow,
3585 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3586 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003587 }
3588
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003589 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003590 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3591 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003592 let entries = get_keyentry(&db)?;
3593 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003594 assert_eq!(
3595 extractor(&entries[0]),
3596 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3597 );
3598 assert_eq!(
3599 extractor(&entries[1]),
3600 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3601 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003602
3603 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003604 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003605 let entries = get_keyentry(&db)?;
3606 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003607 assert_eq!(
3608 extractor(&entries[0]),
3609 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3610 );
3611 assert_eq!(
3612 extractor(&entries[1]),
3613 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3614 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003615
3616 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003617 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003618 let entries = get_keyentry(&db)?;
3619 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003620 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3621 assert_eq!(
3622 extractor(&entries[1]),
3623 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3624 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003625
3626 // Test that we must pass in a valid Domain.
3627 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003628 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003629 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003630 );
3631 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003632 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003633 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003634 );
3635 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003636 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003637 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003638 );
3639
3640 // Test that we correctly handle setting an alias for something that does not exist.
3641 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003642 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003643 "Expected to update a single entry but instead updated 0",
3644 );
3645 // Test that we correctly abort the transaction in this case.
3646 let entries = get_keyentry(&db)?;
3647 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003648 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3649 assert_eq!(
3650 extractor(&entries[1]),
3651 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3652 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003653
3654 Ok(())
3655 }
3656
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003657 #[test]
3658 fn test_grant_ungrant() -> Result<()> {
3659 const CALLER_UID: u32 = 15;
3660 const GRANTEE_UID: u32 = 12;
3661 const SELINUX_NAMESPACE: i64 = 7;
3662
3663 let mut db = new_test_db()?;
3664 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003665 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3666 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3667 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003668 )?;
3669 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003670 domain: super::Domain::APP,
3671 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003672 alias: Some("key".to_string()),
3673 blob: None,
3674 };
3675 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3676 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3677
3678 // Reset totally predictable random number generator in case we
3679 // are not the first test running on this thread.
3680 reset_random();
3681 let next_random = 0i64;
3682
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003683 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003684 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003685 assert_eq!(*a, PVEC1);
3686 assert_eq!(
3687 *k,
3688 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003689 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003690 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003691 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003692 alias: Some("key".to_string()),
3693 blob: None,
3694 }
3695 );
3696 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003697 })
3698 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003699
3700 assert_eq!(
3701 app_granted_key,
3702 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003703 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003704 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003705 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003706 alias: None,
3707 blob: None,
3708 }
3709 );
3710
3711 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003712 domain: super::Domain::SELINUX,
3713 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003714 alias: Some("yek".to_string()),
3715 blob: None,
3716 };
3717
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003718 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003719 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003720 assert_eq!(*a, PVEC1);
3721 assert_eq!(
3722 *k,
3723 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003724 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725 // namespace must be the supplied SELinux
3726 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003727 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003728 alias: Some("yek".to_string()),
3729 blob: None,
3730 }
3731 );
3732 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003733 })
3734 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003735
3736 assert_eq!(
3737 selinux_granted_key,
3738 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003739 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003740 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003741 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003742 alias: None,
3743 blob: None,
3744 }
3745 );
3746
3747 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003748 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003749 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003750 assert_eq!(*a, PVEC2);
3751 assert_eq!(
3752 *k,
3753 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003754 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755 // namespace must be the supplied SELinux
3756 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003757 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003758 alias: Some("yek".to_string()),
3759 blob: None,
3760 }
3761 );
3762 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003763 })
3764 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003765
3766 assert_eq!(
3767 selinux_granted_key,
3768 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003769 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003770 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003771 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003772 alias: None,
3773 blob: None,
3774 }
3775 );
3776
3777 {
3778 // Limiting scope of stmt, because it borrows db.
3779 let mut stmt = db
3780 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003781 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003782 let mut rows =
3783 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3784 Ok((
3785 row.get(0)?,
3786 row.get(1)?,
3787 row.get(2)?,
3788 KeyPermSet::from(row.get::<_, i32>(3)?),
3789 ))
3790 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003791
3792 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003793 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003794 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003795 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003796 assert!(rows.next().is_none());
3797 }
3798
3799 debug_dump_keyentry_table(&mut db)?;
3800 println!("app_key {:?}", app_key);
3801 println!("selinux_key {:?}", selinux_key);
3802
Janis Danisevskis66784c42021-01-27 08:40:25 -08003803 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3804 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003805
3806 Ok(())
3807 }
3808
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003809 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003810 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3811 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3812
3813 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003814 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003815 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003816 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003817 let mut blob_metadata = BlobMetaData::new();
3818 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3819 db.set_blob(
3820 &key_id,
3821 SubComponentType::KEY_BLOB,
3822 Some(TEST_KEY_BLOB),
3823 Some(&blob_metadata),
3824 )?;
3825 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3826 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003827 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003828
3829 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003830 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003831 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003832 )?;
3833 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003834 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3835 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003836 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003837 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003838 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003839 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003840 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003841 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003842 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003843
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003844 drop(rows);
3845 drop(stmt);
3846
3847 assert_eq!(
3848 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3849 BlobMetaData::load_from_db(id, tx).no_gc()
3850 })
3851 .expect("Should find blob metadata."),
3852 blob_metadata
3853 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003854 Ok(())
3855 }
3856
3857 static TEST_ALIAS: &str = "my super duper key";
3858
3859 #[test]
3860 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3861 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003862 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003863 .context("test_insert_and_load_full_keyentry_domain_app")?
3864 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003865 let (_key_guard, key_entry) = db
3866 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003867 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003868 domain: Domain::APP,
3869 nspace: 0,
3870 alias: Some(TEST_ALIAS.to_string()),
3871 blob: None,
3872 },
3873 KeyType::Client,
3874 KeyEntryLoadBits::BOTH,
3875 1,
3876 |_k, _av| Ok(()),
3877 )
3878 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003879 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003880
3881 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003882 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003883 domain: Domain::APP,
3884 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003885 alias: Some(TEST_ALIAS.to_string()),
3886 blob: None,
3887 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003888 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003889 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003890 |_, _| Ok(()),
3891 )
3892 .unwrap();
3893
3894 assert_eq!(
3895 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3896 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003897 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003898 domain: Domain::APP,
3899 nspace: 0,
3900 alias: Some(TEST_ALIAS.to_string()),
3901 blob: None,
3902 },
3903 KeyType::Client,
3904 KeyEntryLoadBits::NONE,
3905 1,
3906 |_k, _av| Ok(()),
3907 )
3908 .unwrap_err()
3909 .root_cause()
3910 .downcast_ref::<KsError>()
3911 );
3912
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003913 Ok(())
3914 }
3915
3916 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003917 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3918 let mut db = new_test_db()?;
3919
3920 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003921 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003922 domain: Domain::APP,
3923 nspace: 1,
3924 alias: Some(TEST_ALIAS.to_string()),
3925 blob: None,
3926 },
3927 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003928 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003929 )
3930 .expect("Trying to insert cert.");
3931
3932 let (_key_guard, mut key_entry) = db
3933 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003934 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003935 domain: Domain::APP,
3936 nspace: 1,
3937 alias: Some(TEST_ALIAS.to_string()),
3938 blob: None,
3939 },
3940 KeyType::Client,
3941 KeyEntryLoadBits::PUBLIC,
3942 1,
3943 |_k, _av| Ok(()),
3944 )
3945 .expect("Trying to read certificate entry.");
3946
3947 assert!(key_entry.pure_cert());
3948 assert!(key_entry.cert().is_none());
3949 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3950
3951 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003952 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003953 domain: Domain::APP,
3954 nspace: 1,
3955 alias: Some(TEST_ALIAS.to_string()),
3956 blob: None,
3957 },
3958 KeyType::Client,
3959 1,
3960 |_, _| Ok(()),
3961 )
3962 .unwrap();
3963
3964 assert_eq!(
3965 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3966 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003967 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003968 domain: Domain::APP,
3969 nspace: 1,
3970 alias: Some(TEST_ALIAS.to_string()),
3971 blob: None,
3972 },
3973 KeyType::Client,
3974 KeyEntryLoadBits::NONE,
3975 1,
3976 |_k, _av| Ok(()),
3977 )
3978 .unwrap_err()
3979 .root_cause()
3980 .downcast_ref::<KsError>()
3981 );
3982
3983 Ok(())
3984 }
3985
3986 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003987 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3988 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003989 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003990 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3991 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003992 let (_key_guard, key_entry) = db
3993 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003994 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003995 domain: Domain::SELINUX,
3996 nspace: 1,
3997 alias: Some(TEST_ALIAS.to_string()),
3998 blob: None,
3999 },
4000 KeyType::Client,
4001 KeyEntryLoadBits::BOTH,
4002 1,
4003 |_k, _av| Ok(()),
4004 )
4005 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004006 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004007
4008 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004009 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004010 domain: Domain::SELINUX,
4011 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004012 alias: Some(TEST_ALIAS.to_string()),
4013 blob: None,
4014 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004015 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004016 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004017 |_, _| Ok(()),
4018 )
4019 .unwrap();
4020
4021 assert_eq!(
4022 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4023 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004024 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004025 domain: Domain::SELINUX,
4026 nspace: 1,
4027 alias: Some(TEST_ALIAS.to_string()),
4028 blob: None,
4029 },
4030 KeyType::Client,
4031 KeyEntryLoadBits::NONE,
4032 1,
4033 |_k, _av| Ok(()),
4034 )
4035 .unwrap_err()
4036 .root_cause()
4037 .downcast_ref::<KsError>()
4038 );
4039
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004040 Ok(())
4041 }
4042
4043 #[test]
4044 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4045 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004046 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004047 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4048 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004049 let (_, key_entry) = db
4050 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004051 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004052 KeyType::Client,
4053 KeyEntryLoadBits::BOTH,
4054 1,
4055 |_k, _av| Ok(()),
4056 )
4057 .unwrap();
4058
Qi Wub9433b52020-12-01 14:52:46 +08004059 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004060
4061 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004062 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004063 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004064 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004065 |_, _| Ok(()),
4066 )
4067 .unwrap();
4068
4069 assert_eq!(
4070 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4071 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004072 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004073 KeyType::Client,
4074 KeyEntryLoadBits::NONE,
4075 1,
4076 |_k, _av| Ok(()),
4077 )
4078 .unwrap_err()
4079 .root_cause()
4080 .downcast_ref::<KsError>()
4081 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004082
4083 Ok(())
4084 }
4085
4086 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004087 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4088 let mut db = new_test_db()?;
4089 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4090 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4091 .0;
4092 // Update the usage count of the limited use key.
4093 db.check_and_update_key_usage_count(key_id)?;
4094
4095 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004096 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004097 KeyType::Client,
4098 KeyEntryLoadBits::BOTH,
4099 1,
4100 |_k, _av| Ok(()),
4101 )?;
4102
4103 // The usage count is decremented now.
4104 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4105
4106 Ok(())
4107 }
4108
4109 #[test]
4110 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4111 let mut db = new_test_db()?;
4112 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4113 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4114 .0;
4115 // Update the usage count of the limited use key.
4116 db.check_and_update_key_usage_count(key_id).expect(concat!(
4117 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4118 "This should succeed."
4119 ));
4120
4121 // Try to update the exhausted limited use key.
4122 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4123 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4124 "This should fail."
4125 ));
4126 assert_eq!(
4127 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4128 e.root_cause().downcast_ref::<KsError>().unwrap()
4129 );
4130
4131 Ok(())
4132 }
4133
4134 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004135 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4136 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004137 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004138 .context("test_insert_and_load_full_keyentry_from_grant")?
4139 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004140
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004141 let granted_key = db
4142 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004143 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004144 domain: Domain::APP,
4145 nspace: 0,
4146 alias: Some(TEST_ALIAS.to_string()),
4147 blob: None,
4148 },
4149 1,
4150 2,
4151 key_perm_set![KeyPerm::use_()],
4152 |_k, _av| Ok(()),
4153 )
4154 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004155
4156 debug_dump_grant_table(&mut db)?;
4157
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004158 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004159 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4160 assert_eq!(Domain::GRANT, k.domain);
4161 assert!(av.unwrap().includes(KeyPerm::use_()));
4162 Ok(())
4163 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004164 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004165
Qi Wub9433b52020-12-01 14:52:46 +08004166 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004167
Janis Danisevskis66784c42021-01-27 08:40:25 -08004168 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004169
4170 assert_eq!(
4171 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4172 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004173 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004174 KeyType::Client,
4175 KeyEntryLoadBits::NONE,
4176 2,
4177 |_k, _av| Ok(()),
4178 )
4179 .unwrap_err()
4180 .root_cause()
4181 .downcast_ref::<KsError>()
4182 );
4183
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004184 Ok(())
4185 }
4186
Janis Danisevskis45760022021-01-19 16:34:10 -08004187 // This test attempts to load a key by key id while the caller is not the owner
4188 // but a grant exists for the given key and the caller.
4189 #[test]
4190 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4191 let mut db = new_test_db()?;
4192 const OWNER_UID: u32 = 1u32;
4193 const GRANTEE_UID: u32 = 2u32;
4194 const SOMEONE_ELSE_UID: u32 = 3u32;
4195 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4196 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4197 .0;
4198
4199 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004200 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004201 domain: Domain::APP,
4202 nspace: 0,
4203 alias: Some(TEST_ALIAS.to_string()),
4204 blob: None,
4205 },
4206 OWNER_UID,
4207 GRANTEE_UID,
4208 key_perm_set![KeyPerm::use_()],
4209 |_k, _av| Ok(()),
4210 )
4211 .unwrap();
4212
4213 debug_dump_grant_table(&mut db)?;
4214
4215 let id_descriptor =
4216 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4217
4218 let (_, key_entry) = db
4219 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004220 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004221 KeyType::Client,
4222 KeyEntryLoadBits::BOTH,
4223 GRANTEE_UID,
4224 |k, av| {
4225 assert_eq!(Domain::APP, k.domain);
4226 assert_eq!(OWNER_UID as i64, k.nspace);
4227 assert!(av.unwrap().includes(KeyPerm::use_()));
4228 Ok(())
4229 },
4230 )
4231 .unwrap();
4232
4233 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4234
4235 let (_, key_entry) = db
4236 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004237 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004238 KeyType::Client,
4239 KeyEntryLoadBits::BOTH,
4240 SOMEONE_ELSE_UID,
4241 |k, av| {
4242 assert_eq!(Domain::APP, k.domain);
4243 assert_eq!(OWNER_UID as i64, k.nspace);
4244 assert!(av.is_none());
4245 Ok(())
4246 },
4247 )
4248 .unwrap();
4249
4250 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4251
Janis Danisevskis66784c42021-01-27 08:40:25 -08004252 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004253
4254 assert_eq!(
4255 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4256 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004257 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004258 KeyType::Client,
4259 KeyEntryLoadBits::NONE,
4260 GRANTEE_UID,
4261 |_k, _av| Ok(()),
4262 )
4263 .unwrap_err()
4264 .root_cause()
4265 .downcast_ref::<KsError>()
4266 );
4267
4268 Ok(())
4269 }
4270
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004271 // Creates a key migrates it to a different location and then tries to access it by the old
4272 // and new location.
4273 #[test]
4274 fn test_migrate_key_app_to_app() -> Result<()> {
4275 let mut db = new_test_db()?;
4276 const SOURCE_UID: u32 = 1u32;
4277 const DESTINATION_UID: u32 = 2u32;
4278 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4279 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4280 let key_id_guard =
4281 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4282 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4283
4284 let source_descriptor: KeyDescriptor = KeyDescriptor {
4285 domain: Domain::APP,
4286 nspace: -1,
4287 alias: Some(SOURCE_ALIAS.to_string()),
4288 blob: None,
4289 };
4290
4291 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4292 domain: Domain::APP,
4293 nspace: -1,
4294 alias: Some(DESTINATION_ALIAS.to_string()),
4295 blob: None,
4296 };
4297
4298 let key_id = key_id_guard.id();
4299
4300 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4301 Ok(())
4302 })
4303 .unwrap();
4304
4305 let (_, key_entry) = db
4306 .load_key_entry(
4307 &destination_descriptor,
4308 KeyType::Client,
4309 KeyEntryLoadBits::BOTH,
4310 DESTINATION_UID,
4311 |k, av| {
4312 assert_eq!(Domain::APP, k.domain);
4313 assert_eq!(DESTINATION_UID as i64, k.nspace);
4314 assert!(av.is_none());
4315 Ok(())
4316 },
4317 )
4318 .unwrap();
4319
4320 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4321
4322 assert_eq!(
4323 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4324 db.load_key_entry(
4325 &source_descriptor,
4326 KeyType::Client,
4327 KeyEntryLoadBits::NONE,
4328 SOURCE_UID,
4329 |_k, _av| Ok(()),
4330 )
4331 .unwrap_err()
4332 .root_cause()
4333 .downcast_ref::<KsError>()
4334 );
4335
4336 Ok(())
4337 }
4338
4339 // Creates a key migrates it to a different location and then tries to access it by the old
4340 // and new location.
4341 #[test]
4342 fn test_migrate_key_app_to_selinux() -> Result<()> {
4343 let mut db = new_test_db()?;
4344 const SOURCE_UID: u32 = 1u32;
4345 const DESTINATION_UID: u32 = 2u32;
4346 const DESTINATION_NAMESPACE: i64 = 1000i64;
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::SELINUX,
4362 nspace: DESTINATION_NAMESPACE,
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::SELINUX, k.domain);
4382 assert_eq!(DESTINATION_NAMESPACE 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 two keys and tries to migrate the first to the location of the second which
4409 // is expected to fail.
4410 #[test]
4411 fn test_migrate_key_destination_occupied() -> Result<()> {
4412 let mut db = new_test_db()?;
4413 const SOURCE_UID: u32 = 1u32;
4414 const DESTINATION_UID: u32 = 2u32;
4415 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4416 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4417 let key_id_guard =
4418 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4419 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4420 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4421 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4422
4423 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4424 domain: Domain::APP,
4425 nspace: -1,
4426 alias: Some(DESTINATION_ALIAS.to_string()),
4427 blob: None,
4428 };
4429
4430 assert_eq!(
4431 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4432 db.migrate_key_namespace(
4433 key_id_guard,
4434 &destination_descriptor,
4435 DESTINATION_UID,
4436 |_k| Ok(())
4437 )
4438 .unwrap_err()
4439 .root_cause()
4440 .downcast_ref::<KsError>()
4441 );
4442
4443 Ok(())
4444 }
4445
Janis Danisevskisaec14592020-11-12 09:41:49 -08004446 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4447
Janis Danisevskisaec14592020-11-12 09:41:49 -08004448 #[test]
4449 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4450 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004451 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4452 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004453 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004454 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004455 .context("test_insert_and_load_full_keyentry_domain_app")?
4456 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004457 let (_key_guard, key_entry) = db
4458 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004459 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004460 domain: Domain::APP,
4461 nspace: 0,
4462 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4463 blob: None,
4464 },
4465 KeyType::Client,
4466 KeyEntryLoadBits::BOTH,
4467 33,
4468 |_k, _av| Ok(()),
4469 )
4470 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004471 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004472 let state = Arc::new(AtomicU8::new(1));
4473 let state2 = state.clone();
4474
4475 // Spawning a second thread that attempts to acquire the key id lock
4476 // for the same key as the primary thread. The primary thread then
4477 // waits, thereby forcing the secondary thread into the second stage
4478 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4479 // The test succeeds if the secondary thread observes the transition
4480 // of `state` from 1 to 2, despite having a whole second to overtake
4481 // the primary thread.
4482 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004483 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004484 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004485 assert!(db
4486 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004487 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004488 domain: Domain::APP,
4489 nspace: 0,
4490 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4491 blob: None,
4492 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004493 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004494 KeyEntryLoadBits::BOTH,
4495 33,
4496 |_k, _av| Ok(()),
4497 )
4498 .is_ok());
4499 // We should only see a 2 here because we can only return
4500 // from load_key_entry when the `_key_guard` expires,
4501 // which happens at the end of the scope.
4502 assert_eq!(2, state2.load(Ordering::Relaxed));
4503 });
4504
4505 thread::sleep(std::time::Duration::from_millis(1000));
4506
4507 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4508
4509 // Return the handle from this scope so we can join with the
4510 // secondary thread after the key id lock has expired.
4511 handle
4512 // This is where the `_key_guard` goes out of scope,
4513 // which is the reason for concurrent load_key_entry on the same key
4514 // to unblock.
4515 };
4516 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4517 // main test thread. We will not see failing asserts in secondary threads otherwise.
4518 handle.join().unwrap();
4519 Ok(())
4520 }
4521
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004522 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004523 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004524 let temp_dir =
4525 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4526
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004527 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4528 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004529
4530 let _tx1 = db1
4531 .conn
4532 .transaction_with_behavior(TransactionBehavior::Immediate)
4533 .expect("Failed to create first transaction.");
4534
4535 let error = db2
4536 .conn
4537 .transaction_with_behavior(TransactionBehavior::Immediate)
4538 .context("Transaction begin failed.")
4539 .expect_err("This should fail.");
4540 let root_cause = error.root_cause();
4541 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4542 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4543 {
4544 return;
4545 }
4546 panic!(
4547 "Unexpected error {:?} \n{:?} \n{:?}",
4548 error,
4549 root_cause,
4550 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4551 )
4552 }
4553
4554 #[cfg(disabled)]
4555 #[test]
4556 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4557 let temp_dir = Arc::new(
4558 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4559 .expect("Failed to create temp dir."),
4560 );
4561
4562 let test_begin = Instant::now();
4563
4564 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4565 const KEY_COUNT: u32 = 500u32;
4566 const OPEN_DB_COUNT: u32 = 50u32;
4567
4568 let mut actual_key_count = KEY_COUNT;
4569 // First insert KEY_COUNT keys.
4570 for count in 0..KEY_COUNT {
4571 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4572 actual_key_count = count;
4573 break;
4574 }
4575 let alias = format!("test_alias_{}", count);
4576 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4577 .expect("Failed to make key entry.");
4578 }
4579
4580 // Insert more keys from a different thread and into a different namespace.
4581 let temp_dir1 = temp_dir.clone();
4582 let handle1 = thread::spawn(move || {
4583 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4584
4585 for count in 0..actual_key_count {
4586 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4587 return;
4588 }
4589 let alias = format!("test_alias_{}", count);
4590 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4591 .expect("Failed to make key entry.");
4592 }
4593
4594 // then unbind them again.
4595 for count in 0..actual_key_count {
4596 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4597 return;
4598 }
4599 let key = KeyDescriptor {
4600 domain: Domain::APP,
4601 nspace: -1,
4602 alias: Some(format!("test_alias_{}", count)),
4603 blob: None,
4604 };
4605 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4606 }
4607 });
4608
4609 // And start unbinding the first set of keys.
4610 let temp_dir2 = temp_dir.clone();
4611 let handle2 = thread::spawn(move || {
4612 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4613
4614 for count in 0..actual_key_count {
4615 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4616 return;
4617 }
4618 let key = KeyDescriptor {
4619 domain: Domain::APP,
4620 nspace: -1,
4621 alias: Some(format!("test_alias_{}", count)),
4622 blob: None,
4623 };
4624 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4625 }
4626 });
4627
4628 let stop_deleting = Arc::new(AtomicU8::new(0));
4629 let stop_deleting2 = stop_deleting.clone();
4630
4631 // And delete anything that is unreferenced keys.
4632 let temp_dir3 = temp_dir.clone();
4633 let handle3 = thread::spawn(move || {
4634 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4635
4636 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4637 while let Some((key_guard, _key)) =
4638 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4639 {
4640 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4641 return;
4642 }
4643 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4644 }
4645 std::thread::sleep(std::time::Duration::from_millis(100));
4646 }
4647 });
4648
4649 // While a lot of inserting and deleting is going on we have to open database connections
4650 // successfully and use them.
4651 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4652 // out of scope.
4653 #[allow(clippy::redundant_clone)]
4654 let temp_dir4 = temp_dir.clone();
4655 let handle4 = thread::spawn(move || {
4656 for count in 0..OPEN_DB_COUNT {
4657 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4658 return;
4659 }
4660 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4661
4662 let alias = format!("test_alias_{}", count);
4663 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4664 .expect("Failed to make key entry.");
4665 let key = KeyDescriptor {
4666 domain: Domain::APP,
4667 nspace: -1,
4668 alias: Some(alias),
4669 blob: None,
4670 };
4671 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4672 }
4673 });
4674
4675 handle1.join().expect("Thread 1 panicked.");
4676 handle2.join().expect("Thread 2 panicked.");
4677 handle4.join().expect("Thread 4 panicked.");
4678
4679 stop_deleting.store(1, Ordering::Relaxed);
4680 handle3.join().expect("Thread 3 panicked.");
4681
4682 Ok(())
4683 }
4684
4685 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004686 fn list() -> Result<()> {
4687 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004688 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004689 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4690 (Domain::APP, 1, "test1"),
4691 (Domain::APP, 1, "test2"),
4692 (Domain::APP, 1, "test3"),
4693 (Domain::APP, 1, "test4"),
4694 (Domain::APP, 1, "test5"),
4695 (Domain::APP, 1, "test6"),
4696 (Domain::APP, 1, "test7"),
4697 (Domain::APP, 2, "test1"),
4698 (Domain::APP, 2, "test2"),
4699 (Domain::APP, 2, "test3"),
4700 (Domain::APP, 2, "test4"),
4701 (Domain::APP, 2, "test5"),
4702 (Domain::APP, 2, "test6"),
4703 (Domain::APP, 2, "test8"),
4704 (Domain::SELINUX, 100, "test1"),
4705 (Domain::SELINUX, 100, "test2"),
4706 (Domain::SELINUX, 100, "test3"),
4707 (Domain::SELINUX, 100, "test4"),
4708 (Domain::SELINUX, 100, "test5"),
4709 (Domain::SELINUX, 100, "test6"),
4710 (Domain::SELINUX, 100, "test9"),
4711 ];
4712
4713 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4714 .iter()
4715 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004716 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4717 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004718 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4719 });
4720 (entry.id(), *ns)
4721 })
4722 .collect();
4723
4724 for (domain, namespace) in
4725 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4726 {
4727 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4728 .iter()
4729 .filter_map(|(domain, ns, alias)| match ns {
4730 ns if *ns == *namespace => Some(KeyDescriptor {
4731 domain: *domain,
4732 nspace: *ns,
4733 alias: Some(alias.to_string()),
4734 blob: None,
4735 }),
4736 _ => None,
4737 })
4738 .collect();
4739 list_o_descriptors.sort();
4740 let mut list_result = db.list(*domain, *namespace)?;
4741 list_result.sort();
4742 assert_eq!(list_o_descriptors, list_result);
4743
4744 let mut list_o_ids: Vec<i64> = list_o_descriptors
4745 .into_iter()
4746 .map(|d| {
4747 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004748 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004749 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004750 KeyType::Client,
4751 KeyEntryLoadBits::NONE,
4752 *namespace as u32,
4753 |_, _| Ok(()),
4754 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004755 .unwrap();
4756 entry.id()
4757 })
4758 .collect();
4759 list_o_ids.sort_unstable();
4760 let mut loaded_entries: Vec<i64> = list_o_keys
4761 .iter()
4762 .filter_map(|(id, ns)| match ns {
4763 ns if *ns == *namespace => Some(*id),
4764 _ => None,
4765 })
4766 .collect();
4767 loaded_entries.sort_unstable();
4768 assert_eq!(list_o_ids, loaded_entries);
4769 }
4770 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4771
4772 Ok(())
4773 }
4774
Joel Galenson0891bc12020-07-20 10:37:03 -07004775 // Helpers
4776
4777 // Checks that the given result is an error containing the given string.
4778 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4779 let error_str = format!(
4780 "{:#?}",
4781 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4782 );
4783 assert!(
4784 error_str.contains(target),
4785 "The string \"{}\" should contain \"{}\"",
4786 error_str,
4787 target
4788 );
4789 }
4790
Joel Galenson2aab4432020-07-22 15:27:57 -07004791 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004792 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004793 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004794 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004795 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004796 namespace: Option<i64>,
4797 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004798 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004799 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004800 }
4801
4802 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4803 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004804 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004805 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004806 Ok(KeyEntryRow {
4807 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004808 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004809 domain: match row.get(2)? {
4810 Some(i) => Some(Domain(i)),
4811 None => None,
4812 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004813 namespace: row.get(3)?,
4814 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004815 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004816 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004817 })
4818 })?
4819 .map(|r| r.context("Could not read keyentry row."))
4820 .collect::<Result<Vec<_>>>()
4821 }
4822
Max Biresb2e1d032021-02-08 21:35:05 -08004823 struct RemoteProvValues {
4824 cert_chain: Vec<u8>,
4825 priv_key: Vec<u8>,
4826 batch_cert: Vec<u8>,
4827 }
4828
Max Bires2b2e6562020-09-22 11:22:36 -07004829 fn load_attestation_key_pool(
4830 db: &mut KeystoreDB,
4831 expiration_date: i64,
4832 namespace: i64,
4833 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004834 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004835 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4836 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4837 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4838 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004839 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004840 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4841 db.store_signed_attestation_certificate_chain(
4842 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004843 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004844 &cert_chain,
4845 expiration_date,
4846 &KEYSTORE_UUID,
4847 )?;
4848 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004849 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004850 }
4851
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004852 // Note: The parameters and SecurityLevel associations are nonsensical. This
4853 // collection is only used to check if the parameters are preserved as expected by the
4854 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004855 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4856 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004857 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4858 KeyParameter::new(
4859 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4860 SecurityLevel::TRUSTED_ENVIRONMENT,
4861 ),
4862 KeyParameter::new(
4863 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4864 SecurityLevel::TRUSTED_ENVIRONMENT,
4865 ),
4866 KeyParameter::new(
4867 KeyParameterValue::Algorithm(Algorithm::RSA),
4868 SecurityLevel::TRUSTED_ENVIRONMENT,
4869 ),
4870 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4871 KeyParameter::new(
4872 KeyParameterValue::BlockMode(BlockMode::ECB),
4873 SecurityLevel::TRUSTED_ENVIRONMENT,
4874 ),
4875 KeyParameter::new(
4876 KeyParameterValue::BlockMode(BlockMode::GCM),
4877 SecurityLevel::TRUSTED_ENVIRONMENT,
4878 ),
4879 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4880 KeyParameter::new(
4881 KeyParameterValue::Digest(Digest::MD5),
4882 SecurityLevel::TRUSTED_ENVIRONMENT,
4883 ),
4884 KeyParameter::new(
4885 KeyParameterValue::Digest(Digest::SHA_2_224),
4886 SecurityLevel::TRUSTED_ENVIRONMENT,
4887 ),
4888 KeyParameter::new(
4889 KeyParameterValue::Digest(Digest::SHA_2_256),
4890 SecurityLevel::STRONGBOX,
4891 ),
4892 KeyParameter::new(
4893 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4894 SecurityLevel::TRUSTED_ENVIRONMENT,
4895 ),
4896 KeyParameter::new(
4897 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4898 SecurityLevel::TRUSTED_ENVIRONMENT,
4899 ),
4900 KeyParameter::new(
4901 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4902 SecurityLevel::STRONGBOX,
4903 ),
4904 KeyParameter::new(
4905 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4906 SecurityLevel::TRUSTED_ENVIRONMENT,
4907 ),
4908 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4909 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4910 KeyParameter::new(
4911 KeyParameterValue::EcCurve(EcCurve::P_224),
4912 SecurityLevel::TRUSTED_ENVIRONMENT,
4913 ),
4914 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4915 KeyParameter::new(
4916 KeyParameterValue::EcCurve(EcCurve::P_384),
4917 SecurityLevel::TRUSTED_ENVIRONMENT,
4918 ),
4919 KeyParameter::new(
4920 KeyParameterValue::EcCurve(EcCurve::P_521),
4921 SecurityLevel::TRUSTED_ENVIRONMENT,
4922 ),
4923 KeyParameter::new(
4924 KeyParameterValue::RSAPublicExponent(3),
4925 SecurityLevel::TRUSTED_ENVIRONMENT,
4926 ),
4927 KeyParameter::new(
4928 KeyParameterValue::IncludeUniqueID,
4929 SecurityLevel::TRUSTED_ENVIRONMENT,
4930 ),
4931 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4932 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4933 KeyParameter::new(
4934 KeyParameterValue::ActiveDateTime(1234567890),
4935 SecurityLevel::STRONGBOX,
4936 ),
4937 KeyParameter::new(
4938 KeyParameterValue::OriginationExpireDateTime(1234567890),
4939 SecurityLevel::TRUSTED_ENVIRONMENT,
4940 ),
4941 KeyParameter::new(
4942 KeyParameterValue::UsageExpireDateTime(1234567890),
4943 SecurityLevel::TRUSTED_ENVIRONMENT,
4944 ),
4945 KeyParameter::new(
4946 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4947 SecurityLevel::TRUSTED_ENVIRONMENT,
4948 ),
4949 KeyParameter::new(
4950 KeyParameterValue::MaxUsesPerBoot(1234567890),
4951 SecurityLevel::TRUSTED_ENVIRONMENT,
4952 ),
4953 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4954 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4955 KeyParameter::new(
4956 KeyParameterValue::NoAuthRequired,
4957 SecurityLevel::TRUSTED_ENVIRONMENT,
4958 ),
4959 KeyParameter::new(
4960 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4961 SecurityLevel::TRUSTED_ENVIRONMENT,
4962 ),
4963 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4964 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4965 KeyParameter::new(
4966 KeyParameterValue::TrustedUserPresenceRequired,
4967 SecurityLevel::TRUSTED_ENVIRONMENT,
4968 ),
4969 KeyParameter::new(
4970 KeyParameterValue::TrustedConfirmationRequired,
4971 SecurityLevel::TRUSTED_ENVIRONMENT,
4972 ),
4973 KeyParameter::new(
4974 KeyParameterValue::UnlockedDeviceRequired,
4975 SecurityLevel::TRUSTED_ENVIRONMENT,
4976 ),
4977 KeyParameter::new(
4978 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4979 SecurityLevel::SOFTWARE,
4980 ),
4981 KeyParameter::new(
4982 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4983 SecurityLevel::SOFTWARE,
4984 ),
4985 KeyParameter::new(
4986 KeyParameterValue::CreationDateTime(12345677890),
4987 SecurityLevel::SOFTWARE,
4988 ),
4989 KeyParameter::new(
4990 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4991 SecurityLevel::TRUSTED_ENVIRONMENT,
4992 ),
4993 KeyParameter::new(
4994 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4995 SecurityLevel::TRUSTED_ENVIRONMENT,
4996 ),
4997 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4998 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4999 KeyParameter::new(
5000 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5001 SecurityLevel::SOFTWARE,
5002 ),
5003 KeyParameter::new(
5004 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5005 SecurityLevel::TRUSTED_ENVIRONMENT,
5006 ),
5007 KeyParameter::new(
5008 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5009 SecurityLevel::TRUSTED_ENVIRONMENT,
5010 ),
5011 KeyParameter::new(
5012 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5013 SecurityLevel::TRUSTED_ENVIRONMENT,
5014 ),
5015 KeyParameter::new(
5016 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5017 SecurityLevel::TRUSTED_ENVIRONMENT,
5018 ),
5019 KeyParameter::new(
5020 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5021 SecurityLevel::TRUSTED_ENVIRONMENT,
5022 ),
5023 KeyParameter::new(
5024 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5025 SecurityLevel::TRUSTED_ENVIRONMENT,
5026 ),
5027 KeyParameter::new(
5028 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5029 SecurityLevel::TRUSTED_ENVIRONMENT,
5030 ),
5031 KeyParameter::new(
5032 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5033 SecurityLevel::TRUSTED_ENVIRONMENT,
5034 ),
5035 KeyParameter::new(
5036 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5037 SecurityLevel::TRUSTED_ENVIRONMENT,
5038 ),
5039 KeyParameter::new(
5040 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5041 SecurityLevel::TRUSTED_ENVIRONMENT,
5042 ),
5043 KeyParameter::new(
5044 KeyParameterValue::VendorPatchLevel(3),
5045 SecurityLevel::TRUSTED_ENVIRONMENT,
5046 ),
5047 KeyParameter::new(
5048 KeyParameterValue::BootPatchLevel(4),
5049 SecurityLevel::TRUSTED_ENVIRONMENT,
5050 ),
5051 KeyParameter::new(
5052 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5053 SecurityLevel::TRUSTED_ENVIRONMENT,
5054 ),
5055 KeyParameter::new(
5056 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5057 SecurityLevel::TRUSTED_ENVIRONMENT,
5058 ),
5059 KeyParameter::new(
5060 KeyParameterValue::MacLength(256),
5061 SecurityLevel::TRUSTED_ENVIRONMENT,
5062 ),
5063 KeyParameter::new(
5064 KeyParameterValue::ResetSinceIdRotation,
5065 SecurityLevel::TRUSTED_ENVIRONMENT,
5066 ),
5067 KeyParameter::new(
5068 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5069 SecurityLevel::TRUSTED_ENVIRONMENT,
5070 ),
Qi Wub9433b52020-12-01 14:52:46 +08005071 ];
5072 if let Some(value) = max_usage_count {
5073 params.push(KeyParameter::new(
5074 KeyParameterValue::UsageCountLimit(value),
5075 SecurityLevel::SOFTWARE,
5076 ));
5077 }
5078 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005079 }
5080
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005081 fn make_test_key_entry(
5082 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005083 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005084 namespace: i64,
5085 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005086 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005087 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005088 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005089 let mut blob_metadata = BlobMetaData::new();
5090 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5091 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5092 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5093 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5094 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5095
5096 db.set_blob(
5097 &key_id,
5098 SubComponentType::KEY_BLOB,
5099 Some(TEST_KEY_BLOB),
5100 Some(&blob_metadata),
5101 )?;
5102 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5103 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005104
5105 let params = make_test_params(max_usage_count);
5106 db.insert_keyparameter(&key_id, &params)?;
5107
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005108 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005109 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005110 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005111 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005112 Ok(key_id)
5113 }
5114
Qi Wub9433b52020-12-01 14:52:46 +08005115 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5116 let params = make_test_params(max_usage_count);
5117
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005118 let mut blob_metadata = BlobMetaData::new();
5119 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5120 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5121 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5122 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5123 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5124
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005125 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005126 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005127
5128 KeyEntry {
5129 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005130 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005131 cert: Some(TEST_CERT_BLOB.to_vec()),
5132 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005133 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005134 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005135 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005136 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005137 }
5138 }
5139
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005140 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005141 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005142 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005143 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005144 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005145 NO_PARAMS,
5146 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005147 Ok((
5148 row.get(0)?,
5149 row.get(1)?,
5150 row.get(2)?,
5151 row.get(3)?,
5152 row.get(4)?,
5153 row.get(5)?,
5154 row.get(6)?,
5155 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005156 },
5157 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005158
5159 println!("Key entry table rows:");
5160 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005161 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005162 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005163 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5164 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005165 );
5166 }
5167 Ok(())
5168 }
5169
5170 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005171 let mut stmt = db
5172 .conn
5173 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005174 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5175 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5176 })?;
5177
5178 println!("Grant table rows:");
5179 for r in rows {
5180 let (id, gt, ki, av) = r.unwrap();
5181 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5182 }
5183 Ok(())
5184 }
5185
Joel Galenson0891bc12020-07-20 10:37:03 -07005186 // Use a custom random number generator that repeats each number once.
5187 // This allows us to test repeated elements.
5188
5189 thread_local! {
5190 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5191 }
5192
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005193 fn reset_random() {
5194 RANDOM_COUNTER.with(|counter| {
5195 *counter.borrow_mut() = 0;
5196 })
5197 }
5198
Joel Galenson0891bc12020-07-20 10:37:03 -07005199 pub fn random() -> i64 {
5200 RANDOM_COUNTER.with(|counter| {
5201 let result = *counter.borrow() / 2;
5202 *counter.borrow_mut() += 1;
5203 result
5204 })
5205 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005206
5207 #[test]
5208 fn test_last_off_body() -> Result<()> {
5209 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005210 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005211 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5212 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5213 tx.commit()?;
5214 let one_second = Duration::from_secs(1);
5215 thread::sleep(one_second);
5216 db.update_last_off_body(MonotonicRawTime::now())?;
5217 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5218 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5219 tx2.commit()?;
5220 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5221 Ok(())
5222 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005223
5224 #[test]
5225 fn test_unbind_keys_for_user() -> Result<()> {
5226 let mut db = new_test_db()?;
5227 db.unbind_keys_for_user(1, false)?;
5228
5229 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5230 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5231 db.unbind_keys_for_user(2, false)?;
5232
5233 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5234 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5235
5236 db.unbind_keys_for_user(1, true)?;
5237 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5238
5239 Ok(())
5240 }
5241
5242 #[test]
5243 fn test_store_super_key() -> Result<()> {
5244 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005245 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005246 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005247 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005248 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005249 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005250
5251 let (encrypted_super_key, metadata) =
5252 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005253 db.store_super_key(
5254 1,
5255 &USER_SUPER_KEY,
5256 &encrypted_super_key,
5257 &metadata,
5258 &KeyMetaData::new(),
5259 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005260
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005261 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005262 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005263
Paul Crowley7a658392021-03-18 17:08:20 -07005264 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005265 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5266 USER_SUPER_KEY.algorithm,
5267 key_entry,
5268 &pw,
5269 None,
5270 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005271
Paul Crowley7a658392021-03-18 17:08:20 -07005272 let decrypted_secret_bytes =
5273 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5274 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005275 Ok(())
5276 }
Seth Moore78c091f2021-04-09 21:38:30 +00005277
5278 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5279 vec![
5280 StatsdStorageType::KeyEntry,
5281 StatsdStorageType::KeyEntryIdIndex,
5282 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5283 StatsdStorageType::BlobEntry,
5284 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5285 StatsdStorageType::KeyParameter,
5286 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5287 StatsdStorageType::KeyMetadata,
5288 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5289 StatsdStorageType::Grant,
5290 StatsdStorageType::AuthToken,
5291 StatsdStorageType::BlobMetadata,
5292 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5293 ]
5294 }
5295
5296 /// Perform a simple check to ensure that we can query all the storage types
5297 /// that are supported by the DB. Check for reasonable values.
5298 #[test]
5299 fn test_query_all_valid_table_sizes() -> Result<()> {
5300 const PAGE_SIZE: i64 = 4096;
5301
5302 let mut db = new_test_db()?;
5303
5304 for t in get_valid_statsd_storage_types() {
5305 let stat = db.get_storage_stat(t)?;
5306 assert!(stat.size >= PAGE_SIZE);
5307 assert!(stat.size >= stat.unused_size);
5308 }
5309
5310 Ok(())
5311 }
5312
5313 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5314 get_valid_statsd_storage_types()
5315 .into_iter()
5316 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5317 .collect()
5318 }
5319
5320 fn assert_storage_increased(
5321 db: &mut KeystoreDB,
5322 increased_storage_types: Vec<StatsdStorageType>,
5323 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5324 ) {
5325 for storage in increased_storage_types {
5326 // Verify the expected storage increased.
5327 let new = db.get_storage_stat(storage).unwrap();
5328 let storage = storage as i32;
5329 let old = &baseline[&storage];
5330 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5331 assert!(
5332 new.unused_size <= old.unused_size,
5333 "{}: {} <= {}",
5334 storage,
5335 new.unused_size,
5336 old.unused_size
5337 );
5338
5339 // Update the baseline with the new value so that it succeeds in the
5340 // later comparison.
5341 baseline.insert(storage, new);
5342 }
5343
5344 // Get an updated map of the storage and verify there were no unexpected changes.
5345 let updated_stats = get_storage_stats_map(db);
5346 assert_eq!(updated_stats.len(), baseline.len());
5347
5348 for &k in baseline.keys() {
5349 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5350 let mut s = String::new();
5351 for &k in map.keys() {
5352 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5353 .expect("string concat failed");
5354 }
5355 s
5356 };
5357
5358 assert!(
5359 updated_stats[&k].size == baseline[&k].size
5360 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5361 "updated_stats:\n{}\nbaseline:\n{}",
5362 stringify(&updated_stats),
5363 stringify(&baseline)
5364 );
5365 }
5366 }
5367
5368 #[test]
5369 fn test_verify_key_table_size_reporting() -> Result<()> {
5370 let mut db = new_test_db()?;
5371 let mut working_stats = get_storage_stats_map(&mut db);
5372
5373 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5374 assert_storage_increased(
5375 &mut db,
5376 vec![
5377 StatsdStorageType::KeyEntry,
5378 StatsdStorageType::KeyEntryIdIndex,
5379 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5380 ],
5381 &mut working_stats,
5382 );
5383
5384 let mut blob_metadata = BlobMetaData::new();
5385 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5386 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5387 assert_storage_increased(
5388 &mut db,
5389 vec![
5390 StatsdStorageType::BlobEntry,
5391 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5392 StatsdStorageType::BlobMetadata,
5393 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5394 ],
5395 &mut working_stats,
5396 );
5397
5398 let params = make_test_params(None);
5399 db.insert_keyparameter(&key_id, &params)?;
5400 assert_storage_increased(
5401 &mut db,
5402 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5403 &mut working_stats,
5404 );
5405
5406 let mut metadata = KeyMetaData::new();
5407 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5408 db.insert_key_metadata(&key_id, &metadata)?;
5409 assert_storage_increased(
5410 &mut db,
5411 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5412 &mut working_stats,
5413 );
5414
5415 let mut sum = 0;
5416 for stat in working_stats.values() {
5417 sum += stat.size;
5418 }
5419 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5420 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5421
5422 Ok(())
5423 }
5424
5425 #[test]
5426 fn test_verify_auth_table_size_reporting() -> Result<()> {
5427 let mut db = new_test_db()?;
5428 let mut working_stats = get_storage_stats_map(&mut db);
5429 db.insert_auth_token(&HardwareAuthToken {
5430 challenge: 123,
5431 userId: 456,
5432 authenticatorId: 789,
5433 authenticatorType: kmhw_authenticator_type::ANY,
5434 timestamp: Timestamp { milliSeconds: 10 },
5435 mac: b"mac".to_vec(),
5436 })?;
5437 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5438 Ok(())
5439 }
5440
5441 #[test]
5442 fn test_verify_grant_table_size_reporting() -> Result<()> {
5443 const OWNER: i64 = 1;
5444 let mut db = new_test_db()?;
5445 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5446
5447 let mut working_stats = get_storage_stats_map(&mut db);
5448 db.grant(
5449 &KeyDescriptor {
5450 domain: Domain::APP,
5451 nspace: 0,
5452 alias: Some(TEST_ALIAS.to_string()),
5453 blob: None,
5454 },
5455 OWNER as u32,
5456 123,
5457 key_perm_set![KeyPerm::use_()],
5458 |_, _| Ok(()),
5459 )?;
5460
5461 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5462
5463 Ok(())
5464 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005465}