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