blob: 876f4cebb549f74ca586ca9d4ab7ca11865f0268 [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
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
45
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080047use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070048use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000049use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080050use crate::{
51 db_utils::{self, SqlField},
52 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070053 super_key::USER_SUPER_KEY,
54};
55use crate::{
56 error::{Error as KsError, ErrorCode, ResponseCode},
57 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080058};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080059use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080060use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070061
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080063 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080065};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070066use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070067 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070068};
Max Bires2b2e6562020-09-22 11:22:36 -070069use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
70 AttestationPoolStatus::AttestationPoolStatus,
71};
Seth Moore78c091f2021-04-09 21:38:30 +000072use statslog_rust::keystore2_storage_stats::{
73 Keystore2StorageStats, StorageType as StatsdStorageType,
74};
Max Bires2b2e6562020-09-22 11:22:36 -070075
76use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080077use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000078use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070079#[cfg(not(test))]
80use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070081use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080082 params,
83 types::FromSql,
84 types::FromSqlResult,
85 types::ToSqlOutput,
86 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080087 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070088};
Max Bires2b2e6562020-09-22 11:22:36 -070089
Janis Danisevskisaec14592020-11-12 09:41:49 -080090use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080091 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080092 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070093 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080095};
Max Bires2b2e6562020-09-22 11:22:36 -070096
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800100impl_metadata!(
101 /// A set of metadata for key entries.
102 #[derive(Debug, Default, Eq, PartialEq)]
103 pub struct KeyMetaData;
104 /// A metadata entry for key entries.
105 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
106 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800107 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800108 CreationDate(DateTime) with accessor creation_date,
109 /// Expiration date for attestation keys.
110 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700111 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
112 /// provisioning
113 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
114 /// Vector representing the raw public key so results from the server can be matched
115 /// to the right entry
116 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700117 /// SEC1 public key for ECDH encryption
118 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800119 // --- ADD NEW META DATA FIELDS HERE ---
120 // For backwards compatibility add new entries only to
121 // end of this list and above this comment.
122 };
123);
124
125impl KeyMetaData {
126 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
127 let mut stmt = tx
128 .prepare(
129 "SELECT tag, data from persistent.keymetadata
130 WHERE keyentryid = ?;",
131 )
132 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
133
134 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
135
136 let mut rows =
137 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
138 db_utils::with_rows_extract_all(&mut rows, |row| {
139 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
140 metadata.insert(
141 db_tag,
142 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
143 .context("Failed to read KeyMetaEntry.")?,
144 );
145 Ok(())
146 })
147 .context("In KeyMetaData::load_from_db.")?;
148
149 Ok(Self { data: metadata })
150 }
151
152 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
153 let mut stmt = tx
154 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000155 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800156 VALUES (?, ?, ?);",
157 )
158 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
159
160 let iter = self.data.iter();
161 for (tag, entry) in iter {
162 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
163 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
164 })?;
165 }
166 Ok(())
167 }
168}
169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170impl_metadata!(
171 /// A set of metadata for key blobs.
172 #[derive(Debug, Default, Eq, PartialEq)]
173 pub struct BlobMetaData;
174 /// A metadata entry for key blobs.
175 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
176 pub enum BlobMetaEntry {
177 /// If present, indicates that the blob is encrypted with another key or a key derived
178 /// from a password.
179 EncryptedBy(EncryptedBy) with accessor encrypted_by,
180 /// If the blob is password encrypted this field is set to the
181 /// salt used for the key derivation.
182 Salt(Vec<u8>) with accessor salt,
183 /// If the blob is encrypted, this field is set to the initialization vector.
184 Iv(Vec<u8>) with accessor iv,
185 /// If the blob is encrypted, this field holds the AEAD TAG.
186 AeadTag(Vec<u8>) with accessor aead_tag,
187 /// The uuid of the owning KeyMint instance.
188 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700189 /// If the key is ECDH encrypted, this is the ephemeral public key
190 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000191 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
192 /// of that key
193 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800194 // --- ADD NEW META DATA FIELDS HERE ---
195 // For backwards compatibility add new entries only to
196 // end of this list and above this comment.
197 };
198);
199
200impl BlobMetaData {
201 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
202 let mut stmt = tx
203 .prepare(
204 "SELECT tag, data from persistent.blobmetadata
205 WHERE blobentryid = ?;",
206 )
207 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
208
209 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
210
211 let mut rows =
212 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
213 db_utils::with_rows_extract_all(&mut rows, |row| {
214 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
215 metadata.insert(
216 db_tag,
217 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
218 .context("Failed to read BlobMetaEntry.")?,
219 );
220 Ok(())
221 })
222 .context("In BlobMetaData::load_from_db.")?;
223
224 Ok(Self { data: metadata })
225 }
226
227 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
228 let mut stmt = tx
229 .prepare(
230 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
231 VALUES (?, ?, ?);",
232 )
233 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
234
235 let iter = self.data.iter();
236 for (tag, entry) in iter {
237 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
238 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
239 })?;
240 }
241 Ok(())
242 }
243}
244
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800245/// Indicates the type of the keyentry.
246#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
247pub enum KeyType {
248 /// This is a client key type. These keys are created or imported through the Keystore 2.0
249 /// AIDL interface android.system.keystore2.
250 Client,
251 /// This is a super key type. These keys are created by keystore itself and used to encrypt
252 /// other key blobs to provide LSKF binding.
253 Super,
254 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
255 Attestation,
256}
257
258impl ToSql for KeyType {
259 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
260 Ok(ToSqlOutput::Owned(Value::Integer(match self {
261 KeyType::Client => 0,
262 KeyType::Super => 1,
263 KeyType::Attestation => 2,
264 })))
265 }
266}
267
268impl FromSql for KeyType {
269 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
270 match i64::column_result(value)? {
271 0 => Ok(KeyType::Client),
272 1 => Ok(KeyType::Super),
273 2 => Ok(KeyType::Attestation),
274 v => Err(FromSqlError::OutOfRange(v)),
275 }
276 }
277}
278
Max Bires8e93d2b2021-01-14 13:17:59 -0800279/// Uuid representation that can be stored in the database.
280/// Right now it can only be initialized from SecurityLevel.
281/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
282#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
283pub struct Uuid([u8; 16]);
284
285impl Deref for Uuid {
286 type Target = [u8; 16];
287
288 fn deref(&self) -> &Self::Target {
289 &self.0
290 }
291}
292
293impl From<SecurityLevel> for Uuid {
294 fn from(sec_level: SecurityLevel) -> Self {
295 Self((sec_level.0 as u128).to_be_bytes())
296 }
297}
298
299impl ToSql for Uuid {
300 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
301 self.0.to_sql()
302 }
303}
304
305impl FromSql for Uuid {
306 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
307 let blob = Vec::<u8>::column_result(value)?;
308 if blob.len() != 16 {
309 return Err(FromSqlError::OutOfRange(blob.len() as i64));
310 }
311 let mut arr = [0u8; 16];
312 arr.copy_from_slice(&blob);
313 Ok(Self(arr))
314 }
315}
316
317/// Key entries that are not associated with any KeyMint instance, such as pure certificate
318/// entries are associated with this UUID.
319pub static KEYSTORE_UUID: Uuid = Uuid([
320 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
321]);
322
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800323/// Indicates how the sensitive part of this key blob is encrypted.
324#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
325pub enum EncryptedBy {
326 /// The keyblob is encrypted by a user password.
327 /// In the database this variant is represented as NULL.
328 Password,
329 /// The keyblob is encrypted by another key with wrapped key id.
330 /// In the database this variant is represented as non NULL value
331 /// that is convertible to i64, typically NUMERIC.
332 KeyId(i64),
333}
334
335impl ToSql for EncryptedBy {
336 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
337 match self {
338 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
339 Self::KeyId(id) => id.to_sql(),
340 }
341 }
342}
343
344impl FromSql for EncryptedBy {
345 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
346 match value {
347 ValueRef::Null => Ok(Self::Password),
348 _ => Ok(Self::KeyId(i64::column_result(value)?)),
349 }
350 }
351}
352
353/// A database representation of wall clock time. DateTime stores unix epoch time as
354/// i64 in milliseconds.
355#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
356pub struct DateTime(i64);
357
358/// Error type returned when creating DateTime or converting it from and to
359/// SystemTime.
360#[derive(thiserror::Error, Debug)]
361pub enum DateTimeError {
362 /// This is returned when SystemTime and Duration computations fail.
363 #[error(transparent)]
364 SystemTimeError(#[from] SystemTimeError),
365
366 /// This is returned when type conversions fail.
367 #[error(transparent)]
368 TypeConversion(#[from] std::num::TryFromIntError),
369
370 /// This is returned when checked time arithmetic failed.
371 #[error("Time arithmetic failed.")]
372 TimeArithmetic,
373}
374
375impl DateTime {
376 /// Constructs a new DateTime object denoting the current time. This may fail during
377 /// conversion to unix epoch time and during conversion to the internal i64 representation.
378 pub fn now() -> Result<Self, DateTimeError> {
379 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
380 }
381
382 /// Constructs a new DateTime object from milliseconds.
383 pub fn from_millis_epoch(millis: i64) -> Self {
384 Self(millis)
385 }
386
387 /// Returns unix epoch time in milliseconds.
388 pub fn to_millis_epoch(&self) -> i64 {
389 self.0
390 }
391
392 /// Returns unix epoch time in seconds.
393 pub fn to_secs_epoch(&self) -> i64 {
394 self.0 / 1000
395 }
396}
397
398impl ToSql for DateTime {
399 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
400 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
401 }
402}
403
404impl FromSql for DateTime {
405 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
406 Ok(Self(i64::column_result(value)?))
407 }
408}
409
410impl TryInto<SystemTime> for DateTime {
411 type Error = DateTimeError;
412
413 fn try_into(self) -> Result<SystemTime, Self::Error> {
414 // We want to construct a SystemTime representation equivalent to self, denoting
415 // a point in time THEN, but we cannot set the time directly. We can only construct
416 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
417 // and between EPOCH and THEN. With this common reference we can construct the
418 // duration between NOW and THEN which we can add to our SystemTime representation
419 // of NOW to get a SystemTime representation of THEN.
420 // Durations can only be positive, thus the if statement below.
421 let now = SystemTime::now();
422 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
423 let then_epoch = Duration::from_millis(self.0.try_into()?);
424 Ok(if now_epoch > then_epoch {
425 // then = now - (now_epoch - then_epoch)
426 now_epoch
427 .checked_sub(then_epoch)
428 .and_then(|d| now.checked_sub(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 } else {
431 // then = now + (then_epoch - now_epoch)
432 then_epoch
433 .checked_sub(now_epoch)
434 .and_then(|d| now.checked_add(d))
435 .ok_or(DateTimeError::TimeArithmetic)?
436 })
437 }
438}
439
440impl TryFrom<SystemTime> for DateTime {
441 type Error = DateTimeError;
442
443 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
444 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
445 }
446}
447
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800448#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
449enum KeyLifeCycle {
450 /// Existing keys have a key ID but are not fully populated yet.
451 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
452 /// them to Unreferenced for garbage collection.
453 Existing,
454 /// A live key is fully populated and usable by clients.
455 Live,
456 /// An unreferenced key is scheduled for garbage collection.
457 Unreferenced,
458}
459
460impl ToSql for KeyLifeCycle {
461 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
462 match self {
463 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
464 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
465 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
466 }
467 }
468}
469
470impl FromSql for KeyLifeCycle {
471 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
472 match i64::column_result(value)? {
473 0 => Ok(KeyLifeCycle::Existing),
474 1 => Ok(KeyLifeCycle::Live),
475 2 => Ok(KeyLifeCycle::Unreferenced),
476 v => Err(FromSqlError::OutOfRange(v)),
477 }
478 }
479}
480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700481/// Keys have a KeyMint blob component and optional public certificate and
482/// certificate chain components.
483/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
484/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800485#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700486pub struct KeyEntryLoadBits(u32);
487
488impl KeyEntryLoadBits {
489 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
490 pub const NONE: KeyEntryLoadBits = Self(0);
491 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
492 pub const KM: KeyEntryLoadBits = Self(1);
493 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
494 pub const PUBLIC: KeyEntryLoadBits = Self(2);
495 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
496 pub const BOTH: KeyEntryLoadBits = Self(3);
497
498 /// Returns true if this object indicates that the public components shall be loaded.
499 pub const fn load_public(&self) -> bool {
500 self.0 & Self::PUBLIC.0 != 0
501 }
502
503 /// Returns true if the object indicates that the KeyMint component shall be loaded.
504 pub const fn load_km(&self) -> bool {
505 self.0 & Self::KM.0 != 0
506 }
507}
508
Janis Danisevskisaec14592020-11-12 09:41:49 -0800509lazy_static! {
510 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
511}
512
513struct KeyIdLockDb {
514 locked_keys: Mutex<HashSet<i64>>,
515 cond_var: Condvar,
516}
517
518/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
519/// from the database a second time. Most functions manipulating the key blob database
520/// require a KeyIdGuard.
521#[derive(Debug)]
522pub struct KeyIdGuard(i64);
523
524impl KeyIdLockDb {
525 fn new() -> Self {
526 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
527 }
528
529 /// This function blocks until an exclusive lock for the given key entry id can
530 /// be acquired. It returns a guard object, that represents the lifecycle of the
531 /// acquired lock.
532 pub fn get(&self, key_id: i64) -> KeyIdGuard {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 while locked_keys.contains(&key_id) {
535 locked_keys = self.cond_var.wait(locked_keys).unwrap();
536 }
537 locked_keys.insert(key_id);
538 KeyIdGuard(key_id)
539 }
540
541 /// This function attempts to acquire an exclusive lock on a given key id. If the
542 /// given key id is already taken the function returns None immediately. If a lock
543 /// can be acquired this function returns a guard object, that represents the
544 /// lifecycle of the acquired lock.
545 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
546 let mut locked_keys = self.locked_keys.lock().unwrap();
547 if locked_keys.insert(key_id) {
548 Some(KeyIdGuard(key_id))
549 } else {
550 None
551 }
552 }
553}
554
555impl KeyIdGuard {
556 /// Get the numeric key id of the locked key.
557 pub fn id(&self) -> i64 {
558 self.0
559 }
560}
561
562impl Drop for KeyIdGuard {
563 fn drop(&mut self) {
564 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
565 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800566 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800567 KEY_ID_LOCK.cond_var.notify_all();
568 }
569}
570
Max Bires8e93d2b2021-01-14 13:17:59 -0800571/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700572#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800573pub struct CertificateInfo {
574 cert: Option<Vec<u8>>,
575 cert_chain: Option<Vec<u8>>,
576}
577
578impl CertificateInfo {
579 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
580 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
581 Self { cert, cert_chain }
582 }
583
584 /// Take the cert
585 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
586 self.cert.take()
587 }
588
589 /// Take the cert chain
590 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
591 self.cert_chain.take()
592 }
593}
594
Max Bires2b2e6562020-09-22 11:22:36 -0700595/// This type represents a certificate chain with a private key corresponding to the leaf
596/// 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 -0700597pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800598 /// A KM key blob
599 pub private_key: ZVec,
600 /// A batch cert for private_key
601 pub batch_cert: Vec<u8>,
602 /// A full certificate chain from root signing authority to private_key, including batch_cert
603 /// for convenience.
604 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700605}
606
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700607/// This type represents a Keystore 2.0 key entry.
608/// An entry has a unique `id` by which it can be found in the database.
609/// It has a security level field, key parameters, and three optional fields
610/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800611#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700612pub struct KeyEntry {
613 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800614 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615 cert: Option<Vec<u8>>,
616 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800617 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700618 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800619 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800620 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700621}
622
623impl KeyEntry {
624 /// Returns the unique id of the Key entry.
625 pub fn id(&self) -> i64 {
626 self.id
627 }
628 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800629 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
630 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 /// Extracts the Optional KeyMint blob including its metadata.
633 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
634 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700635 }
636 /// Exposes the optional public certificate.
637 pub fn cert(&self) -> &Option<Vec<u8>> {
638 &self.cert
639 }
640 /// Extracts the optional public certificate.
641 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
642 self.cert.take()
643 }
644 /// Exposes the optional public certificate chain.
645 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
646 &self.cert_chain
647 }
648 /// Extracts the optional public certificate_chain.
649 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
650 self.cert_chain.take()
651 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800652 /// Returns the uuid of the owning KeyMint instance.
653 pub fn km_uuid(&self) -> &Uuid {
654 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700656 /// Exposes the key parameters of this key entry.
657 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
658 &self.parameters
659 }
660 /// Consumes this key entry and extracts the keyparameters from it.
661 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
662 self.parameters
663 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800664 /// Exposes the key metadata of this key entry.
665 pub fn metadata(&self) -> &KeyMetaData {
666 &self.metadata
667 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800668 /// This returns true if the entry is a pure certificate entry with no
669 /// private key component.
670 pub fn pure_cert(&self) -> bool {
671 self.pure_cert
672 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000673 /// Consumes this key entry and extracts the keyparameters and metadata from it.
674 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
675 (self.parameters, self.metadata)
676 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700677}
678
679/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800680#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681pub struct SubComponentType(u32);
682impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800683 /// Persistent identifier for a key blob.
684 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700685 /// Persistent identifier for a certificate blob.
686 pub const CERT: SubComponentType = Self(1);
687 /// Persistent identifier for a certificate chain blob.
688 pub const CERT_CHAIN: SubComponentType = Self(2);
689}
690
691impl ToSql for SubComponentType {
692 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
693 self.0.to_sql()
694 }
695}
696
697impl FromSql for SubComponentType {
698 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
699 Ok(Self(u32::column_result(value)?))
700 }
701}
702
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800703/// This trait is private to the database module. It is used to convey whether or not the garbage
704/// collector shall be invoked after a database access. All closures passed to
705/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
706/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
707/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
708/// `.need_gc()`.
709trait DoGc<T> {
710 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
711
712 fn no_gc(self) -> Result<(bool, T)>;
713
714 fn need_gc(self) -> Result<(bool, T)>;
715}
716
717impl<T> DoGc<T> for Result<T> {
718 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
719 self.map(|r| (need_gc, r))
720 }
721
722 fn no_gc(self) -> Result<(bool, T)> {
723 self.do_gc(false)
724 }
725
726 fn need_gc(self) -> Result<(bool, T)> {
727 self.do_gc(true)
728 }
729}
730
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700731/// KeystoreDB wraps a connection to an SQLite database and tracks its
732/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700733pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700734 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700735 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700736 perboot: Arc<perboot::PerbootDB>,
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
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000741#[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 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000747 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000748 }
749
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000750 /// Returns the value of MonotonicRawTime in milliseconds as i64
751 pub fn milliseconds(&self) -> i64 {
752 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000757 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000758 }
759
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800760 /// Like i64::checked_sub.
761 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
762 self.0.checked_sub(other.0).map(Self)
763 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000764}
765
766impl ToSql for MonotonicRawTime {
767 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
768 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
769 }
770}
771
772impl FromSql for MonotonicRawTime {
773 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
774 Ok(Self(i64::column_result(value)?))
775 }
776}
777
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000778/// This struct encapsulates the information to be stored in the database about the auth tokens
779/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700780#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000781pub struct AuthTokenEntry {
782 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000783 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000784 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000785}
786
787impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000789 AuthTokenEntry { auth_token, time_received }
790 }
791
792 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800793 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000794 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800795 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
796 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 })
798 }
799
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800801 pub fn auth_token(&self) -> &HardwareAuthToken {
802 &self.auth_token
803 }
804
805 /// Returns the auth token wrapped by the AuthTokenEntry
806 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000807 self.auth_token
808 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800809
810 /// Returns the time that this auth token was received.
811 pub fn time_received(&self) -> MonotonicRawTime {
812 self.time_received
813 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000814
815 /// Returns the challenge value of the auth token.
816 pub fn challenge(&self) -> i64 {
817 self.auth_token.challenge
818 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000819}
820
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800821/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
822/// This object does not allow access to the database connection. But it keeps a database
823/// connection alive in order to keep the in memory per boot database alive.
824pub struct PerBootDbKeepAlive(Connection);
825
Joel Galenson26f4d012020-07-17 14:57:21 -0700826impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800827 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800828
Seth Moore78c091f2021-04-09 21:38:30 +0000829 /// Name of the file that holds the cross-boot persistent database.
830 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
831
Seth Moore472fcbb2021-05-12 10:07:51 -0700832 /// Set write-ahead logging mode on the persistent database found in `db_root`.
833 pub fn set_wal_mode(db_root: &Path) -> Result<()> {
834 let path = Self::make_persistent_path(&db_root)?;
835 let conn =
836 Connection::open(path).context("In KeystoreDB::set_wal_mode: Failed to open DB")?;
837 let mode: String = conn
838 .pragma_update_and_check(None, "journal_mode", &"WAL", |row| row.get(0))
839 .context("In KeystoreDB::set_wal_mode: Failed to set journal_mode")?;
840 match mode.as_str() {
841 "wal" => Ok(()),
842 _ => Err(anyhow!("Unable to set WAL mode, db is still in {} mode.", mode)),
843 }
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
Seth Moore472fcbb2021-05-12 10:07:51 -0700854 let persistent_path = Self::make_persistent_path(&db_root)?;
855 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800856
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700857 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800858 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800859 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800860 })?;
861 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700862 }
863
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 fn init_tables(tx: &Transaction) -> Result<()> {
865 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700866 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700867 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800868 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700869 domain INTEGER,
870 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800871 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800872 state INTEGER,
873 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700874 NO_PARAMS,
875 )
876 .context("Failed to initialize \"keyentry\" table.")?;
877
Janis Danisevskis66784c42021-01-27 08:40:25 -0800878 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800879 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
880 ON keyentry(id);",
881 NO_PARAMS,
882 )
883 .context("Failed to create index keyentry_id_index.")?;
884
885 tx.execute(
886 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
887 ON keyentry(domain, namespace, alias);",
888 NO_PARAMS,
889 )
890 .context("Failed to create index keyentry_domain_namespace_index.")?;
891
892 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700893 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
894 id INTEGER PRIMARY KEY,
895 subcomponent_type INTEGER,
896 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800897 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700898 NO_PARAMS,
899 )
900 .context("Failed to initialize \"blobentry\" table.")?;
901
Janis Danisevskis66784c42021-01-27 08:40:25 -0800902 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800903 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
904 ON blobentry(keyentryid);",
905 NO_PARAMS,
906 )
907 .context("Failed to create index blobentry_keyentryid_index.")?;
908
909 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800910 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
911 id INTEGER PRIMARY KEY,
912 blobentryid INTEGER,
913 tag INTEGER,
914 data ANY,
915 UNIQUE (blobentryid, tag));",
916 NO_PARAMS,
917 )
918 .context("Failed to initialize \"blobmetadata\" table.")?;
919
920 tx.execute(
921 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
922 ON blobmetadata(blobentryid);",
923 NO_PARAMS,
924 )
925 .context("Failed to create index blobmetadata_blobentryid_index.")?;
926
927 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700928 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000929 keyentryid INTEGER,
930 tag INTEGER,
931 data ANY,
932 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700933 NO_PARAMS,
934 )
935 .context("Failed to initialize \"keyparameter\" table.")?;
936
Janis Danisevskis66784c42021-01-27 08:40:25 -0800937 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800938 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
939 ON keyparameter(keyentryid);",
940 NO_PARAMS,
941 )
942 .context("Failed to create index keyparameter_keyentryid_index.")?;
943
944 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800945 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
946 keyentryid INTEGER,
947 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000948 data ANY,
949 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800950 NO_PARAMS,
951 )
952 .context("Failed to initialize \"keymetadata\" table.")?;
953
Janis Danisevskis66784c42021-01-27 08:40:25 -0800954 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800955 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
956 ON keymetadata(keyentryid);",
957 NO_PARAMS,
958 )
959 .context("Failed to create index keymetadata_keyentryid_index.")?;
960
961 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800962 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700963 id INTEGER UNIQUE,
964 grantee INTEGER,
965 keyentryid INTEGER,
966 access_vector INTEGER);",
967 NO_PARAMS,
968 )
969 .context("Failed to initialize \"grant\" table.")?;
970
Joel Galenson0891bc12020-07-20 10:37:03 -0700971 Ok(())
972 }
973
Seth Moore472fcbb2021-05-12 10:07:51 -0700974 fn make_persistent_path(db_root: &Path) -> Result<String> {
975 // Build the path to the sqlite file.
976 let mut persistent_path = db_root.to_path_buf();
977 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
978
979 // Now convert them to strings prefixed with "file:"
980 let mut persistent_path_str = "file:".to_owned();
981 persistent_path_str.push_str(&persistent_path.to_string_lossy());
982
983 Ok(persistent_path_str)
984 }
985
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700986 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700987 let conn =
988 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
989
Janis Danisevskis66784c42021-01-27 08:40:25 -0800990 loop {
991 if let Err(e) = conn
992 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
993 .context("Failed to attach database persistent.")
994 {
995 if Self::is_locked_error(&e) {
996 std::thread::sleep(std::time::Duration::from_micros(500));
997 continue;
998 } else {
999 return Err(e);
1000 }
1001 }
1002 break;
1003 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001004
Matthew Maurer4fb19112021-05-06 15:40:44 -07001005 // Drop the cache size from default (2M) to 0.5M
1006 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1007 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001008
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001009 Ok(conn)
1010 }
1011
Seth Moore78c091f2021-04-09 21:38:30 +00001012 fn do_table_size_query(
1013 &mut self,
1014 storage_type: StatsdStorageType,
1015 query: &str,
1016 params: &[&str],
1017 ) -> Result<Keystore2StorageStats> {
1018 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1019 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1020 .with_context(|| {
1021 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1022 })
1023 .no_gc()
1024 })?;
1025 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1026 }
1027
1028 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1029 self.do_table_size_query(
1030 StatsdStorageType::Database,
1031 "SELECT page_count * page_size, freelist_count * page_size
1032 FROM pragma_page_count('persistent'),
1033 pragma_page_size('persistent'),
1034 persistent.pragma_freelist_count();",
1035 &[],
1036 )
1037 }
1038
1039 fn get_table_size(
1040 &mut self,
1041 storage_type: StatsdStorageType,
1042 schema: &str,
1043 table: &str,
1044 ) -> Result<Keystore2StorageStats> {
1045 self.do_table_size_query(
1046 storage_type,
1047 "SELECT pgsize,unused FROM dbstat(?1)
1048 WHERE name=?2 AND aggregate=TRUE;",
1049 &[schema, table],
1050 )
1051 }
1052
1053 /// Fetches a storage statisitics atom for a given storage type. For storage
1054 /// types that map to a table, information about the table's storage is
1055 /// returned. Requests for storage types that are not DB tables return None.
1056 pub fn get_storage_stat(
1057 &mut self,
1058 storage_type: StatsdStorageType,
1059 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001060 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1061
Seth Moore78c091f2021-04-09 21:38:30 +00001062 match storage_type {
1063 StatsdStorageType::Database => self.get_total_size(),
1064 StatsdStorageType::KeyEntry => {
1065 self.get_table_size(storage_type, "persistent", "keyentry")
1066 }
1067 StatsdStorageType::KeyEntryIdIndex => {
1068 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1069 }
1070 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1071 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1072 }
1073 StatsdStorageType::BlobEntry => {
1074 self.get_table_size(storage_type, "persistent", "blobentry")
1075 }
1076 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1077 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1078 }
1079 StatsdStorageType::KeyParameter => {
1080 self.get_table_size(storage_type, "persistent", "keyparameter")
1081 }
1082 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1083 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1084 }
1085 StatsdStorageType::KeyMetadata => {
1086 self.get_table_size(storage_type, "persistent", "keymetadata")
1087 }
1088 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1089 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1090 }
1091 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1092 StatsdStorageType::AuthToken => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001093 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1094 // reportable
1095 // Size provided is only an approximation
1096 Ok(Keystore2StorageStats {
1097 storage_type,
1098 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1099 as i64,
1100 unused_size: 0,
1101 })
Seth Moore78c091f2021-04-09 21:38:30 +00001102 }
1103 StatsdStorageType::BlobMetadata => {
1104 self.get_table_size(storage_type, "persistent", "blobmetadata")
1105 }
1106 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1107 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1108 }
1109 _ => Err(anyhow::Error::msg(format!(
1110 "Unsupported storage type: {}",
1111 storage_type as i32
1112 ))),
1113 }
1114 }
1115
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001116 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001117 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1118 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001119 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1120 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001121 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001122 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001123 blob_ids_to_delete: &[i64],
1124 max_blobs: usize,
1125 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001126 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001127 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001128 // Delete the given blobs.
1129 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001130 tx.execute(
1131 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001132 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001133 )
1134 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001135 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1136 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001137 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001138
1139 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1140
Janis Danisevskis3395f862021-05-06 10:54:17 -07001141 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1142 let result: Vec<(i64, Vec<u8>)> = {
1143 let mut stmt = tx
1144 .prepare(
1145 "SELECT id, blob FROM persistent.blobentry
1146 WHERE subcomponent_type = ?
1147 AND (
1148 id NOT IN (
1149 SELECT MAX(id) FROM persistent.blobentry
1150 WHERE subcomponent_type = ?
1151 GROUP BY keyentryid, subcomponent_type
1152 )
1153 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1154 ) LIMIT ?;",
1155 )
1156 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001157
Janis Danisevskis3395f862021-05-06 10:54:17 -07001158 let rows = stmt
1159 .query_map(
1160 params![
1161 SubComponentType::KEY_BLOB,
1162 SubComponentType::KEY_BLOB,
1163 max_blobs as i64,
1164 ],
1165 |row| Ok((row.get(0)?, row.get(1)?)),
1166 )
1167 .context("Trying to query superseded blob.")?;
1168
1169 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1170 .context("Trying to extract superseded blobs.")?
1171 };
1172
1173 let result = result
1174 .into_iter()
1175 .map(|(blob_id, blob)| {
1176 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1177 })
1178 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1179 .context("Trying to load blob metadata.")?;
1180 if !result.is_empty() {
1181 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001182 }
1183
1184 // We did not find any superseded key blob, so let's remove other superseded blob in
1185 // one transaction.
1186 tx.execute(
1187 "DELETE FROM persistent.blobentry
1188 WHERE NOT subcomponent_type = ?
1189 AND (
1190 id NOT IN (
1191 SELECT MAX(id) FROM persistent.blobentry
1192 WHERE NOT subcomponent_type = ?
1193 GROUP BY keyentryid, subcomponent_type
1194 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1195 );",
1196 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1197 )
1198 .context("Trying to purge superseded blobs.")?;
1199
Janis Danisevskis3395f862021-05-06 10:54:17 -07001200 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001201 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001202 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001203 }
1204
1205 /// This maintenance function should be called only once before the database is used for the
1206 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1207 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1208 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1209 /// Keystore crashed at some point during key generation. Callers may want to log such
1210 /// occurrences.
1211 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1212 /// it to `KeyLifeCycle::Live` may have grants.
1213 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001214 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1215
Janis Danisevskis66784c42021-01-27 08:40:25 -08001216 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1217 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001218 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1219 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1220 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001221 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001222 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001223 })
1224 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001225 }
1226
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001227 /// Checks if a key exists with given key type and key descriptor properties.
1228 pub fn key_exists(
1229 &mut self,
1230 domain: Domain,
1231 nspace: i64,
1232 alias: &str,
1233 key_type: KeyType,
1234 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001235 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1236
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001237 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1238 let key_descriptor =
1239 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1240 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1241 match result {
1242 Ok(_) => Ok(true),
1243 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1244 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1245 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1246 },
1247 }
1248 .no_gc()
1249 })
1250 .context("In key_exists.")
1251 }
1252
Hasini Gunasingheda895552021-01-27 19:34:37 +00001253 /// Stores a super key in the database.
1254 pub fn store_super_key(
1255 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001256 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001257 key_type: &SuperKeyType,
1258 blob: &[u8],
1259 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001260 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001261 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001262 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1263
Hasini Gunasingheda895552021-01-27 19:34:37 +00001264 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1265 let key_id = Self::insert_with_retry(|id| {
1266 tx.execute(
1267 "INSERT into persistent.keyentry
1268 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001269 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001270 params![
1271 id,
1272 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001273 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001274 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001275 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001276 KeyLifeCycle::Live,
1277 &KEYSTORE_UUID,
1278 ],
1279 )
1280 })
1281 .context("Failed to insert into keyentry table.")?;
1282
Paul Crowley8d5b2532021-03-19 10:53:07 -07001283 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1284
Hasini Gunasingheda895552021-01-27 19:34:37 +00001285 Self::set_blob_internal(
1286 &tx,
1287 key_id,
1288 SubComponentType::KEY_BLOB,
1289 Some(blob),
1290 Some(blob_metadata),
1291 )
1292 .context("Failed to store key blob.")?;
1293
1294 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1295 .context("Trying to load key components.")
1296 .no_gc()
1297 })
1298 .context("In store_super_key.")
1299 }
1300
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001301 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001302 pub fn load_super_key(
1303 &mut self,
1304 key_type: &SuperKeyType,
1305 user_id: u32,
1306 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001307 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1308
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001309 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1310 let key_descriptor = KeyDescriptor {
1311 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001312 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001313 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001314 blob: None,
1315 };
1316 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1317 match id {
1318 Ok(id) => {
1319 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1320 .context("In load_super_key. Failed to load key entry.")?;
1321 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1322 }
1323 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1324 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1325 _ => Err(error).context("In load_super_key."),
1326 },
1327 }
1328 .no_gc()
1329 })
1330 .context("In load_super_key.")
1331 }
1332
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001333 /// Atomically loads a key entry and associated metadata or creates it using the
1334 /// callback create_new_key callback. The callback is called during a database
1335 /// transaction. This means that implementers should be mindful about using
1336 /// blocking operations such as IPC or grabbing mutexes.
1337 pub fn get_or_create_key_with<F>(
1338 &mut self,
1339 domain: Domain,
1340 namespace: i64,
1341 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001342 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001343 create_new_key: F,
1344 ) -> Result<(KeyIdGuard, KeyEntry)>
1345 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001346 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001347 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001348 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1349
Janis Danisevskis66784c42021-01-27 08:40:25 -08001350 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1351 let id = {
1352 let mut stmt = tx
1353 .prepare(
1354 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001355 WHERE
1356 key_type = ?
1357 AND domain = ?
1358 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001359 AND alias = ?
1360 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001361 )
1362 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1363 let mut rows = stmt
1364 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1365 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001366
Janis Danisevskis66784c42021-01-27 08:40:25 -08001367 db_utils::with_rows_extract_one(&mut rows, |row| {
1368 Ok(match row {
1369 Some(r) => r.get(0).context("Failed to unpack id.")?,
1370 None => None,
1371 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001372 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001373 .context("In get_or_create_key_with.")?
1374 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001375
Janis Danisevskis66784c42021-01-27 08:40:25 -08001376 let (id, entry) = match id {
1377 Some(id) => (
1378 id,
1379 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1380 .context("In get_or_create_key_with.")?,
1381 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001382
Janis Danisevskis66784c42021-01-27 08:40:25 -08001383 None => {
1384 let id = Self::insert_with_retry(|id| {
1385 tx.execute(
1386 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001387 (id, key_type, domain, namespace, alias, state, km_uuid)
1388 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001389 params![
1390 id,
1391 KeyType::Super,
1392 domain.0,
1393 namespace,
1394 alias,
1395 KeyLifeCycle::Live,
1396 km_uuid,
1397 ],
1398 )
1399 })
1400 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001401
Janis Danisevskis66784c42021-01-27 08:40:25 -08001402 let (blob, metadata) =
1403 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001404 Self::set_blob_internal(
1405 &tx,
1406 id,
1407 SubComponentType::KEY_BLOB,
1408 Some(&blob),
1409 Some(&metadata),
1410 )
Paul Crowley7a658392021-03-18 17:08:20 -07001411 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001413 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001414 KeyEntry {
1415 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001416 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 pure_cert: false,
1418 ..Default::default()
1419 },
1420 )
1421 }
1422 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001423 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001424 })
1425 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001426 }
1427
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001428 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001429 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1430 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001431 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1432 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001433 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001434 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001435 loop {
1436 match self
1437 .conn
1438 .transaction_with_behavior(behavior)
1439 .context("In with_transaction.")
1440 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1441 .and_then(|(result, tx)| {
1442 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1443 Ok(result)
1444 }) {
1445 Ok(result) => break Ok(result),
1446 Err(e) => {
1447 if Self::is_locked_error(&e) {
1448 std::thread::sleep(std::time::Duration::from_micros(500));
1449 continue;
1450 } else {
1451 return Err(e).context("In with_transaction.");
1452 }
1453 }
1454 }
1455 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001456 .map(|(need_gc, result)| {
1457 if need_gc {
1458 if let Some(ref gc) = self.gc {
1459 gc.notify_gc();
1460 }
1461 }
1462 result
1463 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001464 }
1465
1466 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001467 matches!(
1468 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1469 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1470 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1471 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001472 }
1473
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001474 /// Creates a new key entry and allocates a new randomized id for the new key.
1475 /// The key id gets associated with a domain and namespace but not with an alias.
1476 /// To complete key generation `rebind_alias` should be called after all of the
1477 /// key artifacts, i.e., blobs and parameters have been associated with the new
1478 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1479 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001480 pub fn create_key_entry(
1481 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001482 domain: &Domain,
1483 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001484 km_uuid: &Uuid,
1485 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001486 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1487
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001488 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001489 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001490 })
1491 .context("In create_key_entry.")
1492 }
1493
1494 fn create_key_entry_internal(
1495 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001496 domain: &Domain,
1497 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001498 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001499 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001500 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001501 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001502 _ => {
1503 return Err(KsError::sys())
1504 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1505 }
1506 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001507 Ok(KEY_ID_LOCK.get(
1508 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001509 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001510 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001511 (id, key_type, domain, namespace, alias, state, km_uuid)
1512 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001513 params![
1514 id,
1515 KeyType::Client,
1516 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001517 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001518 KeyLifeCycle::Existing,
1519 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001520 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001521 )
1522 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001523 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001524 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001525 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001526
Max Bires2b2e6562020-09-22 11:22:36 -07001527 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1528 /// The key id gets associated with a domain and namespace later but not with an alias. The
1529 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1530 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1531 /// a key.
1532 pub fn create_attestation_key_entry(
1533 &mut self,
1534 maced_public_key: &[u8],
1535 raw_public_key: &[u8],
1536 private_key: &[u8],
1537 km_uuid: &Uuid,
1538 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001539 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1540
Max Bires2b2e6562020-09-22 11:22:36 -07001541 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1542 let key_id = KEY_ID_LOCK.get(
1543 Self::insert_with_retry(|id| {
1544 tx.execute(
1545 "INSERT into persistent.keyentry
1546 (id, key_type, domain, namespace, alias, state, km_uuid)
1547 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1548 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1549 )
1550 })
1551 .context("In create_key_entry")?,
1552 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001553 Self::set_blob_internal(
1554 &tx,
1555 key_id.0,
1556 SubComponentType::KEY_BLOB,
1557 Some(private_key),
1558 None,
1559 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001560 let mut metadata = KeyMetaData::new();
1561 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1562 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1563 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001564 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001565 })
1566 .context("In create_attestation_key_entry")
1567 }
1568
Janis Danisevskis377d1002021-01-27 19:07:48 -08001569 /// Set a new blob and associates it with the given key id. Each blob
1570 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001571 /// Each key can have one of each sub component type associated. If more
1572 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001573 /// will get garbage collected.
1574 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1575 /// removed by setting blob to None.
1576 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001577 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001578 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001579 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001580 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001581 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001582 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001583 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1584
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001585 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001586 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001587 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001588 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001589 }
1590
Janis Danisevskiseed69842021-02-18 20:04:10 -08001591 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1592 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1593 /// We use this to insert key blobs into the database which can then be garbage collected
1594 /// lazily by the key garbage collector.
1595 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001596 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1597
Janis Danisevskiseed69842021-02-18 20:04:10 -08001598 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1599 Self::set_blob_internal(
1600 &tx,
1601 Self::UNASSIGNED_KEY_ID,
1602 SubComponentType::KEY_BLOB,
1603 Some(blob),
1604 Some(blob_metadata),
1605 )
1606 .need_gc()
1607 })
1608 .context("In set_deleted_blob.")
1609 }
1610
Janis Danisevskis377d1002021-01-27 19:07:48 -08001611 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001612 tx: &Transaction,
1613 key_id: i64,
1614 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001615 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001616 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001617 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001618 match (blob, sc_type) {
1619 (Some(blob), _) => {
1620 tx.execute(
1621 "INSERT INTO persistent.blobentry
1622 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1623 params![sc_type, key_id, blob],
1624 )
1625 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001626 if let Some(blob_metadata) = blob_metadata {
1627 let blob_id = tx
1628 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1629 row.get(0)
1630 })
1631 .context("In set_blob_internal: Failed to get new blob id.")?;
1632 blob_metadata
1633 .store_in_db(blob_id, tx)
1634 .context("In set_blob_internal: Trying to store blob metadata.")?;
1635 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001636 }
1637 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1638 tx.execute(
1639 "DELETE FROM persistent.blobentry
1640 WHERE subcomponent_type = ? AND keyentryid = ?;",
1641 params![sc_type, key_id],
1642 )
1643 .context("In set_blob_internal: Failed to delete blob.")?;
1644 }
1645 (None, _) => {
1646 return Err(KsError::sys())
1647 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1648 }
1649 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001650 Ok(())
1651 }
1652
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001653 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1654 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001655 #[cfg(test)]
1656 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001657 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001658 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001659 })
1660 .context("In insert_keyparameter.")
1661 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001662
Janis Danisevskis66784c42021-01-27 08:40:25 -08001663 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001664 tx: &Transaction,
1665 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001666 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001667 ) -> Result<()> {
1668 let mut stmt = tx
1669 .prepare(
1670 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1671 VALUES (?, ?, ?, ?);",
1672 )
1673 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1674
Janis Danisevskis66784c42021-01-27 08:40:25 -08001675 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001676 stmt.insert(params![
1677 key_id.0,
1678 p.get_tag().0,
1679 p.key_parameter_value(),
1680 p.security_level().0
1681 ])
1682 .with_context(|| {
1683 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1684 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001685 }
1686 Ok(())
1687 }
1688
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001689 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001690 #[cfg(test)]
1691 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001692 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001693 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001694 })
1695 .context("In insert_key_metadata.")
1696 }
1697
Max Bires2b2e6562020-09-22 11:22:36 -07001698 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1699 /// on the public key.
1700 pub fn store_signed_attestation_certificate_chain(
1701 &mut self,
1702 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001703 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001704 cert_chain: &[u8],
1705 expiration_date: i64,
1706 km_uuid: &Uuid,
1707 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001708 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1709
Max Bires2b2e6562020-09-22 11:22:36 -07001710 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1711 let mut stmt = tx
1712 .prepare(
1713 "SELECT keyentryid
1714 FROM persistent.keymetadata
1715 WHERE tag = ? AND data = ? AND keyentryid IN
1716 (SELECT id
1717 FROM persistent.keyentry
1718 WHERE
1719 alias IS NULL AND
1720 domain IS NULL AND
1721 namespace IS NULL AND
1722 key_type = ? AND
1723 km_uuid = ?);",
1724 )
1725 .context("Failed to store attestation certificate chain.")?;
1726 let mut rows = stmt
1727 .query(params![
1728 KeyMetaData::AttestationRawPubKey,
1729 raw_public_key,
1730 KeyType::Attestation,
1731 km_uuid
1732 ])
1733 .context("Failed to fetch keyid")?;
1734 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1735 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1736 .get(0)
1737 .context("Failed to unpack id.")
1738 })
1739 .context("Failed to get key_id.")?;
1740 let num_updated = tx
1741 .execute(
1742 "UPDATE persistent.keyentry
1743 SET alias = ?
1744 WHERE id = ?;",
1745 params!["signed", key_id],
1746 )
1747 .context("Failed to update alias.")?;
1748 if num_updated != 1 {
1749 return Err(KsError::sys()).context("Alias not updated for the key.");
1750 }
1751 let mut metadata = KeyMetaData::new();
1752 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1753 expiration_date,
1754 )));
1755 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001756 Self::set_blob_internal(
1757 &tx,
1758 key_id,
1759 SubComponentType::CERT_CHAIN,
1760 Some(cert_chain),
1761 None,
1762 )
1763 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001764 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1765 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001766 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001767 })
1768 .context("In store_signed_attestation_certificate_chain: ")
1769 }
1770
1771 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1772 /// currently have a key assigned to it.
1773 pub fn assign_attestation_key(
1774 &mut self,
1775 domain: Domain,
1776 namespace: i64,
1777 km_uuid: &Uuid,
1778 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001779 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1780
Max Bires2b2e6562020-09-22 11:22:36 -07001781 match domain {
1782 Domain::APP | Domain::SELINUX => {}
1783 _ => {
1784 return Err(KsError::sys()).context(format!(
1785 concat!(
1786 "In assign_attestation_key: Domain {:?} ",
1787 "must be either App or SELinux.",
1788 ),
1789 domain
1790 ));
1791 }
1792 }
1793 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1794 let result = tx
1795 .execute(
1796 "UPDATE persistent.keyentry
1797 SET domain=?1, namespace=?2
1798 WHERE
1799 id =
1800 (SELECT MIN(id)
1801 FROM persistent.keyentry
1802 WHERE ALIAS IS NOT NULL
1803 AND domain IS NULL
1804 AND key_type IS ?3
1805 AND state IS ?4
1806 AND km_uuid IS ?5)
1807 AND
1808 (SELECT COUNT(*)
1809 FROM persistent.keyentry
1810 WHERE domain=?1
1811 AND namespace=?2
1812 AND key_type IS ?3
1813 AND state IS ?4
1814 AND km_uuid IS ?5) = 0;",
1815 params![
1816 domain.0 as u32,
1817 namespace,
1818 KeyType::Attestation,
1819 KeyLifeCycle::Live,
1820 km_uuid,
1821 ],
1822 )
1823 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001824 if result == 0 {
1825 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1826 } else if result > 1 {
1827 return Err(KsError::sys())
1828 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001829 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001830 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001831 })
1832 .context("In assign_attestation_key: ")
1833 }
1834
1835 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1836 /// provisioning server, or the maximum number available if there are not num_keys number of
1837 /// entries in the table.
1838 pub fn fetch_unsigned_attestation_keys(
1839 &mut self,
1840 num_keys: i32,
1841 km_uuid: &Uuid,
1842 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001843 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1844
Max Bires2b2e6562020-09-22 11:22:36 -07001845 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1846 let mut stmt = tx
1847 .prepare(
1848 "SELECT data
1849 FROM persistent.keymetadata
1850 WHERE tag = ? AND keyentryid IN
1851 (SELECT id
1852 FROM persistent.keyentry
1853 WHERE
1854 alias IS NULL AND
1855 domain IS NULL AND
1856 namespace IS NULL AND
1857 key_type = ? AND
1858 km_uuid = ?
1859 LIMIT ?);",
1860 )
1861 .context("Failed to prepare statement")?;
1862 let rows = stmt
1863 .query_map(
1864 params![
1865 KeyMetaData::AttestationMacedPublicKey,
1866 KeyType::Attestation,
1867 km_uuid,
1868 num_keys
1869 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001870 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001871 )?
1872 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1873 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001874 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001875 })
1876 .context("In fetch_unsigned_attestation_keys")
1877 }
1878
1879 /// Removes any keys that have expired as of the current time. Returns the number of keys
1880 /// marked unreferenced that are bound to be garbage collected.
1881 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001882 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1883
Max Bires2b2e6562020-09-22 11:22:36 -07001884 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1885 let mut stmt = tx
1886 .prepare(
1887 "SELECT keyentryid, data
1888 FROM persistent.keymetadata
1889 WHERE tag = ? AND keyentryid IN
1890 (SELECT id
1891 FROM persistent.keyentry
1892 WHERE key_type = ?);",
1893 )
1894 .context("Failed to prepare query")?;
1895 let key_ids_to_check = stmt
1896 .query_map(
1897 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1898 |row| Ok((row.get(0)?, row.get(1)?)),
1899 )?
1900 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1901 .context("Failed to get date metadata")?;
1902 let curr_time = DateTime::from_millis_epoch(
1903 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1904 );
1905 let mut num_deleted = 0;
1906 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1907 if Self::mark_unreferenced(&tx, id)? {
1908 num_deleted += 1;
1909 }
1910 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001911 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001912 })
1913 .context("In delete_expired_attestation_keys: ")
1914 }
1915
Max Bires60d7ed12021-03-05 15:59:22 -08001916 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1917 /// they are in. This is useful primarily as a testing mechanism.
1918 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001919 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1920
Max Bires60d7ed12021-03-05 15:59:22 -08001921 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1922 let mut stmt = tx
1923 .prepare(
1924 "SELECT id FROM persistent.keyentry
1925 WHERE key_type IS ?;",
1926 )
1927 .context("Failed to prepare statement")?;
1928 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001929 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001930 .collect::<rusqlite::Result<Vec<i64>>>()
1931 .context("Failed to execute statement")?;
1932 let num_deleted = keys_to_delete
1933 .iter()
1934 .map(|id| Self::mark_unreferenced(&tx, *id))
1935 .collect::<Result<Vec<bool>>>()
1936 .context("Failed to execute mark_unreferenced on a keyid")?
1937 .into_iter()
1938 .filter(|result| *result)
1939 .count() as i64;
1940 Ok(num_deleted).do_gc(num_deleted != 0)
1941 })
1942 .context("In delete_all_attestation_keys: ")
1943 }
1944
Max Bires2b2e6562020-09-22 11:22:36 -07001945 /// Counts the number of keys that will expire by the provided epoch date and the number of
1946 /// keys not currently assigned to a domain.
1947 pub fn get_attestation_pool_status(
1948 &mut self,
1949 date: i64,
1950 km_uuid: &Uuid,
1951 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001952 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1953
Max Bires2b2e6562020-09-22 11:22:36 -07001954 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1955 let mut stmt = tx.prepare(
1956 "SELECT data
1957 FROM persistent.keymetadata
1958 WHERE tag = ? AND keyentryid IN
1959 (SELECT id
1960 FROM persistent.keyentry
1961 WHERE alias IS NOT NULL
1962 AND key_type = ?
1963 AND km_uuid = ?
1964 AND state = ?);",
1965 )?;
1966 let times = stmt
1967 .query_map(
1968 params![
1969 KeyMetaData::AttestationExpirationDate,
1970 KeyType::Attestation,
1971 km_uuid,
1972 KeyLifeCycle::Live
1973 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001974 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001975 )?
1976 .collect::<rusqlite::Result<Vec<DateTime>>>()
1977 .context("Failed to execute metadata statement")?;
1978 let expiring =
1979 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1980 as i32;
1981 stmt = tx.prepare(
1982 "SELECT alias, domain
1983 FROM persistent.keyentry
1984 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1985 )?;
1986 let rows = stmt
1987 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1988 Ok((row.get(0)?, row.get(1)?))
1989 })?
1990 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1991 .context("Failed to execute keyentry statement")?;
1992 let mut unassigned = 0i32;
1993 let mut attested = 0i32;
1994 let total = rows.len() as i32;
1995 for (alias, domain) in rows {
1996 match (alias, domain) {
1997 (Some(_alias), None) => {
1998 attested += 1;
1999 unassigned += 1;
2000 }
2001 (Some(_alias), Some(_domain)) => {
2002 attested += 1;
2003 }
2004 _ => {}
2005 }
2006 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002007 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002008 })
2009 .context("In get_attestation_pool_status: ")
2010 }
2011
2012 /// Fetches the private key and corresponding certificate chain assigned to a
2013 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2014 /// not assigned, or one CertificateChain.
2015 pub fn retrieve_attestation_key_and_cert_chain(
2016 &mut self,
2017 domain: Domain,
2018 namespace: i64,
2019 km_uuid: &Uuid,
2020 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002021 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2022
Max Bires2b2e6562020-09-22 11:22:36 -07002023 match domain {
2024 Domain::APP | Domain::SELINUX => {}
2025 _ => {
2026 return Err(KsError::sys())
2027 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2028 }
2029 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002030 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2031 let mut stmt = tx.prepare(
2032 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002033 FROM persistent.blobentry
2034 WHERE keyentryid IN
2035 (SELECT id
2036 FROM persistent.keyentry
2037 WHERE key_type = ?
2038 AND domain = ?
2039 AND namespace = ?
2040 AND state = ?
2041 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002042 )?;
2043 let rows = stmt
2044 .query_map(
2045 params![
2046 KeyType::Attestation,
2047 domain.0 as u32,
2048 namespace,
2049 KeyLifeCycle::Live,
2050 km_uuid
2051 ],
2052 |row| Ok((row.get(0)?, row.get(1)?)),
2053 )?
2054 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002055 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002056 if rows.is_empty() {
2057 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002058 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002059 return Err(KsError::sys()).context(format!(
2060 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002061 "Expected to get a single attestation",
2062 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2063 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002064 rows.len()
2065 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002066 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002067 let mut km_blob: Vec<u8> = Vec::new();
2068 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002069 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002070 for row in rows {
2071 let sub_type: SubComponentType = row.0;
2072 match sub_type {
2073 SubComponentType::KEY_BLOB => {
2074 km_blob = row.1;
2075 }
2076 SubComponentType::CERT_CHAIN => {
2077 cert_chain_blob = row.1;
2078 }
Max Biresb2e1d032021-02-08 21:35:05 -08002079 SubComponentType::CERT => {
2080 batch_cert_blob = row.1;
2081 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2083 }
2084 }
2085 Ok(Some(CertificateChain {
2086 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002087 batch_cert: batch_cert_blob,
2088 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002089 }))
2090 .no_gc()
2091 })
Max Biresb2e1d032021-02-08 21:35:05 -08002092 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002093 }
2094
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002095 /// Updates the alias column of the given key id `newid` with the given alias,
2096 /// and atomically, removes the alias, domain, and namespace from another row
2097 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002098 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2099 /// collector.
2100 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002101 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002102 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002103 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002104 domain: &Domain,
2105 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002106 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002107 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002108 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002109 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002110 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002111 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002112 domain
2113 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002114 }
2115 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002116 let updated = tx
2117 .execute(
2118 "UPDATE persistent.keyentry
2119 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002120 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002121 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2122 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002123 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002124 let result = tx
2125 .execute(
2126 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 SET alias = ?, state = ?
2128 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2129 params![
2130 alias,
2131 KeyLifeCycle::Live,
2132 newid.0,
2133 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002134 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002135 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002136 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002137 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002138 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002139 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002140 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002141 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002142 result
2143 ));
2144 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002145 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002146 }
2147
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002148 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2149 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2150 pub fn migrate_key_namespace(
2151 &mut self,
2152 key_id_guard: KeyIdGuard,
2153 destination: &KeyDescriptor,
2154 caller_uid: u32,
2155 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2156 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002157 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2158
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002159 let destination = match destination.domain {
2160 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2161 Domain::SELINUX => (*destination).clone(),
2162 domain => {
2163 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2164 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2165 }
2166 };
2167
2168 // Security critical: Must return immediately on failure. Do not remove the '?';
2169 check_permission(&destination)
2170 .context("In migrate_key_namespace: Trying to check permission.")?;
2171
2172 let alias = destination
2173 .alias
2174 .as_ref()
2175 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2176 .context("In migrate_key_namespace: Alias must be specified.")?;
2177
2178 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2179 // Query the destination location. If there is a key, the migration request fails.
2180 if tx
2181 .query_row(
2182 "SELECT id FROM persistent.keyentry
2183 WHERE alias = ? AND domain = ? AND namespace = ?;",
2184 params![alias, destination.domain.0, destination.nspace],
2185 |_| Ok(()),
2186 )
2187 .optional()
2188 .context("Failed to query destination.")?
2189 .is_some()
2190 {
2191 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2192 .context("Target already exists.");
2193 }
2194
2195 let updated = tx
2196 .execute(
2197 "UPDATE persistent.keyentry
2198 SET alias = ?, domain = ?, namespace = ?
2199 WHERE id = ?;",
2200 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2201 )
2202 .context("Failed to update key entry.")?;
2203
2204 if updated != 1 {
2205 return Err(KsError::sys())
2206 .context(format!("Update succeeded, but {} rows were updated.", updated));
2207 }
2208 Ok(()).no_gc()
2209 })
2210 .context("In migrate_key_namespace:")
2211 }
2212
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002213 /// Store a new key in a single transaction.
2214 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2215 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002216 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2217 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002218 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002219 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002220 key: &KeyDescriptor,
2221 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002222 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002223 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002224 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002225 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002226 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002227 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2228
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002229 let (alias, domain, namespace) = match key {
2230 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2231 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2232 (alias, key.domain, nspace)
2233 }
2234 _ => {
2235 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2236 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2237 }
2238 };
2239 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002240 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002241 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002242 let (blob, blob_metadata) = *blob_info;
2243 Self::set_blob_internal(
2244 tx,
2245 key_id.id(),
2246 SubComponentType::KEY_BLOB,
2247 Some(blob),
2248 Some(&blob_metadata),
2249 )
2250 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002251 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002252 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002253 .context("Trying to insert the certificate.")?;
2254 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002255 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002256 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002257 tx,
2258 key_id.id(),
2259 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002260 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002261 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002262 )
2263 .context("Trying to insert the certificate chain.")?;
2264 }
2265 Self::insert_keyparameter_internal(tx, &key_id, params)
2266 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002267 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002268 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002269 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002270 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 })
2272 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002273 }
2274
Janis Danisevskis377d1002021-01-27 19:07:48 -08002275 /// Store a new certificate
2276 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2277 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002278 pub fn store_new_certificate(
2279 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002280 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002281 cert: &[u8],
2282 km_uuid: &Uuid,
2283 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002284 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2285
Janis Danisevskis377d1002021-01-27 19:07:48 -08002286 let (alias, domain, namespace) = match key {
2287 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2288 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2289 (alias, key.domain, nspace)
2290 }
2291 _ => {
2292 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2293 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2294 )
2295 }
2296 };
2297 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002298 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002299 .context("Trying to create new key entry.")?;
2300
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002301 Self::set_blob_internal(
2302 tx,
2303 key_id.id(),
2304 SubComponentType::CERT_CHAIN,
2305 Some(cert),
2306 None,
2307 )
2308 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002309
2310 let mut metadata = KeyMetaData::new();
2311 metadata.add(KeyMetaEntry::CreationDate(
2312 DateTime::now().context("Trying to make creation time.")?,
2313 ));
2314
2315 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2316
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002317 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002318 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002319 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002320 })
2321 .context("In store_new_certificate.")
2322 }
2323
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002324 // Helper function loading the key_id given the key descriptor
2325 // tuple comprising domain, namespace, and alias.
2326 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002327 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002328 let alias = key
2329 .alias
2330 .as_ref()
2331 .map_or_else(|| Err(KsError::sys()), Ok)
2332 .context("In load_key_entry_id: Alias must be specified.")?;
2333 let mut stmt = tx
2334 .prepare(
2335 "SELECT id FROM persistent.keyentry
2336 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002337 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002338 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002339 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002340 AND alias = ?
2341 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002342 )
2343 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2344 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002345 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002346 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002347 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002348 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002349 .get(0)
2350 .context("Failed to unpack id.")
2351 })
2352 .context("In load_key_entry_id.")
2353 }
2354
2355 /// This helper function completes the access tuple of a key, which is required
2356 /// to perform access control. The strategy depends on the `domain` field in the
2357 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002358 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002359 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002360 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002361 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002362 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002363 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002364 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002365 /// `namespace`.
2366 /// In each case the information returned is sufficient to perform the access
2367 /// check and the key id can be used to load further key artifacts.
2368 fn load_access_tuple(
2369 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002370 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002371 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002372 caller_uid: u32,
2373 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2374 match key.domain {
2375 // Domain App or SELinux. In this case we load the key_id from
2376 // the keyentry database for further loading of key components.
2377 // We already have the full access tuple to perform access control.
2378 // The only distinction is that we use the caller_uid instead
2379 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002380 // Domain::APP.
2381 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002382 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002383 if access_key.domain == Domain::APP {
2384 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002385 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002386 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002387 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002388
2389 Ok((key_id, access_key, None))
2390 }
2391
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002392 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002393 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002394 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002395 let mut stmt = tx
2396 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002397 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002398 WHERE grantee = ? AND id = ? AND
2399 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002400 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002401 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002402 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002403 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002404 .context("Domain:Grant: query failed.")?;
2405 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002406 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002407 let r =
2408 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002409 Ok((
2410 r.get(0).context("Failed to unpack key_id.")?,
2411 r.get(1).context("Failed to unpack access_vector.")?,
2412 ))
2413 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002414 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002415 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002416 }
2417
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002418 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002420 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002421 let (domain, namespace): (Domain, i64) = {
2422 let mut stmt = tx
2423 .prepare(
2424 "SELECT domain, namespace FROM persistent.keyentry
2425 WHERE
2426 id = ?
2427 AND state = ?;",
2428 )
2429 .context("Domain::KEY_ID: prepare statement failed")?;
2430 let mut rows = stmt
2431 .query(params![key.nspace, KeyLifeCycle::Live])
2432 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002433 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002434 let r =
2435 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002436 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002437 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 r.get(1).context("Failed to unpack namespace.")?,
2439 ))
2440 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002441 .context("Domain::KEY_ID.")?
2442 };
2443
2444 // We may use a key by id after loading it by grant.
2445 // In this case we have to check if the caller has a grant for this particular
2446 // key. We can skip this if we already know that the caller is the owner.
2447 // But we cannot know this if domain is anything but App. E.g. in the case
2448 // of Domain::SELINUX we have to speculatively check for grants because we have to
2449 // consult the SEPolicy before we know if the caller is the owner.
2450 let access_vector: Option<KeyPermSet> =
2451 if domain != Domain::APP || namespace != caller_uid as i64 {
2452 let access_vector: Option<i32> = tx
2453 .query_row(
2454 "SELECT access_vector FROM persistent.grant
2455 WHERE grantee = ? AND keyentryid = ?;",
2456 params![caller_uid as i64, key.nspace],
2457 |row| row.get(0),
2458 )
2459 .optional()
2460 .context("Domain::KEY_ID: query grant failed.")?;
2461 access_vector.map(|p| p.into())
2462 } else {
2463 None
2464 };
2465
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002466 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002467 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002468 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002469 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002470
Janis Danisevskis45760022021-01-19 16:34:10 -08002471 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002472 }
2473 _ => Err(anyhow!(KsError::sys())),
2474 }
2475 }
2476
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002477 fn load_blob_components(
2478 key_id: i64,
2479 load_bits: KeyEntryLoadBits,
2480 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002481 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002482 let mut stmt = tx
2483 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002484 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002485 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2486 )
2487 .context("In load_blob_components: prepare statement failed.")?;
2488
2489 let mut rows =
2490 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2491
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002492 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002493 let mut cert_blob: Option<Vec<u8>> = None;
2494 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002495 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002496 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002497 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002498 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002499 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002500 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2501 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002502 key_blob = Some((
2503 row.get(0).context("Failed to extract key blob id.")?,
2504 row.get(2).context("Failed to extract key blob.")?,
2505 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002506 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002507 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002508 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002509 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002510 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002511 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002512 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002513 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002514 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002515 (SubComponentType::CERT, _, _)
2516 | (SubComponentType::CERT_CHAIN, _, _)
2517 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002518 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2519 }
2520 Ok(())
2521 })
2522 .context("In load_blob_components.")?;
2523
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002524 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2525 Ok(Some((
2526 blob,
2527 BlobMetaData::load_from_db(blob_id, tx)
2528 .context("In load_blob_components: Trying to load blob_metadata.")?,
2529 )))
2530 })?;
2531
2532 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002533 }
2534
2535 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2536 let mut stmt = tx
2537 .prepare(
2538 "SELECT tag, data, security_level from persistent.keyparameter
2539 WHERE keyentryid = ?;",
2540 )
2541 .context("In load_key_parameters: prepare statement failed.")?;
2542
2543 let mut parameters: Vec<KeyParameter> = Vec::new();
2544
2545 let mut rows =
2546 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002547 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002548 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2549 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002550 parameters.push(
2551 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2552 .context("Failed to read KeyParameter.")?,
2553 );
2554 Ok(())
2555 })
2556 .context("In load_key_parameters.")?;
2557
2558 Ok(parameters)
2559 }
2560
Qi Wub9433b52020-12-01 14:52:46 +08002561 /// Decrements the usage count of a limited use key. This function first checks whether the
2562 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2563 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2564 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002565 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002566 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2567
Qi Wub9433b52020-12-01 14:52:46 +08002568 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2569 let limit: Option<i32> = tx
2570 .query_row(
2571 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2572 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2573 |row| row.get(0),
2574 )
2575 .optional()
2576 .context("Trying to load usage count")?;
2577
2578 let limit = limit
2579 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2580 .context("The Key no longer exists. Key is exhausted.")?;
2581
2582 tx.execute(
2583 "UPDATE persistent.keyparameter
2584 SET data = data - 1
2585 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2586 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2587 )
2588 .context("Failed to update key usage count.")?;
2589
2590 match limit {
2591 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002592 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002593 .context("Trying to mark limited use key for deletion."),
2594 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002595 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002596 }
2597 })
2598 .context("In check_and_update_key_usage_count.")
2599 }
2600
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002601 /// Load a key entry by the given key descriptor.
2602 /// It uses the `check_permission` callback to verify if the access is allowed
2603 /// given the key access tuple read from the database using `load_access_tuple`.
2604 /// With `load_bits` the caller may specify which blobs shall be loaded from
2605 /// the blob database.
2606 pub fn load_key_entry(
2607 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002608 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002609 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002610 load_bits: KeyEntryLoadBits,
2611 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002612 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2613 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002614 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2615
Janis Danisevskis66784c42021-01-27 08:40:25 -08002616 loop {
2617 match self.load_key_entry_internal(
2618 key,
2619 key_type,
2620 load_bits,
2621 caller_uid,
2622 &check_permission,
2623 ) {
2624 Ok(result) => break Ok(result),
2625 Err(e) => {
2626 if Self::is_locked_error(&e) {
2627 std::thread::sleep(std::time::Duration::from_micros(500));
2628 continue;
2629 } else {
2630 return Err(e).context("In load_key_entry.");
2631 }
2632 }
2633 }
2634 }
2635 }
2636
2637 fn load_key_entry_internal(
2638 &mut self,
2639 key: &KeyDescriptor,
2640 key_type: KeyType,
2641 load_bits: KeyEntryLoadBits,
2642 caller_uid: u32,
2643 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002644 ) -> Result<(KeyIdGuard, KeyEntry)> {
2645 // KEY ID LOCK 1/2
2646 // If we got a key descriptor with a key id we can get the lock right away.
2647 // Otherwise we have to defer it until we know the key id.
2648 let key_id_guard = match key.domain {
2649 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2650 _ => None,
2651 };
2652
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002653 let tx = self
2654 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002655 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002656 .context("In load_key_entry: Failed to initialize transaction.")?;
2657
2658 // Load the key_id and complete the access control tuple.
2659 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002660 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2661 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002662
2663 // Perform access control. It is vital that we return here if the permission is denied.
2664 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002665 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002666
Janis Danisevskisaec14592020-11-12 09:41:49 -08002667 // KEY ID LOCK 2/2
2668 // If we did not get a key id lock by now, it was because we got a key descriptor
2669 // without a key id. At this point we got the key id, so we can try and get a lock.
2670 // However, we cannot block here, because we are in the middle of the transaction.
2671 // So first we try to get the lock non blocking. If that fails, we roll back the
2672 // transaction and block until we get the lock. After we successfully got the lock,
2673 // we start a new transaction and load the access tuple again.
2674 //
2675 // We don't need to perform access control again, because we already established
2676 // that the caller had access to the given key. But we need to make sure that the
2677 // key id still exists. So we have to load the key entry by key id this time.
2678 let (key_id_guard, tx) = match key_id_guard {
2679 None => match KEY_ID_LOCK.try_get(key_id) {
2680 None => {
2681 // Roll back the transaction.
2682 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002683
Janis Danisevskisaec14592020-11-12 09:41:49 -08002684 // Block until we have a key id lock.
2685 let key_id_guard = KEY_ID_LOCK.get(key_id);
2686
2687 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002688 let tx = self
2689 .conn
2690 .unchecked_transaction()
2691 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002692
2693 Self::load_access_tuple(
2694 &tx,
2695 // This time we have to load the key by the retrieved key id, because the
2696 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002697 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002698 domain: Domain::KEY_ID,
2699 nspace: key_id,
2700 ..Default::default()
2701 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002702 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002703 caller_uid,
2704 )
2705 .context("In load_key_entry. (deferred key lock)")?;
2706 (key_id_guard, tx)
2707 }
2708 Some(l) => (l, tx),
2709 },
2710 Some(key_id_guard) => (key_id_guard, tx),
2711 };
2712
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002713 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2714 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002715
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002716 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2717
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002718 Ok((key_id_guard, key_entry))
2719 }
2720
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002721 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002722 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002723 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2724 .context("Trying to delete keyentry.")?;
2725 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2726 .context("Trying to delete keymetadata.")?;
2727 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2728 .context("Trying to delete keyparameters.")?;
2729 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2730 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002731 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002732 }
2733
2734 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002735 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002736 pub fn unbind_key(
2737 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002738 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002739 key_type: KeyType,
2740 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002741 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002742 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002743 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2744
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002745 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2746 let (key_id, access_key_descriptor, access_vector) =
2747 Self::load_access_tuple(tx, key, key_type, caller_uid)
2748 .context("Trying to get access tuple.")?;
2749
2750 // Perform access control. It is vital that we return here if the permission is denied.
2751 // So do not touch that '?' at the end.
2752 check_permission(&access_key_descriptor, access_vector)
2753 .context("While checking permission.")?;
2754
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002755 Self::mark_unreferenced(tx, key_id)
2756 .map(|need_gc| (need_gc, ()))
2757 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002758 })
2759 .context("In unbind_key.")
2760 }
2761
Max Bires8e93d2b2021-01-14 13:17:59 -08002762 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2763 tx.query_row(
2764 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2765 params![key_id],
2766 |row| row.get(0),
2767 )
2768 .context("In get_key_km_uuid.")
2769 }
2770
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002771 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2772 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2773 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002774 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2775
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002776 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2777 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2778 .context("In unbind_keys_for_namespace.");
2779 }
2780 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2781 tx.execute(
2782 "DELETE FROM persistent.keymetadata
2783 WHERE keyentryid IN (
2784 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002785 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002786 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002787 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002788 )
2789 .context("Trying to delete keymetadata.")?;
2790 tx.execute(
2791 "DELETE FROM persistent.keyparameter
2792 WHERE keyentryid IN (
2793 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002794 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002795 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002796 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002797 )
2798 .context("Trying to delete keyparameters.")?;
2799 tx.execute(
2800 "DELETE FROM persistent.grant
2801 WHERE keyentryid IN (
2802 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002803 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002804 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002805 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002806 )
2807 .context("Trying to delete grants.")?;
2808 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002809 "DELETE FROM persistent.keyentry
2810 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2811 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002812 )
2813 .context("Trying to delete keyentry.")?;
2814 Ok(()).need_gc()
2815 })
2816 .context("In unbind_keys_for_namespace")
2817 }
2818
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002819 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2820 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2821 {
2822 tx.execute(
2823 "DELETE FROM persistent.keymetadata
2824 WHERE keyentryid IN (
2825 SELECT id FROM persistent.keyentry
2826 WHERE state = ?
2827 );",
2828 params![KeyLifeCycle::Unreferenced],
2829 )
2830 .context("Trying to delete keymetadata.")?;
2831 tx.execute(
2832 "DELETE FROM persistent.keyparameter
2833 WHERE keyentryid IN (
2834 SELECT id FROM persistent.keyentry
2835 WHERE state = ?
2836 );",
2837 params![KeyLifeCycle::Unreferenced],
2838 )
2839 .context("Trying to delete keyparameters.")?;
2840 tx.execute(
2841 "DELETE FROM persistent.grant
2842 WHERE keyentryid IN (
2843 SELECT id FROM persistent.keyentry
2844 WHERE state = ?
2845 );",
2846 params![KeyLifeCycle::Unreferenced],
2847 )
2848 .context("Trying to delete grants.")?;
2849 tx.execute(
2850 "DELETE FROM persistent.keyentry
2851 WHERE state = ?;",
2852 params![KeyLifeCycle::Unreferenced],
2853 )
2854 .context("Trying to delete keyentry.")?;
2855 Result::<()>::Ok(())
2856 }
2857 .context("In cleanup_unreferenced")
2858 }
2859
Hasini Gunasingheda895552021-01-27 19:34:37 +00002860 /// Delete the keys created on behalf of the user, denoted by the user id.
2861 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2862 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2863 /// The caller of this function should notify the gc if the returned value is true.
2864 pub fn unbind_keys_for_user(
2865 &mut self,
2866 user_id: u32,
2867 keep_non_super_encrypted_keys: bool,
2868 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002869 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2870
Hasini Gunasingheda895552021-01-27 19:34:37 +00002871 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2872 let mut stmt = tx
2873 .prepare(&format!(
2874 "SELECT id from persistent.keyentry
2875 WHERE (
2876 key_type = ?
2877 AND domain = ?
2878 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2879 AND state = ?
2880 ) OR (
2881 key_type = ?
2882 AND namespace = ?
2883 AND alias = ?
2884 AND state = ?
2885 );",
2886 aid_user_offset = AID_USER_OFFSET
2887 ))
2888 .context(concat!(
2889 "In unbind_keys_for_user. ",
2890 "Failed to prepare the query to find the keys created by apps."
2891 ))?;
2892
2893 let mut rows = stmt
2894 .query(params![
2895 // WHERE client key:
2896 KeyType::Client,
2897 Domain::APP.0 as u32,
2898 user_id,
2899 KeyLifeCycle::Live,
2900 // OR super key:
2901 KeyType::Super,
2902 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002903 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002904 KeyLifeCycle::Live
2905 ])
2906 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2907
2908 let mut key_ids: Vec<i64> = Vec::new();
2909 db_utils::with_rows_extract_all(&mut rows, |row| {
2910 key_ids
2911 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2912 Ok(())
2913 })
2914 .context("In unbind_keys_for_user.")?;
2915
2916 let mut notify_gc = false;
2917 for key_id in key_ids {
2918 if keep_non_super_encrypted_keys {
2919 // Load metadata and filter out non-super-encrypted keys.
2920 if let (_, Some((_, blob_metadata)), _, _) =
2921 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2922 .context("In unbind_keys_for_user: Trying to load blob info.")?
2923 {
2924 if blob_metadata.encrypted_by().is_none() {
2925 continue;
2926 }
2927 }
2928 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002929 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002930 .context("In unbind_keys_for_user.")?
2931 || notify_gc;
2932 }
2933 Ok(()).do_gc(notify_gc)
2934 })
2935 .context("In unbind_keys_for_user.")
2936 }
2937
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002938 fn load_key_components(
2939 tx: &Transaction,
2940 load_bits: KeyEntryLoadBits,
2941 key_id: i64,
2942 ) -> Result<KeyEntry> {
2943 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2944
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002945 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002946 Self::load_blob_components(key_id, load_bits, &tx)
2947 .context("In load_key_components.")?;
2948
Max Bires8e93d2b2021-01-14 13:17:59 -08002949 let parameters = Self::load_key_parameters(key_id, &tx)
2950 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002951
Max Bires8e93d2b2021-01-14 13:17:59 -08002952 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2953 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002954
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002955 Ok(KeyEntry {
2956 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002957 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002958 cert: cert_blob,
2959 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002960 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002961 parameters,
2962 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002963 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002964 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002965 }
2966
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002967 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2968 /// The key descriptors will have the domain, nspace, and alias field set.
2969 /// Domain must be APP or SELINUX, the caller must make sure of that.
2970 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002971 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2972
Janis Danisevskis66784c42021-01-27 08:40:25 -08002973 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2974 let mut stmt = tx
2975 .prepare(
2976 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002977 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002978 )
2979 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002980
Janis Danisevskis66784c42021-01-27 08:40:25 -08002981 let mut rows = stmt
2982 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2983 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002984
Janis Danisevskis66784c42021-01-27 08:40:25 -08002985 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2986 db_utils::with_rows_extract_all(&mut rows, |row| {
2987 descriptors.push(KeyDescriptor {
2988 domain,
2989 nspace: namespace,
2990 alias: Some(row.get(0).context("Trying to extract alias.")?),
2991 blob: None,
2992 });
2993 Ok(())
2994 })
2995 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002996 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002997 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002998 }
2999
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003000 /// Adds a grant to the grant table.
3001 /// Like `load_key_entry` this function loads the access tuple before
3002 /// it uses the callback for a permission check. Upon success,
3003 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3004 /// grant table. The new row will have a randomized id, which is used as
3005 /// grant id in the namespace field of the resulting KeyDescriptor.
3006 pub fn grant(
3007 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003008 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003009 caller_uid: u32,
3010 grantee_uid: u32,
3011 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003012 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003013 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003014 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3015
Janis Danisevskis66784c42021-01-27 08:40:25 -08003016 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3017 // Load the key_id and complete the access control tuple.
3018 // We ignore the access vector here because grants cannot be granted.
3019 // The access vector returned here expresses the permissions the
3020 // grantee has if key.domain == Domain::GRANT. But this vector
3021 // cannot include the grant permission by design, so there is no way the
3022 // subsequent permission check can pass.
3023 // We could check key.domain == Domain::GRANT and fail early.
3024 // But even if we load the access tuple by grant here, the permission
3025 // check denies the attempt to create a grant by grant descriptor.
3026 let (key_id, access_key_descriptor, _) =
3027 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3028 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003029
Janis Danisevskis66784c42021-01-27 08:40:25 -08003030 // Perform access control. It is vital that we return here if the permission
3031 // was denied. So do not touch that '?' at the end of the line.
3032 // This permission check checks if the caller has the grant permission
3033 // for the given key and in addition to all of the permissions
3034 // expressed in `access_vector`.
3035 check_permission(&access_key_descriptor, &access_vector)
3036 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003037
Janis Danisevskis66784c42021-01-27 08:40:25 -08003038 let grant_id = if let Some(grant_id) = tx
3039 .query_row(
3040 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003041 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003042 params![key_id, grantee_uid],
3043 |row| row.get(0),
3044 )
3045 .optional()
3046 .context("In grant: Failed get optional existing grant id.")?
3047 {
3048 tx.execute(
3049 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003050 SET access_vector = ?
3051 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003052 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003053 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003054 .context("In grant: Failed to update existing grant.")?;
3055 grant_id
3056 } else {
3057 Self::insert_with_retry(|id| {
3058 tx.execute(
3059 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3060 VALUES (?, ?, ?, ?);",
3061 params![id, grantee_uid, key_id, i32::from(access_vector)],
3062 )
3063 })
3064 .context("In grant")?
3065 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003066
Janis Danisevskis66784c42021-01-27 08:40:25 -08003067 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003068 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003069 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003070 }
3071
3072 /// This function checks permissions like `grant` and `load_key_entry`
3073 /// before removing a grant from the grant table.
3074 pub fn ungrant(
3075 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003076 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003077 caller_uid: u32,
3078 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003079 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003080 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003081 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3082
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3084 // Load the key_id and complete the access control tuple.
3085 // We ignore the access vector here because grants cannot be granted.
3086 let (key_id, access_key_descriptor, _) =
3087 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3088 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003089
Janis Danisevskis66784c42021-01-27 08:40:25 -08003090 // Perform access control. We must return here if the permission
3091 // was denied. So do not touch the '?' at the end of this line.
3092 check_permission(&access_key_descriptor)
3093 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003094
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 tx.execute(
3096 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003097 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003098 params![key_id, grantee_uid],
3099 )
3100 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003102 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003103 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003104 }
3105
Joel Galenson845f74b2020-09-09 14:11:55 -07003106 // Generates a random id and passes it to the given function, which will
3107 // try to insert it into a database. If that insertion fails, retry;
3108 // otherwise return the id.
3109 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3110 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003111 let newid: i64 = match random() {
3112 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3113 i => i,
3114 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003115 match inserter(newid) {
3116 // If the id already existed, try again.
3117 Err(rusqlite::Error::SqliteFailure(
3118 libsqlite3_sys::Error {
3119 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3120 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3121 },
3122 _,
3123 )) => (),
3124 Err(e) => {
3125 return Err(e).context("In insert_with_retry: failed to insert into database.")
3126 }
3127 _ => return Ok(newid),
3128 }
3129 }
3130 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003131
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003132 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3133 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3134 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3135 auth_token.clone(),
3136 MonotonicRawTime::now(),
3137 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003138 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003139
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003140 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003141 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003142 where
3143 F: Fn(&AuthTokenEntry) -> bool,
3144 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003145 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003146 }
3147
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003148 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003149 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3150 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003151 }
3152
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003153 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003154 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3155 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003156 }
3157
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003158 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003159 fn get_last_off_body(&self) -> MonotonicRawTime {
3160 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003161 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003162
3163 /// Load descriptor of a key by key id
3164 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3165 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3166
3167 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3168 tx.query_row(
3169 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3170 params![key_id],
3171 |row| {
3172 Ok(KeyDescriptor {
3173 domain: Domain(row.get(0)?),
3174 nspace: row.get(1)?,
3175 alias: row.get(2)?,
3176 blob: None,
3177 })
3178 },
3179 )
3180 .optional()
3181 .context("Trying to load key descriptor")
3182 .no_gc()
3183 })
3184 .context("In load_key_descriptor.")
3185 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003186}
3187
3188#[cfg(test)]
3189mod tests {
3190
3191 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003192 use crate::key_parameter::{
3193 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3194 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3195 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003196 use crate::key_perm_set;
3197 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003198 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003199 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003200 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3201 HardwareAuthToken::HardwareAuthToken,
3202 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003203 };
3204 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003205 Timestamp::Timestamp,
3206 };
Seth Moore472fcbb2021-05-12 10:07:51 -07003207 use rusqlite::DatabaseName::Attached;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003208 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003209 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003210 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003211 use std::collections::BTreeMap;
3212 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003213 use std::sync::atomic::{AtomicU8, Ordering};
3214 use std::sync::Arc;
3215 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003216 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003217 #[cfg(disabled)]
3218 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003219
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003220 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003221 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003222
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003223 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003224 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003225 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003226 })?;
3227 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003228 }
3229
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003230 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3231 where
3232 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3233 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003234 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003235
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003236 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003237 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003238
Janis Danisevskis3395f862021-05-06 10:54:17 -07003239 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003240 }
3241
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003242 fn rebind_alias(
3243 db: &mut KeystoreDB,
3244 newid: &KeyIdGuard,
3245 alias: &str,
3246 domain: Domain,
3247 namespace: i64,
3248 ) -> Result<bool> {
3249 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003250 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003251 })
3252 .context("In rebind_alias.")
3253 }
3254
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003255 #[test]
3256 fn datetime() -> Result<()> {
3257 let conn = Connection::open_in_memory()?;
3258 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3259 let now = SystemTime::now();
3260 let duration = Duration::from_secs(1000);
3261 let then = now.checked_sub(duration).unwrap();
3262 let soon = now.checked_add(duration).unwrap();
3263 conn.execute(
3264 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3265 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3266 )?;
3267 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3268 let mut rows = stmt.query(NO_PARAMS)?;
3269 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3270 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3271 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3272 assert!(rows.next()?.is_none());
3273 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3274 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3275 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3276 Ok(())
3277 }
3278
Joel Galenson0891bc12020-07-20 10:37:03 -07003279 // Ensure that we're using the "injected" random function, not the real one.
3280 #[test]
3281 fn test_mocked_random() {
3282 let rand1 = random();
3283 let rand2 = random();
3284 let rand3 = random();
3285 if rand1 == rand2 {
3286 assert_eq!(rand2 + 1, rand3);
3287 } else {
3288 assert_eq!(rand1 + 1, rand2);
3289 assert_eq!(rand2, rand3);
3290 }
3291 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003292
Joel Galenson26f4d012020-07-17 14:57:21 -07003293 // Test that we have the correct tables.
3294 #[test]
3295 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003296 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003297 let tables = db
3298 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003299 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003300 .query_map(params![], |row| row.get(0))?
3301 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003302 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003303 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003304 assert_eq!(tables[1], "blobmetadata");
3305 assert_eq!(tables[2], "grant");
3306 assert_eq!(tables[3], "keyentry");
3307 assert_eq!(tables[4], "keymetadata");
3308 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003309 Ok(())
3310 }
3311
3312 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003313 fn test_auth_token_table_invariant() -> Result<()> {
3314 let mut db = new_test_db()?;
3315 let auth_token1 = HardwareAuthToken {
3316 challenge: i64::MAX,
3317 userId: 200,
3318 authenticatorId: 200,
3319 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3320 timestamp: Timestamp { milliSeconds: 500 },
3321 mac: String::from("mac").into_bytes(),
3322 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003323 db.insert_auth_token(&auth_token1);
3324 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003325 assert_eq!(auth_tokens_returned.len(), 1);
3326
3327 // insert another auth token with the same values for the columns in the UNIQUE constraint
3328 // of the auth token table and different value for timestamp
3329 let auth_token2 = HardwareAuthToken {
3330 challenge: i64::MAX,
3331 userId: 200,
3332 authenticatorId: 200,
3333 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3334 timestamp: Timestamp { milliSeconds: 600 },
3335 mac: String::from("mac").into_bytes(),
3336 };
3337
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003338 db.insert_auth_token(&auth_token2);
3339 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003340 assert_eq!(auth_tokens_returned.len(), 1);
3341
3342 if let Some(auth_token) = auth_tokens_returned.pop() {
3343 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3344 }
3345
3346 // insert another auth token with the different values for the columns in the UNIQUE
3347 // constraint of the auth token table
3348 let auth_token3 = HardwareAuthToken {
3349 challenge: i64::MAX,
3350 userId: 201,
3351 authenticatorId: 200,
3352 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3353 timestamp: Timestamp { milliSeconds: 600 },
3354 mac: String::from("mac").into_bytes(),
3355 };
3356
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003357 db.insert_auth_token(&auth_token3);
3358 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003359 assert_eq!(auth_tokens_returned.len(), 2);
3360
3361 Ok(())
3362 }
3363
3364 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003365 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3366 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003367 }
3368
3369 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003370 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003371 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003372 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003373
Janis Danisevskis66784c42021-01-27 08:40:25 -08003374 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003375 let entries = get_keyentry(&db)?;
3376 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003377
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003378 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003379
3380 let entries_new = get_keyentry(&db)?;
3381 assert_eq!(entries, entries_new);
3382 Ok(())
3383 }
3384
3385 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003386 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003387 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3388 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003389 }
3390
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003391 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003392
Janis Danisevskis66784c42021-01-27 08:40:25 -08003393 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3394 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003395
3396 let entries = get_keyentry(&db)?;
3397 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003398 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3399 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003400
3401 // Test that we must pass in a valid Domain.
3402 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003403 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003404 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003405 );
3406 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003407 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003408 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003409 );
3410 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003411 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003412 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003413 );
3414
3415 Ok(())
3416 }
3417
Joel Galenson33c04ad2020-08-03 11:04:38 -07003418 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003419 fn test_add_unsigned_key() -> Result<()> {
3420 let mut db = new_test_db()?;
3421 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3422 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3423 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3424 db.create_attestation_key_entry(
3425 &public_key,
3426 &raw_public_key,
3427 &private_key,
3428 &KEYSTORE_UUID,
3429 )?;
3430 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3431 assert_eq!(keys.len(), 1);
3432 assert_eq!(keys[0], public_key);
3433 Ok(())
3434 }
3435
3436 #[test]
3437 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3438 let mut db = new_test_db()?;
3439 let expiration_date: i64 = 20;
3440 let namespace: i64 = 30;
3441 let base_byte: u8 = 1;
3442 let loaded_values =
3443 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3444 let chain =
3445 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3446 assert_eq!(true, chain.is_some());
3447 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003448 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003449 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3450 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003451 Ok(())
3452 }
3453
3454 #[test]
3455 fn test_get_attestation_pool_status() -> Result<()> {
3456 let mut db = new_test_db()?;
3457 let namespace: i64 = 30;
3458 load_attestation_key_pool(
3459 &mut db, 10, /* expiration */
3460 namespace, 0x01, /* base_byte */
3461 )?;
3462 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3463 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3464 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3465 assert_eq!(status.expiring, 0);
3466 assert_eq!(status.attested, 3);
3467 assert_eq!(status.unassigned, 0);
3468 assert_eq!(status.total, 3);
3469 assert_eq!(
3470 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3471 1
3472 );
3473 assert_eq!(
3474 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3475 2
3476 );
3477 assert_eq!(
3478 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3479 3
3480 );
3481 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3482 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3483 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3484 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003485 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003486 db.create_attestation_key_entry(
3487 &public_key,
3488 &raw_public_key,
3489 &private_key,
3490 &KEYSTORE_UUID,
3491 )?;
3492 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3493 assert_eq!(status.attested, 3);
3494 assert_eq!(status.unassigned, 0);
3495 assert_eq!(status.total, 4);
3496 db.store_signed_attestation_certificate_chain(
3497 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003498 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003499 &cert_chain,
3500 20,
3501 &KEYSTORE_UUID,
3502 )?;
3503 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3504 assert_eq!(status.attested, 4);
3505 assert_eq!(status.unassigned, 1);
3506 assert_eq!(status.total, 4);
3507 Ok(())
3508 }
3509
3510 #[test]
3511 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003512 let temp_dir =
3513 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3514 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003515 let expiration_date: i64 =
3516 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3517 let namespace: i64 = 30;
3518 let namespace_del1: i64 = 45;
3519 let namespace_del2: i64 = 60;
3520 let entry_values = load_attestation_key_pool(
3521 &mut db,
3522 expiration_date,
3523 namespace,
3524 0x01, /* base_byte */
3525 )?;
3526 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3527 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003528
3529 let blob_entry_row_count: u32 = db
3530 .conn
3531 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3532 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003533 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3534 // one key, one certificate chain, and one certificate.
3535 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003536
Max Bires2b2e6562020-09-22 11:22:36 -07003537 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3538
3539 let mut cert_chain =
3540 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003541 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003542 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003543 assert_eq!(entry_values.batch_cert, value.batch_cert);
3544 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003545 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003546
3547 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3548 Domain::APP,
3549 namespace_del1,
3550 &KEYSTORE_UUID,
3551 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003552 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003553 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3554 Domain::APP,
3555 namespace_del2,
3556 &KEYSTORE_UUID,
3557 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003558 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003559
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003560 // Give the garbage collector half a second to catch up.
3561 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003562
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003563 let blob_entry_row_count: u32 = db
3564 .conn
3565 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3566 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003567 // There shound be 3 blob entries left, because we deleted two of the attestation
3568 // key entries with three blobs each.
3569 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003570
Max Bires2b2e6562020-09-22 11:22:36 -07003571 Ok(())
3572 }
3573
3574 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003575 fn test_delete_all_attestation_keys() -> Result<()> {
3576 let mut db = new_test_db()?;
3577 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3578 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3579 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3580 let result = db.delete_all_attestation_keys()?;
3581
3582 // Give the garbage collector half a second to catch up.
3583 std::thread::sleep(Duration::from_millis(500));
3584
3585 // Attestation keys should be deleted, and the regular key should remain.
3586 assert_eq!(result, 2);
3587
3588 Ok(())
3589 }
3590
3591 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003592 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003593 fn extractor(
3594 ke: &KeyEntryRow,
3595 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3596 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003597 }
3598
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003599 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003600 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3601 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003602 let entries = get_keyentry(&db)?;
3603 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003604 assert_eq!(
3605 extractor(&entries[0]),
3606 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3607 );
3608 assert_eq!(
3609 extractor(&entries[1]),
3610 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3611 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003612
3613 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003614 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003615 let entries = get_keyentry(&db)?;
3616 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003617 assert_eq!(
3618 extractor(&entries[0]),
3619 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3620 );
3621 assert_eq!(
3622 extractor(&entries[1]),
3623 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3624 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003625
3626 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003627 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003628 let entries = get_keyentry(&db)?;
3629 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003630 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3631 assert_eq!(
3632 extractor(&entries[1]),
3633 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3634 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003635
3636 // Test that we must pass in a valid Domain.
3637 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003638 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003639 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003640 );
3641 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003642 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003643 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003644 );
3645 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003646 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003647 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003648 );
3649
3650 // Test that we correctly handle setting an alias for something that does not exist.
3651 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003652 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003653 "Expected to update a single entry but instead updated 0",
3654 );
3655 // Test that we correctly abort the transaction in this case.
3656 let entries = get_keyentry(&db)?;
3657 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003658 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3659 assert_eq!(
3660 extractor(&entries[1]),
3661 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3662 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003663
3664 Ok(())
3665 }
3666
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003667 #[test]
3668 fn test_grant_ungrant() -> Result<()> {
3669 const CALLER_UID: u32 = 15;
3670 const GRANTEE_UID: u32 = 12;
3671 const SELINUX_NAMESPACE: i64 = 7;
3672
3673 let mut db = new_test_db()?;
3674 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003675 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3676 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3677 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003678 )?;
3679 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003680 domain: super::Domain::APP,
3681 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003682 alias: Some("key".to_string()),
3683 blob: None,
3684 };
3685 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3686 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3687
3688 // Reset totally predictable random number generator in case we
3689 // are not the first test running on this thread.
3690 reset_random();
3691 let next_random = 0i64;
3692
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003693 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003694 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003695 assert_eq!(*a, PVEC1);
3696 assert_eq!(
3697 *k,
3698 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003699 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003700 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003701 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003702 alias: Some("key".to_string()),
3703 blob: None,
3704 }
3705 );
3706 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003707 })
3708 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003709
3710 assert_eq!(
3711 app_granted_key,
3712 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003713 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003714 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003715 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003716 alias: None,
3717 blob: None,
3718 }
3719 );
3720
3721 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003722 domain: super::Domain::SELINUX,
3723 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003724 alias: Some("yek".to_string()),
3725 blob: None,
3726 };
3727
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003728 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003729 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003730 assert_eq!(*a, PVEC1);
3731 assert_eq!(
3732 *k,
3733 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003734 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003735 // namespace must be the supplied SELinux
3736 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003737 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003738 alias: Some("yek".to_string()),
3739 blob: None,
3740 }
3741 );
3742 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003743 })
3744 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003745
3746 assert_eq!(
3747 selinux_granted_key,
3748 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003749 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003750 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003751 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003752 alias: None,
3753 blob: None,
3754 }
3755 );
3756
3757 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003758 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003759 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003760 assert_eq!(*a, PVEC2);
3761 assert_eq!(
3762 *k,
3763 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003764 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003765 // namespace must be the supplied SELinux
3766 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003767 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003768 alias: Some("yek".to_string()),
3769 blob: None,
3770 }
3771 );
3772 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003773 })
3774 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775
3776 assert_eq!(
3777 selinux_granted_key,
3778 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003779 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003780 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003781 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003782 alias: None,
3783 blob: None,
3784 }
3785 );
3786
3787 {
3788 // Limiting scope of stmt, because it borrows db.
3789 let mut stmt = db
3790 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003791 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003792 let mut rows =
3793 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3794 Ok((
3795 row.get(0)?,
3796 row.get(1)?,
3797 row.get(2)?,
3798 KeyPermSet::from(row.get::<_, i32>(3)?),
3799 ))
3800 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003801
3802 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003803 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003804 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003805 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003806 assert!(rows.next().is_none());
3807 }
3808
3809 debug_dump_keyentry_table(&mut db)?;
3810 println!("app_key {:?}", app_key);
3811 println!("selinux_key {:?}", selinux_key);
3812
Janis Danisevskis66784c42021-01-27 08:40:25 -08003813 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3814 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003815
3816 Ok(())
3817 }
3818
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003819 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003820 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3821 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3822
3823 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003824 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003825 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003826 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003827 let mut blob_metadata = BlobMetaData::new();
3828 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3829 db.set_blob(
3830 &key_id,
3831 SubComponentType::KEY_BLOB,
3832 Some(TEST_KEY_BLOB),
3833 Some(&blob_metadata),
3834 )?;
3835 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3836 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003837 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003838
3839 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003840 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003841 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003842 )?;
3843 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003844 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3845 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003846 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003847 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003848 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003849 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003850 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003851 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003852 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003853
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003854 drop(rows);
3855 drop(stmt);
3856
3857 assert_eq!(
3858 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3859 BlobMetaData::load_from_db(id, tx).no_gc()
3860 })
3861 .expect("Should find blob metadata."),
3862 blob_metadata
3863 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003864 Ok(())
3865 }
3866
3867 static TEST_ALIAS: &str = "my super duper key";
3868
3869 #[test]
3870 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3871 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003872 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003873 .context("test_insert_and_load_full_keyentry_domain_app")?
3874 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003875 let (_key_guard, key_entry) = db
3876 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003877 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003878 domain: Domain::APP,
3879 nspace: 0,
3880 alias: Some(TEST_ALIAS.to_string()),
3881 blob: None,
3882 },
3883 KeyType::Client,
3884 KeyEntryLoadBits::BOTH,
3885 1,
3886 |_k, _av| Ok(()),
3887 )
3888 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003889 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003890
3891 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003892 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003893 domain: Domain::APP,
3894 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003895 alias: Some(TEST_ALIAS.to_string()),
3896 blob: None,
3897 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003898 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003899 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003900 |_, _| Ok(()),
3901 )
3902 .unwrap();
3903
3904 assert_eq!(
3905 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3906 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003907 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003908 domain: Domain::APP,
3909 nspace: 0,
3910 alias: Some(TEST_ALIAS.to_string()),
3911 blob: None,
3912 },
3913 KeyType::Client,
3914 KeyEntryLoadBits::NONE,
3915 1,
3916 |_k, _av| Ok(()),
3917 )
3918 .unwrap_err()
3919 .root_cause()
3920 .downcast_ref::<KsError>()
3921 );
3922
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003923 Ok(())
3924 }
3925
3926 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003927 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3928 let mut db = new_test_db()?;
3929
3930 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003931 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003932 domain: Domain::APP,
3933 nspace: 1,
3934 alias: Some(TEST_ALIAS.to_string()),
3935 blob: None,
3936 },
3937 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003938 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003939 )
3940 .expect("Trying to insert cert.");
3941
3942 let (_key_guard, mut key_entry) = db
3943 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003944 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003945 domain: Domain::APP,
3946 nspace: 1,
3947 alias: Some(TEST_ALIAS.to_string()),
3948 blob: None,
3949 },
3950 KeyType::Client,
3951 KeyEntryLoadBits::PUBLIC,
3952 1,
3953 |_k, _av| Ok(()),
3954 )
3955 .expect("Trying to read certificate entry.");
3956
3957 assert!(key_entry.pure_cert());
3958 assert!(key_entry.cert().is_none());
3959 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3960
3961 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003962 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003963 domain: Domain::APP,
3964 nspace: 1,
3965 alias: Some(TEST_ALIAS.to_string()),
3966 blob: None,
3967 },
3968 KeyType::Client,
3969 1,
3970 |_, _| Ok(()),
3971 )
3972 .unwrap();
3973
3974 assert_eq!(
3975 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3976 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003977 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003978 domain: Domain::APP,
3979 nspace: 1,
3980 alias: Some(TEST_ALIAS.to_string()),
3981 blob: None,
3982 },
3983 KeyType::Client,
3984 KeyEntryLoadBits::NONE,
3985 1,
3986 |_k, _av| Ok(()),
3987 )
3988 .unwrap_err()
3989 .root_cause()
3990 .downcast_ref::<KsError>()
3991 );
3992
3993 Ok(())
3994 }
3995
3996 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003997 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3998 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003999 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004000 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4001 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004002 let (_key_guard, key_entry) = db
4003 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004004 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004005 domain: Domain::SELINUX,
4006 nspace: 1,
4007 alias: Some(TEST_ALIAS.to_string()),
4008 blob: None,
4009 },
4010 KeyType::Client,
4011 KeyEntryLoadBits::BOTH,
4012 1,
4013 |_k, _av| Ok(()),
4014 )
4015 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004016 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004017
4018 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004019 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004020 domain: Domain::SELINUX,
4021 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004022 alias: Some(TEST_ALIAS.to_string()),
4023 blob: None,
4024 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004025 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004026 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004027 |_, _| Ok(()),
4028 )
4029 .unwrap();
4030
4031 assert_eq!(
4032 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4033 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004034 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004035 domain: Domain::SELINUX,
4036 nspace: 1,
4037 alias: Some(TEST_ALIAS.to_string()),
4038 blob: None,
4039 },
4040 KeyType::Client,
4041 KeyEntryLoadBits::NONE,
4042 1,
4043 |_k, _av| Ok(()),
4044 )
4045 .unwrap_err()
4046 .root_cause()
4047 .downcast_ref::<KsError>()
4048 );
4049
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004050 Ok(())
4051 }
4052
4053 #[test]
4054 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4055 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004056 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004057 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4058 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004059 let (_, key_entry) = db
4060 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004061 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004062 KeyType::Client,
4063 KeyEntryLoadBits::BOTH,
4064 1,
4065 |_k, _av| Ok(()),
4066 )
4067 .unwrap();
4068
Qi Wub9433b52020-12-01 14:52:46 +08004069 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004070
4071 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004072 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004073 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004074 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004075 |_, _| Ok(()),
4076 )
4077 .unwrap();
4078
4079 assert_eq!(
4080 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4081 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004082 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004083 KeyType::Client,
4084 KeyEntryLoadBits::NONE,
4085 1,
4086 |_k, _av| Ok(()),
4087 )
4088 .unwrap_err()
4089 .root_cause()
4090 .downcast_ref::<KsError>()
4091 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004092
4093 Ok(())
4094 }
4095
4096 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004097 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4098 let mut db = new_test_db()?;
4099 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4100 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4101 .0;
4102 // Update the usage count of the limited use key.
4103 db.check_and_update_key_usage_count(key_id)?;
4104
4105 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004106 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004107 KeyType::Client,
4108 KeyEntryLoadBits::BOTH,
4109 1,
4110 |_k, _av| Ok(()),
4111 )?;
4112
4113 // The usage count is decremented now.
4114 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4115
4116 Ok(())
4117 }
4118
4119 #[test]
4120 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4121 let mut db = new_test_db()?;
4122 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4123 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4124 .0;
4125 // Update the usage count of the limited use key.
4126 db.check_and_update_key_usage_count(key_id).expect(concat!(
4127 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4128 "This should succeed."
4129 ));
4130
4131 // Try to update the exhausted limited use key.
4132 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4133 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4134 "This should fail."
4135 ));
4136 assert_eq!(
4137 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4138 e.root_cause().downcast_ref::<KsError>().unwrap()
4139 );
4140
4141 Ok(())
4142 }
4143
4144 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004145 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4146 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004147 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004148 .context("test_insert_and_load_full_keyentry_from_grant")?
4149 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004150
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004151 let granted_key = db
4152 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004153 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004154 domain: Domain::APP,
4155 nspace: 0,
4156 alias: Some(TEST_ALIAS.to_string()),
4157 blob: None,
4158 },
4159 1,
4160 2,
4161 key_perm_set![KeyPerm::use_()],
4162 |_k, _av| Ok(()),
4163 )
4164 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004165
4166 debug_dump_grant_table(&mut db)?;
4167
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004168 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004169 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4170 assert_eq!(Domain::GRANT, k.domain);
4171 assert!(av.unwrap().includes(KeyPerm::use_()));
4172 Ok(())
4173 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004174 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004175
Qi Wub9433b52020-12-01 14:52:46 +08004176 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004177
Janis Danisevskis66784c42021-01-27 08:40:25 -08004178 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004179
4180 assert_eq!(
4181 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4182 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004183 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004184 KeyType::Client,
4185 KeyEntryLoadBits::NONE,
4186 2,
4187 |_k, _av| Ok(()),
4188 )
4189 .unwrap_err()
4190 .root_cause()
4191 .downcast_ref::<KsError>()
4192 );
4193
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004194 Ok(())
4195 }
4196
Janis Danisevskis45760022021-01-19 16:34:10 -08004197 // This test attempts to load a key by key id while the caller is not the owner
4198 // but a grant exists for the given key and the caller.
4199 #[test]
4200 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4201 let mut db = new_test_db()?;
4202 const OWNER_UID: u32 = 1u32;
4203 const GRANTEE_UID: u32 = 2u32;
4204 const SOMEONE_ELSE_UID: u32 = 3u32;
4205 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4206 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4207 .0;
4208
4209 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004210 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004211 domain: Domain::APP,
4212 nspace: 0,
4213 alias: Some(TEST_ALIAS.to_string()),
4214 blob: None,
4215 },
4216 OWNER_UID,
4217 GRANTEE_UID,
4218 key_perm_set![KeyPerm::use_()],
4219 |_k, _av| Ok(()),
4220 )
4221 .unwrap();
4222
4223 debug_dump_grant_table(&mut db)?;
4224
4225 let id_descriptor =
4226 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4227
4228 let (_, key_entry) = db
4229 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004230 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004231 KeyType::Client,
4232 KeyEntryLoadBits::BOTH,
4233 GRANTEE_UID,
4234 |k, av| {
4235 assert_eq!(Domain::APP, k.domain);
4236 assert_eq!(OWNER_UID as i64, k.nspace);
4237 assert!(av.unwrap().includes(KeyPerm::use_()));
4238 Ok(())
4239 },
4240 )
4241 .unwrap();
4242
4243 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4244
4245 let (_, key_entry) = db
4246 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004247 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004248 KeyType::Client,
4249 KeyEntryLoadBits::BOTH,
4250 SOMEONE_ELSE_UID,
4251 |k, av| {
4252 assert_eq!(Domain::APP, k.domain);
4253 assert_eq!(OWNER_UID as i64, k.nspace);
4254 assert!(av.is_none());
4255 Ok(())
4256 },
4257 )
4258 .unwrap();
4259
4260 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4261
Janis Danisevskis66784c42021-01-27 08:40:25 -08004262 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004263
4264 assert_eq!(
4265 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4266 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004267 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004268 KeyType::Client,
4269 KeyEntryLoadBits::NONE,
4270 GRANTEE_UID,
4271 |_k, _av| Ok(()),
4272 )
4273 .unwrap_err()
4274 .root_cause()
4275 .downcast_ref::<KsError>()
4276 );
4277
4278 Ok(())
4279 }
4280
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004281 // Creates a key migrates it to a different location and then tries to access it by the old
4282 // and new location.
4283 #[test]
4284 fn test_migrate_key_app_to_app() -> Result<()> {
4285 let mut db = new_test_db()?;
4286 const SOURCE_UID: u32 = 1u32;
4287 const DESTINATION_UID: u32 = 2u32;
4288 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4289 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4290 let key_id_guard =
4291 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4292 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4293
4294 let source_descriptor: KeyDescriptor = KeyDescriptor {
4295 domain: Domain::APP,
4296 nspace: -1,
4297 alias: Some(SOURCE_ALIAS.to_string()),
4298 blob: None,
4299 };
4300
4301 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4302 domain: Domain::APP,
4303 nspace: -1,
4304 alias: Some(DESTINATION_ALIAS.to_string()),
4305 blob: None,
4306 };
4307
4308 let key_id = key_id_guard.id();
4309
4310 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4311 Ok(())
4312 })
4313 .unwrap();
4314
4315 let (_, key_entry) = db
4316 .load_key_entry(
4317 &destination_descriptor,
4318 KeyType::Client,
4319 KeyEntryLoadBits::BOTH,
4320 DESTINATION_UID,
4321 |k, av| {
4322 assert_eq!(Domain::APP, k.domain);
4323 assert_eq!(DESTINATION_UID as i64, k.nspace);
4324 assert!(av.is_none());
4325 Ok(())
4326 },
4327 )
4328 .unwrap();
4329
4330 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4331
4332 assert_eq!(
4333 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4334 db.load_key_entry(
4335 &source_descriptor,
4336 KeyType::Client,
4337 KeyEntryLoadBits::NONE,
4338 SOURCE_UID,
4339 |_k, _av| Ok(()),
4340 )
4341 .unwrap_err()
4342 .root_cause()
4343 .downcast_ref::<KsError>()
4344 );
4345
4346 Ok(())
4347 }
4348
4349 // Creates a key migrates it to a different location and then tries to access it by the old
4350 // and new location.
4351 #[test]
4352 fn test_migrate_key_app_to_selinux() -> Result<()> {
4353 let mut db = new_test_db()?;
4354 const SOURCE_UID: u32 = 1u32;
4355 const DESTINATION_UID: u32 = 2u32;
4356 const DESTINATION_NAMESPACE: i64 = 1000i64;
4357 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4358 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4359 let key_id_guard =
4360 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4361 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4362
4363 let source_descriptor: KeyDescriptor = KeyDescriptor {
4364 domain: Domain::APP,
4365 nspace: -1,
4366 alias: Some(SOURCE_ALIAS.to_string()),
4367 blob: None,
4368 };
4369
4370 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4371 domain: Domain::SELINUX,
4372 nspace: DESTINATION_NAMESPACE,
4373 alias: Some(DESTINATION_ALIAS.to_string()),
4374 blob: None,
4375 };
4376
4377 let key_id = key_id_guard.id();
4378
4379 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4380 Ok(())
4381 })
4382 .unwrap();
4383
4384 let (_, key_entry) = db
4385 .load_key_entry(
4386 &destination_descriptor,
4387 KeyType::Client,
4388 KeyEntryLoadBits::BOTH,
4389 DESTINATION_UID,
4390 |k, av| {
4391 assert_eq!(Domain::SELINUX, k.domain);
4392 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4393 assert!(av.is_none());
4394 Ok(())
4395 },
4396 )
4397 .unwrap();
4398
4399 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4400
4401 assert_eq!(
4402 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4403 db.load_key_entry(
4404 &source_descriptor,
4405 KeyType::Client,
4406 KeyEntryLoadBits::NONE,
4407 SOURCE_UID,
4408 |_k, _av| Ok(()),
4409 )
4410 .unwrap_err()
4411 .root_cause()
4412 .downcast_ref::<KsError>()
4413 );
4414
4415 Ok(())
4416 }
4417
4418 // Creates two keys and tries to migrate the first to the location of the second which
4419 // is expected to fail.
4420 #[test]
4421 fn test_migrate_key_destination_occupied() -> Result<()> {
4422 let mut db = new_test_db()?;
4423 const SOURCE_UID: u32 = 1u32;
4424 const DESTINATION_UID: u32 = 2u32;
4425 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4426 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4427 let key_id_guard =
4428 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4429 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4430 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4431 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4432
4433 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4434 domain: Domain::APP,
4435 nspace: -1,
4436 alias: Some(DESTINATION_ALIAS.to_string()),
4437 blob: None,
4438 };
4439
4440 assert_eq!(
4441 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4442 db.migrate_key_namespace(
4443 key_id_guard,
4444 &destination_descriptor,
4445 DESTINATION_UID,
4446 |_k| Ok(())
4447 )
4448 .unwrap_err()
4449 .root_cause()
4450 .downcast_ref::<KsError>()
4451 );
4452
4453 Ok(())
4454 }
4455
Janis Danisevskisaec14592020-11-12 09:41:49 -08004456 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4457
Janis Danisevskisaec14592020-11-12 09:41:49 -08004458 #[test]
4459 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4460 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004461 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4462 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004463 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004464 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004465 .context("test_insert_and_load_full_keyentry_domain_app")?
4466 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004467 let (_key_guard, key_entry) = db
4468 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004469 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004470 domain: Domain::APP,
4471 nspace: 0,
4472 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4473 blob: None,
4474 },
4475 KeyType::Client,
4476 KeyEntryLoadBits::BOTH,
4477 33,
4478 |_k, _av| Ok(()),
4479 )
4480 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004481 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004482 let state = Arc::new(AtomicU8::new(1));
4483 let state2 = state.clone();
4484
4485 // Spawning a second thread that attempts to acquire the key id lock
4486 // for the same key as the primary thread. The primary thread then
4487 // waits, thereby forcing the secondary thread into the second stage
4488 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4489 // The test succeeds if the secondary thread observes the transition
4490 // of `state` from 1 to 2, despite having a whole second to overtake
4491 // the primary thread.
4492 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004493 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004494 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004495 assert!(db
4496 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004497 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004498 domain: Domain::APP,
4499 nspace: 0,
4500 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4501 blob: None,
4502 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004503 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004504 KeyEntryLoadBits::BOTH,
4505 33,
4506 |_k, _av| Ok(()),
4507 )
4508 .is_ok());
4509 // We should only see a 2 here because we can only return
4510 // from load_key_entry when the `_key_guard` expires,
4511 // which happens at the end of the scope.
4512 assert_eq!(2, state2.load(Ordering::Relaxed));
4513 });
4514
4515 thread::sleep(std::time::Duration::from_millis(1000));
4516
4517 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4518
4519 // Return the handle from this scope so we can join with the
4520 // secondary thread after the key id lock has expired.
4521 handle
4522 // This is where the `_key_guard` goes out of scope,
4523 // which is the reason for concurrent load_key_entry on the same key
4524 // to unblock.
4525 };
4526 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4527 // main test thread. We will not see failing asserts in secondary threads otherwise.
4528 handle.join().unwrap();
4529 Ok(())
4530 }
4531
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004532 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004533 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004534 let temp_dir =
4535 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4536
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004537 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4538 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004539
4540 let _tx1 = db1
4541 .conn
4542 .transaction_with_behavior(TransactionBehavior::Immediate)
4543 .expect("Failed to create first transaction.");
4544
4545 let error = db2
4546 .conn
4547 .transaction_with_behavior(TransactionBehavior::Immediate)
4548 .context("Transaction begin failed.")
4549 .expect_err("This should fail.");
4550 let root_cause = error.root_cause();
4551 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4552 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4553 {
4554 return;
4555 }
4556 panic!(
4557 "Unexpected error {:?} \n{:?} \n{:?}",
4558 error,
4559 root_cause,
4560 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4561 )
4562 }
4563
4564 #[cfg(disabled)]
4565 #[test]
4566 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4567 let temp_dir = Arc::new(
4568 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4569 .expect("Failed to create temp dir."),
4570 );
4571
4572 let test_begin = Instant::now();
4573
4574 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4575 const KEY_COUNT: u32 = 500u32;
4576 const OPEN_DB_COUNT: u32 = 50u32;
4577
4578 let mut actual_key_count = KEY_COUNT;
4579 // First insert KEY_COUNT keys.
4580 for count in 0..KEY_COUNT {
4581 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4582 actual_key_count = count;
4583 break;
4584 }
4585 let alias = format!("test_alias_{}", count);
4586 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4587 .expect("Failed to make key entry.");
4588 }
4589
4590 // Insert more keys from a different thread and into a different namespace.
4591 let temp_dir1 = temp_dir.clone();
4592 let handle1 = thread::spawn(move || {
4593 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4594
4595 for count in 0..actual_key_count {
4596 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4597 return;
4598 }
4599 let alias = format!("test_alias_{}", count);
4600 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4601 .expect("Failed to make key entry.");
4602 }
4603
4604 // then unbind them again.
4605 for count in 0..actual_key_count {
4606 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4607 return;
4608 }
4609 let key = KeyDescriptor {
4610 domain: Domain::APP,
4611 nspace: -1,
4612 alias: Some(format!("test_alias_{}", count)),
4613 blob: None,
4614 };
4615 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4616 }
4617 });
4618
4619 // And start unbinding the first set of keys.
4620 let temp_dir2 = temp_dir.clone();
4621 let handle2 = thread::spawn(move || {
4622 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4623
4624 for count in 0..actual_key_count {
4625 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4626 return;
4627 }
4628 let key = KeyDescriptor {
4629 domain: Domain::APP,
4630 nspace: -1,
4631 alias: Some(format!("test_alias_{}", count)),
4632 blob: None,
4633 };
4634 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4635 }
4636 });
4637
4638 let stop_deleting = Arc::new(AtomicU8::new(0));
4639 let stop_deleting2 = stop_deleting.clone();
4640
4641 // And delete anything that is unreferenced keys.
4642 let temp_dir3 = temp_dir.clone();
4643 let handle3 = thread::spawn(move || {
4644 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4645
4646 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4647 while let Some((key_guard, _key)) =
4648 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4649 {
4650 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4651 return;
4652 }
4653 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4654 }
4655 std::thread::sleep(std::time::Duration::from_millis(100));
4656 }
4657 });
4658
4659 // While a lot of inserting and deleting is going on we have to open database connections
4660 // successfully and use them.
4661 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4662 // out of scope.
4663 #[allow(clippy::redundant_clone)]
4664 let temp_dir4 = temp_dir.clone();
4665 let handle4 = thread::spawn(move || {
4666 for count in 0..OPEN_DB_COUNT {
4667 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4668 return;
4669 }
4670 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4671
4672 let alias = format!("test_alias_{}", count);
4673 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4674 .expect("Failed to make key entry.");
4675 let key = KeyDescriptor {
4676 domain: Domain::APP,
4677 nspace: -1,
4678 alias: Some(alias),
4679 blob: None,
4680 };
4681 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4682 }
4683 });
4684
4685 handle1.join().expect("Thread 1 panicked.");
4686 handle2.join().expect("Thread 2 panicked.");
4687 handle4.join().expect("Thread 4 panicked.");
4688
4689 stop_deleting.store(1, Ordering::Relaxed);
4690 handle3.join().expect("Thread 3 panicked.");
4691
4692 Ok(())
4693 }
4694
4695 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004696 fn list() -> Result<()> {
4697 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004698 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004699 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4700 (Domain::APP, 1, "test1"),
4701 (Domain::APP, 1, "test2"),
4702 (Domain::APP, 1, "test3"),
4703 (Domain::APP, 1, "test4"),
4704 (Domain::APP, 1, "test5"),
4705 (Domain::APP, 1, "test6"),
4706 (Domain::APP, 1, "test7"),
4707 (Domain::APP, 2, "test1"),
4708 (Domain::APP, 2, "test2"),
4709 (Domain::APP, 2, "test3"),
4710 (Domain::APP, 2, "test4"),
4711 (Domain::APP, 2, "test5"),
4712 (Domain::APP, 2, "test6"),
4713 (Domain::APP, 2, "test8"),
4714 (Domain::SELINUX, 100, "test1"),
4715 (Domain::SELINUX, 100, "test2"),
4716 (Domain::SELINUX, 100, "test3"),
4717 (Domain::SELINUX, 100, "test4"),
4718 (Domain::SELINUX, 100, "test5"),
4719 (Domain::SELINUX, 100, "test6"),
4720 (Domain::SELINUX, 100, "test9"),
4721 ];
4722
4723 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4724 .iter()
4725 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004726 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4727 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004728 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4729 });
4730 (entry.id(), *ns)
4731 })
4732 .collect();
4733
4734 for (domain, namespace) in
4735 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4736 {
4737 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4738 .iter()
4739 .filter_map(|(domain, ns, alias)| match ns {
4740 ns if *ns == *namespace => Some(KeyDescriptor {
4741 domain: *domain,
4742 nspace: *ns,
4743 alias: Some(alias.to_string()),
4744 blob: None,
4745 }),
4746 _ => None,
4747 })
4748 .collect();
4749 list_o_descriptors.sort();
4750 let mut list_result = db.list(*domain, *namespace)?;
4751 list_result.sort();
4752 assert_eq!(list_o_descriptors, list_result);
4753
4754 let mut list_o_ids: Vec<i64> = list_o_descriptors
4755 .into_iter()
4756 .map(|d| {
4757 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004758 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004759 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004760 KeyType::Client,
4761 KeyEntryLoadBits::NONE,
4762 *namespace as u32,
4763 |_, _| Ok(()),
4764 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004765 .unwrap();
4766 entry.id()
4767 })
4768 .collect();
4769 list_o_ids.sort_unstable();
4770 let mut loaded_entries: Vec<i64> = list_o_keys
4771 .iter()
4772 .filter_map(|(id, ns)| match ns {
4773 ns if *ns == *namespace => Some(*id),
4774 _ => None,
4775 })
4776 .collect();
4777 loaded_entries.sort_unstable();
4778 assert_eq!(list_o_ids, loaded_entries);
4779 }
4780 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4781
4782 Ok(())
4783 }
4784
Joel Galenson0891bc12020-07-20 10:37:03 -07004785 // Helpers
4786
4787 // Checks that the given result is an error containing the given string.
4788 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4789 let error_str = format!(
4790 "{:#?}",
4791 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4792 );
4793 assert!(
4794 error_str.contains(target),
4795 "The string \"{}\" should contain \"{}\"",
4796 error_str,
4797 target
4798 );
4799 }
4800
Joel Galenson2aab4432020-07-22 15:27:57 -07004801 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004802 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004803 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004804 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004805 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004806 namespace: Option<i64>,
4807 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004808 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004809 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004810 }
4811
4812 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4813 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004814 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004815 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004816 Ok(KeyEntryRow {
4817 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004818 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004819 domain: match row.get(2)? {
4820 Some(i) => Some(Domain(i)),
4821 None => None,
4822 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004823 namespace: row.get(3)?,
4824 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004825 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004826 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004827 })
4828 })?
4829 .map(|r| r.context("Could not read keyentry row."))
4830 .collect::<Result<Vec<_>>>()
4831 }
4832
Max Biresb2e1d032021-02-08 21:35:05 -08004833 struct RemoteProvValues {
4834 cert_chain: Vec<u8>,
4835 priv_key: Vec<u8>,
4836 batch_cert: Vec<u8>,
4837 }
4838
Max Bires2b2e6562020-09-22 11:22:36 -07004839 fn load_attestation_key_pool(
4840 db: &mut KeystoreDB,
4841 expiration_date: i64,
4842 namespace: i64,
4843 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004844 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004845 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4846 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4847 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4848 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004849 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004850 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4851 db.store_signed_attestation_certificate_chain(
4852 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004853 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004854 &cert_chain,
4855 expiration_date,
4856 &KEYSTORE_UUID,
4857 )?;
4858 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004859 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004860 }
4861
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004862 // Note: The parameters and SecurityLevel associations are nonsensical. This
4863 // collection is only used to check if the parameters are preserved as expected by the
4864 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004865 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4866 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004867 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4868 KeyParameter::new(
4869 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4870 SecurityLevel::TRUSTED_ENVIRONMENT,
4871 ),
4872 KeyParameter::new(
4873 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4874 SecurityLevel::TRUSTED_ENVIRONMENT,
4875 ),
4876 KeyParameter::new(
4877 KeyParameterValue::Algorithm(Algorithm::RSA),
4878 SecurityLevel::TRUSTED_ENVIRONMENT,
4879 ),
4880 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4881 KeyParameter::new(
4882 KeyParameterValue::BlockMode(BlockMode::ECB),
4883 SecurityLevel::TRUSTED_ENVIRONMENT,
4884 ),
4885 KeyParameter::new(
4886 KeyParameterValue::BlockMode(BlockMode::GCM),
4887 SecurityLevel::TRUSTED_ENVIRONMENT,
4888 ),
4889 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4890 KeyParameter::new(
4891 KeyParameterValue::Digest(Digest::MD5),
4892 SecurityLevel::TRUSTED_ENVIRONMENT,
4893 ),
4894 KeyParameter::new(
4895 KeyParameterValue::Digest(Digest::SHA_2_224),
4896 SecurityLevel::TRUSTED_ENVIRONMENT,
4897 ),
4898 KeyParameter::new(
4899 KeyParameterValue::Digest(Digest::SHA_2_256),
4900 SecurityLevel::STRONGBOX,
4901 ),
4902 KeyParameter::new(
4903 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4904 SecurityLevel::TRUSTED_ENVIRONMENT,
4905 ),
4906 KeyParameter::new(
4907 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4908 SecurityLevel::TRUSTED_ENVIRONMENT,
4909 ),
4910 KeyParameter::new(
4911 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4912 SecurityLevel::STRONGBOX,
4913 ),
4914 KeyParameter::new(
4915 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4916 SecurityLevel::TRUSTED_ENVIRONMENT,
4917 ),
4918 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4919 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4920 KeyParameter::new(
4921 KeyParameterValue::EcCurve(EcCurve::P_224),
4922 SecurityLevel::TRUSTED_ENVIRONMENT,
4923 ),
4924 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4925 KeyParameter::new(
4926 KeyParameterValue::EcCurve(EcCurve::P_384),
4927 SecurityLevel::TRUSTED_ENVIRONMENT,
4928 ),
4929 KeyParameter::new(
4930 KeyParameterValue::EcCurve(EcCurve::P_521),
4931 SecurityLevel::TRUSTED_ENVIRONMENT,
4932 ),
4933 KeyParameter::new(
4934 KeyParameterValue::RSAPublicExponent(3),
4935 SecurityLevel::TRUSTED_ENVIRONMENT,
4936 ),
4937 KeyParameter::new(
4938 KeyParameterValue::IncludeUniqueID,
4939 SecurityLevel::TRUSTED_ENVIRONMENT,
4940 ),
4941 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4942 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4943 KeyParameter::new(
4944 KeyParameterValue::ActiveDateTime(1234567890),
4945 SecurityLevel::STRONGBOX,
4946 ),
4947 KeyParameter::new(
4948 KeyParameterValue::OriginationExpireDateTime(1234567890),
4949 SecurityLevel::TRUSTED_ENVIRONMENT,
4950 ),
4951 KeyParameter::new(
4952 KeyParameterValue::UsageExpireDateTime(1234567890),
4953 SecurityLevel::TRUSTED_ENVIRONMENT,
4954 ),
4955 KeyParameter::new(
4956 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4957 SecurityLevel::TRUSTED_ENVIRONMENT,
4958 ),
4959 KeyParameter::new(
4960 KeyParameterValue::MaxUsesPerBoot(1234567890),
4961 SecurityLevel::TRUSTED_ENVIRONMENT,
4962 ),
4963 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4964 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4965 KeyParameter::new(
4966 KeyParameterValue::NoAuthRequired,
4967 SecurityLevel::TRUSTED_ENVIRONMENT,
4968 ),
4969 KeyParameter::new(
4970 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4971 SecurityLevel::TRUSTED_ENVIRONMENT,
4972 ),
4973 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4974 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4975 KeyParameter::new(
4976 KeyParameterValue::TrustedUserPresenceRequired,
4977 SecurityLevel::TRUSTED_ENVIRONMENT,
4978 ),
4979 KeyParameter::new(
4980 KeyParameterValue::TrustedConfirmationRequired,
4981 SecurityLevel::TRUSTED_ENVIRONMENT,
4982 ),
4983 KeyParameter::new(
4984 KeyParameterValue::UnlockedDeviceRequired,
4985 SecurityLevel::TRUSTED_ENVIRONMENT,
4986 ),
4987 KeyParameter::new(
4988 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4989 SecurityLevel::SOFTWARE,
4990 ),
4991 KeyParameter::new(
4992 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4993 SecurityLevel::SOFTWARE,
4994 ),
4995 KeyParameter::new(
4996 KeyParameterValue::CreationDateTime(12345677890),
4997 SecurityLevel::SOFTWARE,
4998 ),
4999 KeyParameter::new(
5000 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5001 SecurityLevel::TRUSTED_ENVIRONMENT,
5002 ),
5003 KeyParameter::new(
5004 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5005 SecurityLevel::TRUSTED_ENVIRONMENT,
5006 ),
5007 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5008 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5009 KeyParameter::new(
5010 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5011 SecurityLevel::SOFTWARE,
5012 ),
5013 KeyParameter::new(
5014 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5015 SecurityLevel::TRUSTED_ENVIRONMENT,
5016 ),
5017 KeyParameter::new(
5018 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5019 SecurityLevel::TRUSTED_ENVIRONMENT,
5020 ),
5021 KeyParameter::new(
5022 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5023 SecurityLevel::TRUSTED_ENVIRONMENT,
5024 ),
5025 KeyParameter::new(
5026 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5027 SecurityLevel::TRUSTED_ENVIRONMENT,
5028 ),
5029 KeyParameter::new(
5030 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5031 SecurityLevel::TRUSTED_ENVIRONMENT,
5032 ),
5033 KeyParameter::new(
5034 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5035 SecurityLevel::TRUSTED_ENVIRONMENT,
5036 ),
5037 KeyParameter::new(
5038 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5039 SecurityLevel::TRUSTED_ENVIRONMENT,
5040 ),
5041 KeyParameter::new(
5042 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5043 SecurityLevel::TRUSTED_ENVIRONMENT,
5044 ),
5045 KeyParameter::new(
5046 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5047 SecurityLevel::TRUSTED_ENVIRONMENT,
5048 ),
5049 KeyParameter::new(
5050 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5051 SecurityLevel::TRUSTED_ENVIRONMENT,
5052 ),
5053 KeyParameter::new(
5054 KeyParameterValue::VendorPatchLevel(3),
5055 SecurityLevel::TRUSTED_ENVIRONMENT,
5056 ),
5057 KeyParameter::new(
5058 KeyParameterValue::BootPatchLevel(4),
5059 SecurityLevel::TRUSTED_ENVIRONMENT,
5060 ),
5061 KeyParameter::new(
5062 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5063 SecurityLevel::TRUSTED_ENVIRONMENT,
5064 ),
5065 KeyParameter::new(
5066 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5067 SecurityLevel::TRUSTED_ENVIRONMENT,
5068 ),
5069 KeyParameter::new(
5070 KeyParameterValue::MacLength(256),
5071 SecurityLevel::TRUSTED_ENVIRONMENT,
5072 ),
5073 KeyParameter::new(
5074 KeyParameterValue::ResetSinceIdRotation,
5075 SecurityLevel::TRUSTED_ENVIRONMENT,
5076 ),
5077 KeyParameter::new(
5078 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5079 SecurityLevel::TRUSTED_ENVIRONMENT,
5080 ),
Qi Wub9433b52020-12-01 14:52:46 +08005081 ];
5082 if let Some(value) = max_usage_count {
5083 params.push(KeyParameter::new(
5084 KeyParameterValue::UsageCountLimit(value),
5085 SecurityLevel::SOFTWARE,
5086 ));
5087 }
5088 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005089 }
5090
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005091 fn make_test_key_entry(
5092 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005093 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005094 namespace: i64,
5095 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005096 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005097 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005098 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005099 let mut blob_metadata = BlobMetaData::new();
5100 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5101 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5102 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5103 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5104 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5105
5106 db.set_blob(
5107 &key_id,
5108 SubComponentType::KEY_BLOB,
5109 Some(TEST_KEY_BLOB),
5110 Some(&blob_metadata),
5111 )?;
5112 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5113 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005114
5115 let params = make_test_params(max_usage_count);
5116 db.insert_keyparameter(&key_id, &params)?;
5117
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005118 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005119 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005120 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005121 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005122 Ok(key_id)
5123 }
5124
Qi Wub9433b52020-12-01 14:52:46 +08005125 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5126 let params = make_test_params(max_usage_count);
5127
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005128 let mut blob_metadata = BlobMetaData::new();
5129 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5130 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5131 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5132 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5133 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5134
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005135 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005136 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005137
5138 KeyEntry {
5139 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005140 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005141 cert: Some(TEST_CERT_BLOB.to_vec()),
5142 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005143 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005144 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005145 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005146 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005147 }
5148 }
5149
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005150 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005151 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005152 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005153 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005154 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005155 NO_PARAMS,
5156 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005157 Ok((
5158 row.get(0)?,
5159 row.get(1)?,
5160 row.get(2)?,
5161 row.get(3)?,
5162 row.get(4)?,
5163 row.get(5)?,
5164 row.get(6)?,
5165 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005166 },
5167 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005168
5169 println!("Key entry table rows:");
5170 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005171 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005172 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005173 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5174 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005175 );
5176 }
5177 Ok(())
5178 }
5179
5180 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005181 let mut stmt = db
5182 .conn
5183 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005184 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5185 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5186 })?;
5187
5188 println!("Grant table rows:");
5189 for r in rows {
5190 let (id, gt, ki, av) = r.unwrap();
5191 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5192 }
5193 Ok(())
5194 }
5195
Joel Galenson0891bc12020-07-20 10:37:03 -07005196 // Use a custom random number generator that repeats each number once.
5197 // This allows us to test repeated elements.
5198
5199 thread_local! {
5200 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5201 }
5202
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005203 fn reset_random() {
5204 RANDOM_COUNTER.with(|counter| {
5205 *counter.borrow_mut() = 0;
5206 })
5207 }
5208
Joel Galenson0891bc12020-07-20 10:37:03 -07005209 pub fn random() -> i64 {
5210 RANDOM_COUNTER.with(|counter| {
5211 let result = *counter.borrow() / 2;
5212 *counter.borrow_mut() += 1;
5213 result
5214 })
5215 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005216
5217 #[test]
5218 fn test_last_off_body() -> Result<()> {
5219 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005220 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005221 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005222 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005223 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005224 let one_second = Duration::from_secs(1);
5225 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005226 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005227 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005228 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005229 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005230 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005231 Ok(())
5232 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005233
5234 #[test]
5235 fn test_unbind_keys_for_user() -> Result<()> {
5236 let mut db = new_test_db()?;
5237 db.unbind_keys_for_user(1, false)?;
5238
5239 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5240 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5241 db.unbind_keys_for_user(2, false)?;
5242
5243 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5244 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5245
5246 db.unbind_keys_for_user(1, true)?;
5247 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5248
5249 Ok(())
5250 }
5251
5252 #[test]
5253 fn test_store_super_key() -> Result<()> {
5254 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005255 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005256 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005257 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005258 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005259 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005260
5261 let (encrypted_super_key, metadata) =
5262 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005263 db.store_super_key(
5264 1,
5265 &USER_SUPER_KEY,
5266 &encrypted_super_key,
5267 &metadata,
5268 &KeyMetaData::new(),
5269 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005270
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005271 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005272 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005273
Paul Crowley7a658392021-03-18 17:08:20 -07005274 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005275 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5276 USER_SUPER_KEY.algorithm,
5277 key_entry,
5278 &pw,
5279 None,
5280 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005281
Paul Crowley7a658392021-03-18 17:08:20 -07005282 let decrypted_secret_bytes =
5283 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5284 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005285 Ok(())
5286 }
Seth Moore78c091f2021-04-09 21:38:30 +00005287
5288 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5289 vec![
5290 StatsdStorageType::KeyEntry,
5291 StatsdStorageType::KeyEntryIdIndex,
5292 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5293 StatsdStorageType::BlobEntry,
5294 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5295 StatsdStorageType::KeyParameter,
5296 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5297 StatsdStorageType::KeyMetadata,
5298 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5299 StatsdStorageType::Grant,
5300 StatsdStorageType::AuthToken,
5301 StatsdStorageType::BlobMetadata,
5302 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5303 ]
5304 }
5305
5306 /// Perform a simple check to ensure that we can query all the storage types
5307 /// that are supported by the DB. Check for reasonable values.
5308 #[test]
5309 fn test_query_all_valid_table_sizes() -> Result<()> {
5310 const PAGE_SIZE: i64 = 4096;
5311
5312 let mut db = new_test_db()?;
5313
5314 for t in get_valid_statsd_storage_types() {
5315 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005316 // AuthToken can be less than a page since it's in a btree, not sqlite
5317 // TODO(b/187474736) stop using if-let here
5318 if let StatsdStorageType::AuthToken = t {
5319 } else {
5320 assert!(stat.size >= PAGE_SIZE);
5321 }
Seth Moore78c091f2021-04-09 21:38:30 +00005322 assert!(stat.size >= stat.unused_size);
5323 }
5324
5325 Ok(())
5326 }
5327
5328 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5329 get_valid_statsd_storage_types()
5330 .into_iter()
5331 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5332 .collect()
5333 }
5334
5335 fn assert_storage_increased(
5336 db: &mut KeystoreDB,
5337 increased_storage_types: Vec<StatsdStorageType>,
5338 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5339 ) {
5340 for storage in increased_storage_types {
5341 // Verify the expected storage increased.
5342 let new = db.get_storage_stat(storage).unwrap();
5343 let storage = storage as i32;
5344 let old = &baseline[&storage];
5345 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5346 assert!(
5347 new.unused_size <= old.unused_size,
5348 "{}: {} <= {}",
5349 storage,
5350 new.unused_size,
5351 old.unused_size
5352 );
5353
5354 // Update the baseline with the new value so that it succeeds in the
5355 // later comparison.
5356 baseline.insert(storage, new);
5357 }
5358
5359 // Get an updated map of the storage and verify there were no unexpected changes.
5360 let updated_stats = get_storage_stats_map(db);
5361 assert_eq!(updated_stats.len(), baseline.len());
5362
5363 for &k in baseline.keys() {
5364 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5365 let mut s = String::new();
5366 for &k in map.keys() {
5367 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5368 .expect("string concat failed");
5369 }
5370 s
5371 };
5372
5373 assert!(
5374 updated_stats[&k].size == baseline[&k].size
5375 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5376 "updated_stats:\n{}\nbaseline:\n{}",
5377 stringify(&updated_stats),
5378 stringify(&baseline)
5379 );
5380 }
5381 }
5382
5383 #[test]
5384 fn test_verify_key_table_size_reporting() -> Result<()> {
5385 let mut db = new_test_db()?;
5386 let mut working_stats = get_storage_stats_map(&mut db);
5387
5388 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5389 assert_storage_increased(
5390 &mut db,
5391 vec![
5392 StatsdStorageType::KeyEntry,
5393 StatsdStorageType::KeyEntryIdIndex,
5394 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5395 ],
5396 &mut working_stats,
5397 );
5398
5399 let mut blob_metadata = BlobMetaData::new();
5400 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5401 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5402 assert_storage_increased(
5403 &mut db,
5404 vec![
5405 StatsdStorageType::BlobEntry,
5406 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5407 StatsdStorageType::BlobMetadata,
5408 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5409 ],
5410 &mut working_stats,
5411 );
5412
5413 let params = make_test_params(None);
5414 db.insert_keyparameter(&key_id, &params)?;
5415 assert_storage_increased(
5416 &mut db,
5417 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5418 &mut working_stats,
5419 );
5420
5421 let mut metadata = KeyMetaData::new();
5422 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5423 db.insert_key_metadata(&key_id, &metadata)?;
5424 assert_storage_increased(
5425 &mut db,
5426 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5427 &mut working_stats,
5428 );
5429
5430 let mut sum = 0;
5431 for stat in working_stats.values() {
5432 sum += stat.size;
5433 }
5434 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5435 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5436
5437 Ok(())
5438 }
5439
5440 #[test]
5441 fn test_verify_auth_table_size_reporting() -> Result<()> {
5442 let mut db = new_test_db()?;
5443 let mut working_stats = get_storage_stats_map(&mut db);
5444 db.insert_auth_token(&HardwareAuthToken {
5445 challenge: 123,
5446 userId: 456,
5447 authenticatorId: 789,
5448 authenticatorType: kmhw_authenticator_type::ANY,
5449 timestamp: Timestamp { milliSeconds: 10 },
5450 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005451 });
Seth Moore78c091f2021-04-09 21:38:30 +00005452 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5453 Ok(())
5454 }
5455
5456 #[test]
5457 fn test_verify_grant_table_size_reporting() -> Result<()> {
5458 const OWNER: i64 = 1;
5459 let mut db = new_test_db()?;
5460 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5461
5462 let mut working_stats = get_storage_stats_map(&mut db);
5463 db.grant(
5464 &KeyDescriptor {
5465 domain: Domain::APP,
5466 nspace: 0,
5467 alias: Some(TEST_ALIAS.to_string()),
5468 blob: None,
5469 },
5470 OWNER as u32,
5471 123,
5472 key_perm_set![KeyPerm::use_()],
5473 |_, _| Ok(()),
5474 )?;
5475
5476 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5477
5478 Ok(())
5479 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005480
5481 #[test]
5482 fn find_auth_token_entry_returns_latest() -> Result<()> {
5483 let mut db = new_test_db()?;
5484 db.insert_auth_token(&HardwareAuthToken {
5485 challenge: 123,
5486 userId: 456,
5487 authenticatorId: 789,
5488 authenticatorType: kmhw_authenticator_type::ANY,
5489 timestamp: Timestamp { milliSeconds: 10 },
5490 mac: b"mac0".to_vec(),
5491 });
5492 std::thread::sleep(std::time::Duration::from_millis(1));
5493 db.insert_auth_token(&HardwareAuthToken {
5494 challenge: 123,
5495 userId: 457,
5496 authenticatorId: 789,
5497 authenticatorType: kmhw_authenticator_type::ANY,
5498 timestamp: Timestamp { milliSeconds: 12 },
5499 mac: b"mac1".to_vec(),
5500 });
5501 std::thread::sleep(std::time::Duration::from_millis(1));
5502 db.insert_auth_token(&HardwareAuthToken {
5503 challenge: 123,
5504 userId: 458,
5505 authenticatorId: 789,
5506 authenticatorType: kmhw_authenticator_type::ANY,
5507 timestamp: Timestamp { milliSeconds: 3 },
5508 mac: b"mac2".to_vec(),
5509 });
5510 // All three entries are in the database
5511 assert_eq!(db.perboot.auth_tokens_len(), 3);
5512 // It selected the most recent timestamp
5513 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5514 Ok(())
5515 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005516
5517 #[test]
5518 fn test_set_wal_mode() -> Result<()> {
5519 let temp_dir = TempDir::new("test_set_wal_mode")?;
5520 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5521 let mode: String =
5522 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5523 row.get(0)
5524 })?;
5525 assert_eq!(mode, "delete");
5526 db.conn.close().expect("Close didn't work");
5527
5528 KeystoreDB::set_wal_mode(temp_dir.path())?;
5529
5530 db = KeystoreDB::new(temp_dir.path(), None)?;
5531 let mode: String =
5532 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5533 row.get(0)
5534 })?;
5535 assert_eq!(mode, "wal");
5536 Ok(())
5537 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01005538
5539 #[test]
5540 fn test_load_key_descriptor() -> Result<()> {
5541 let mut db = new_test_db()?;
5542 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5543
5544 let key = db.load_key_descriptor(key_id)?.unwrap();
5545
5546 assert_eq!(key.domain, Domain::APP);
5547 assert_eq!(key.nspace, 1);
5548 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5549
5550 // No such id
5551 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5552 Ok(())
5553 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005554}