blob: a6c16e93c2a10dd4b653b0b6c0c832a76e1261d8 [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::{
Joel Galensonff79e362021-05-25 16:30:17 -070082 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080083 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| {
Joel Galensonff79e362021-05-25 16:30:17 -07001019 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001020 .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,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001484 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001485 km_uuid: &Uuid,
1486 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001487 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1488
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001489 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001490 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001491 })
1492 .context("In create_key_entry.")
1493 }
1494
1495 fn create_key_entry_internal(
1496 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001497 domain: &Domain,
1498 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001499 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001500 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001501 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001502 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001503 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001504 _ => {
1505 return Err(KsError::sys())
1506 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1507 }
1508 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001509 Ok(KEY_ID_LOCK.get(
1510 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001511 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001512 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001513 (id, key_type, domain, namespace, alias, state, km_uuid)
1514 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001515 params![
1516 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001517 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001518 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001519 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001520 KeyLifeCycle::Existing,
1521 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001522 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001523 )
1524 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001526 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001527 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001528
Max Bires2b2e6562020-09-22 11:22:36 -07001529 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1530 /// The key id gets associated with a domain and namespace later but not with an alias. The
1531 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1532 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1533 /// a key.
1534 pub fn create_attestation_key_entry(
1535 &mut self,
1536 maced_public_key: &[u8],
1537 raw_public_key: &[u8],
1538 private_key: &[u8],
1539 km_uuid: &Uuid,
1540 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001541 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1542
Max Bires2b2e6562020-09-22 11:22:36 -07001543 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1544 let key_id = KEY_ID_LOCK.get(
1545 Self::insert_with_retry(|id| {
1546 tx.execute(
1547 "INSERT into persistent.keyentry
1548 (id, key_type, domain, namespace, alias, state, km_uuid)
1549 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1550 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1551 )
1552 })
1553 .context("In create_key_entry")?,
1554 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001555 Self::set_blob_internal(
1556 &tx,
1557 key_id.0,
1558 SubComponentType::KEY_BLOB,
1559 Some(private_key),
1560 None,
1561 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001562 let mut metadata = KeyMetaData::new();
1563 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1564 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1565 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001566 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001567 })
1568 .context("In create_attestation_key_entry")
1569 }
1570
Janis Danisevskis377d1002021-01-27 19:07:48 -08001571 /// Set a new blob and associates it with the given key id. Each blob
1572 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001573 /// Each key can have one of each sub component type associated. If more
1574 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001575 /// will get garbage collected.
1576 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1577 /// removed by setting blob to None.
1578 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001579 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001580 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001581 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001582 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001583 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001584 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001585 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1586
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001587 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001588 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001589 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001590 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001591 }
1592
Janis Danisevskiseed69842021-02-18 20:04:10 -08001593 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1594 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1595 /// We use this to insert key blobs into the database which can then be garbage collected
1596 /// lazily by the key garbage collector.
1597 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001598 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1599
Janis Danisevskiseed69842021-02-18 20:04:10 -08001600 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1601 Self::set_blob_internal(
1602 &tx,
1603 Self::UNASSIGNED_KEY_ID,
1604 SubComponentType::KEY_BLOB,
1605 Some(blob),
1606 Some(blob_metadata),
1607 )
1608 .need_gc()
1609 })
1610 .context("In set_deleted_blob.")
1611 }
1612
Janis Danisevskis377d1002021-01-27 19:07:48 -08001613 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001614 tx: &Transaction,
1615 key_id: i64,
1616 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001617 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001618 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001619 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001620 match (blob, sc_type) {
1621 (Some(blob), _) => {
1622 tx.execute(
1623 "INSERT INTO persistent.blobentry
1624 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1625 params![sc_type, key_id, blob],
1626 )
1627 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001628 if let Some(blob_metadata) = blob_metadata {
1629 let blob_id = tx
1630 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1631 row.get(0)
1632 })
1633 .context("In set_blob_internal: Failed to get new blob id.")?;
1634 blob_metadata
1635 .store_in_db(blob_id, tx)
1636 .context("In set_blob_internal: Trying to store blob metadata.")?;
1637 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001638 }
1639 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1640 tx.execute(
1641 "DELETE FROM persistent.blobentry
1642 WHERE subcomponent_type = ? AND keyentryid = ?;",
1643 params![sc_type, key_id],
1644 )
1645 .context("In set_blob_internal: Failed to delete blob.")?;
1646 }
1647 (None, _) => {
1648 return Err(KsError::sys())
1649 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1650 }
1651 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001652 Ok(())
1653 }
1654
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001655 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1656 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001657 #[cfg(test)]
1658 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001659 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001660 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001661 })
1662 .context("In insert_keyparameter.")
1663 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001664
Janis Danisevskis66784c42021-01-27 08:40:25 -08001665 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001666 tx: &Transaction,
1667 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001668 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001669 ) -> Result<()> {
1670 let mut stmt = tx
1671 .prepare(
1672 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1673 VALUES (?, ?, ?, ?);",
1674 )
1675 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1676
Janis Danisevskis66784c42021-01-27 08:40:25 -08001677 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001678 stmt.insert(params![
1679 key_id.0,
1680 p.get_tag().0,
1681 p.key_parameter_value(),
1682 p.security_level().0
1683 ])
1684 .with_context(|| {
1685 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1686 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001687 }
1688 Ok(())
1689 }
1690
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001691 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001692 #[cfg(test)]
1693 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001694 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001695 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001696 })
1697 .context("In insert_key_metadata.")
1698 }
1699
Max Bires2b2e6562020-09-22 11:22:36 -07001700 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1701 /// on the public key.
1702 pub fn store_signed_attestation_certificate_chain(
1703 &mut self,
1704 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001705 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001706 cert_chain: &[u8],
1707 expiration_date: i64,
1708 km_uuid: &Uuid,
1709 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001710 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1711
Max Bires2b2e6562020-09-22 11:22:36 -07001712 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1713 let mut stmt = tx
1714 .prepare(
1715 "SELECT keyentryid
1716 FROM persistent.keymetadata
1717 WHERE tag = ? AND data = ? AND keyentryid IN
1718 (SELECT id
1719 FROM persistent.keyentry
1720 WHERE
1721 alias IS NULL AND
1722 domain IS NULL AND
1723 namespace IS NULL AND
1724 key_type = ? AND
1725 km_uuid = ?);",
1726 )
1727 .context("Failed to store attestation certificate chain.")?;
1728 let mut rows = stmt
1729 .query(params![
1730 KeyMetaData::AttestationRawPubKey,
1731 raw_public_key,
1732 KeyType::Attestation,
1733 km_uuid
1734 ])
1735 .context("Failed to fetch keyid")?;
1736 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1737 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1738 .get(0)
1739 .context("Failed to unpack id.")
1740 })
1741 .context("Failed to get key_id.")?;
1742 let num_updated = tx
1743 .execute(
1744 "UPDATE persistent.keyentry
1745 SET alias = ?
1746 WHERE id = ?;",
1747 params!["signed", key_id],
1748 )
1749 .context("Failed to update alias.")?;
1750 if num_updated != 1 {
1751 return Err(KsError::sys()).context("Alias not updated for the key.");
1752 }
1753 let mut metadata = KeyMetaData::new();
1754 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1755 expiration_date,
1756 )));
1757 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001758 Self::set_blob_internal(
1759 &tx,
1760 key_id,
1761 SubComponentType::CERT_CHAIN,
1762 Some(cert_chain),
1763 None,
1764 )
1765 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001766 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1767 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001768 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001769 })
1770 .context("In store_signed_attestation_certificate_chain: ")
1771 }
1772
1773 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1774 /// currently have a key assigned to it.
1775 pub fn assign_attestation_key(
1776 &mut self,
1777 domain: Domain,
1778 namespace: i64,
1779 km_uuid: &Uuid,
1780 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001781 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1782
Max Bires2b2e6562020-09-22 11:22:36 -07001783 match domain {
1784 Domain::APP | Domain::SELINUX => {}
1785 _ => {
1786 return Err(KsError::sys()).context(format!(
1787 concat!(
1788 "In assign_attestation_key: Domain {:?} ",
1789 "must be either App or SELinux.",
1790 ),
1791 domain
1792 ));
1793 }
1794 }
1795 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1796 let result = tx
1797 .execute(
1798 "UPDATE persistent.keyentry
1799 SET domain=?1, namespace=?2
1800 WHERE
1801 id =
1802 (SELECT MIN(id)
1803 FROM persistent.keyentry
1804 WHERE ALIAS IS NOT NULL
1805 AND domain IS NULL
1806 AND key_type IS ?3
1807 AND state IS ?4
1808 AND km_uuid IS ?5)
1809 AND
1810 (SELECT COUNT(*)
1811 FROM persistent.keyentry
1812 WHERE domain=?1
1813 AND namespace=?2
1814 AND key_type IS ?3
1815 AND state IS ?4
1816 AND km_uuid IS ?5) = 0;",
1817 params![
1818 domain.0 as u32,
1819 namespace,
1820 KeyType::Attestation,
1821 KeyLifeCycle::Live,
1822 km_uuid,
1823 ],
1824 )
1825 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001826 if result == 0 {
1827 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1828 } else if result > 1 {
1829 return Err(KsError::sys())
1830 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001831 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001832 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001833 })
1834 .context("In assign_attestation_key: ")
1835 }
1836
1837 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1838 /// provisioning server, or the maximum number available if there are not num_keys number of
1839 /// entries in the table.
1840 pub fn fetch_unsigned_attestation_keys(
1841 &mut self,
1842 num_keys: i32,
1843 km_uuid: &Uuid,
1844 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001845 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1846
Max Bires2b2e6562020-09-22 11:22:36 -07001847 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1848 let mut stmt = tx
1849 .prepare(
1850 "SELECT data
1851 FROM persistent.keymetadata
1852 WHERE tag = ? AND keyentryid IN
1853 (SELECT id
1854 FROM persistent.keyentry
1855 WHERE
1856 alias IS NULL AND
1857 domain IS NULL AND
1858 namespace IS NULL AND
1859 key_type = ? AND
1860 km_uuid = ?
1861 LIMIT ?);",
1862 )
1863 .context("Failed to prepare statement")?;
1864 let rows = stmt
1865 .query_map(
1866 params![
1867 KeyMetaData::AttestationMacedPublicKey,
1868 KeyType::Attestation,
1869 km_uuid,
1870 num_keys
1871 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001872 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001873 )?
1874 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1875 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001876 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001877 })
1878 .context("In fetch_unsigned_attestation_keys")
1879 }
1880
1881 /// Removes any keys that have expired as of the current time. Returns the number of keys
1882 /// marked unreferenced that are bound to be garbage collected.
1883 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001884 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1885
Max Bires2b2e6562020-09-22 11:22:36 -07001886 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1887 let mut stmt = tx
1888 .prepare(
1889 "SELECT keyentryid, data
1890 FROM persistent.keymetadata
1891 WHERE tag = ? AND keyentryid IN
1892 (SELECT id
1893 FROM persistent.keyentry
1894 WHERE key_type = ?);",
1895 )
1896 .context("Failed to prepare query")?;
1897 let key_ids_to_check = stmt
1898 .query_map(
1899 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1900 |row| Ok((row.get(0)?, row.get(1)?)),
1901 )?
1902 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1903 .context("Failed to get date metadata")?;
1904 let curr_time = DateTime::from_millis_epoch(
1905 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1906 );
1907 let mut num_deleted = 0;
1908 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1909 if Self::mark_unreferenced(&tx, id)? {
1910 num_deleted += 1;
1911 }
1912 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001913 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001914 })
1915 .context("In delete_expired_attestation_keys: ")
1916 }
1917
Max Bires60d7ed12021-03-05 15:59:22 -08001918 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1919 /// they are in. This is useful primarily as a testing mechanism.
1920 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001921 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1922
Max Bires60d7ed12021-03-05 15:59:22 -08001923 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1924 let mut stmt = tx
1925 .prepare(
1926 "SELECT id FROM persistent.keyentry
1927 WHERE key_type IS ?;",
1928 )
1929 .context("Failed to prepare statement")?;
1930 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001931 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001932 .collect::<rusqlite::Result<Vec<i64>>>()
1933 .context("Failed to execute statement")?;
1934 let num_deleted = keys_to_delete
1935 .iter()
1936 .map(|id| Self::mark_unreferenced(&tx, *id))
1937 .collect::<Result<Vec<bool>>>()
1938 .context("Failed to execute mark_unreferenced on a keyid")?
1939 .into_iter()
1940 .filter(|result| *result)
1941 .count() as i64;
1942 Ok(num_deleted).do_gc(num_deleted != 0)
1943 })
1944 .context("In delete_all_attestation_keys: ")
1945 }
1946
Max Bires2b2e6562020-09-22 11:22:36 -07001947 /// Counts the number of keys that will expire by the provided epoch date and the number of
1948 /// keys not currently assigned to a domain.
1949 pub fn get_attestation_pool_status(
1950 &mut self,
1951 date: i64,
1952 km_uuid: &Uuid,
1953 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001954 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1955
Max Bires2b2e6562020-09-22 11:22:36 -07001956 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1957 let mut stmt = tx.prepare(
1958 "SELECT data
1959 FROM persistent.keymetadata
1960 WHERE tag = ? AND keyentryid IN
1961 (SELECT id
1962 FROM persistent.keyentry
1963 WHERE alias IS NOT NULL
1964 AND key_type = ?
1965 AND km_uuid = ?
1966 AND state = ?);",
1967 )?;
1968 let times = stmt
1969 .query_map(
1970 params![
1971 KeyMetaData::AttestationExpirationDate,
1972 KeyType::Attestation,
1973 km_uuid,
1974 KeyLifeCycle::Live
1975 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001976 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001977 )?
1978 .collect::<rusqlite::Result<Vec<DateTime>>>()
1979 .context("Failed to execute metadata statement")?;
1980 let expiring =
1981 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1982 as i32;
1983 stmt = tx.prepare(
1984 "SELECT alias, domain
1985 FROM persistent.keyentry
1986 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1987 )?;
1988 let rows = stmt
1989 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1990 Ok((row.get(0)?, row.get(1)?))
1991 })?
1992 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1993 .context("Failed to execute keyentry statement")?;
1994 let mut unassigned = 0i32;
1995 let mut attested = 0i32;
1996 let total = rows.len() as i32;
1997 for (alias, domain) in rows {
1998 match (alias, domain) {
1999 (Some(_alias), None) => {
2000 attested += 1;
2001 unassigned += 1;
2002 }
2003 (Some(_alias), Some(_domain)) => {
2004 attested += 1;
2005 }
2006 _ => {}
2007 }
2008 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002009 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002010 })
2011 .context("In get_attestation_pool_status: ")
2012 }
2013
2014 /// Fetches the private key and corresponding certificate chain assigned to a
2015 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2016 /// not assigned, or one CertificateChain.
2017 pub fn retrieve_attestation_key_and_cert_chain(
2018 &mut self,
2019 domain: Domain,
2020 namespace: i64,
2021 km_uuid: &Uuid,
2022 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002023 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2024
Max Bires2b2e6562020-09-22 11:22:36 -07002025 match domain {
2026 Domain::APP | Domain::SELINUX => {}
2027 _ => {
2028 return Err(KsError::sys())
2029 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2030 }
2031 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002032 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2033 let mut stmt = tx.prepare(
2034 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002035 FROM persistent.blobentry
2036 WHERE keyentryid IN
2037 (SELECT id
2038 FROM persistent.keyentry
2039 WHERE key_type = ?
2040 AND domain = ?
2041 AND namespace = ?
2042 AND state = ?
2043 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002044 )?;
2045 let rows = stmt
2046 .query_map(
2047 params![
2048 KeyType::Attestation,
2049 domain.0 as u32,
2050 namespace,
2051 KeyLifeCycle::Live,
2052 km_uuid
2053 ],
2054 |row| Ok((row.get(0)?, row.get(1)?)),
2055 )?
2056 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002057 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002058 if rows.is_empty() {
2059 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002060 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002061 return Err(KsError::sys()).context(format!(
2062 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002063 "Expected to get a single attestation",
2064 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2065 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002066 rows.len()
2067 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002068 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002069 let mut km_blob: Vec<u8> = Vec::new();
2070 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002071 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002072 for row in rows {
2073 let sub_type: SubComponentType = row.0;
2074 match sub_type {
2075 SubComponentType::KEY_BLOB => {
2076 km_blob = row.1;
2077 }
2078 SubComponentType::CERT_CHAIN => {
2079 cert_chain_blob = row.1;
2080 }
Max Biresb2e1d032021-02-08 21:35:05 -08002081 SubComponentType::CERT => {
2082 batch_cert_blob = row.1;
2083 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002084 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2085 }
2086 }
2087 Ok(Some(CertificateChain {
2088 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002089 batch_cert: batch_cert_blob,
2090 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002091 }))
2092 .no_gc()
2093 })
Max Biresb2e1d032021-02-08 21:35:05 -08002094 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002095 }
2096
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002097 /// Updates the alias column of the given key id `newid` with the given alias,
2098 /// and atomically, removes the alias, domain, and namespace from another row
2099 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002100 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2101 /// collector.
2102 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002103 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002104 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002105 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002106 domain: &Domain,
2107 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002108 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002109 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002110 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002111 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002112 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002113 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002114 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002115 domain
2116 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002117 }
2118 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002119 let updated = tx
2120 .execute(
2121 "UPDATE persistent.keyentry
2122 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002123 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2124 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002125 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002126 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002127 let result = tx
2128 .execute(
2129 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002130 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002131 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002132 params![
2133 alias,
2134 KeyLifeCycle::Live,
2135 newid.0,
2136 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002137 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002138 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002139 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002140 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002141 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002142 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002143 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002144 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002145 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002146 result
2147 ));
2148 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002149 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002150 }
2151
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002152 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2153 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2154 pub fn migrate_key_namespace(
2155 &mut self,
2156 key_id_guard: KeyIdGuard,
2157 destination: &KeyDescriptor,
2158 caller_uid: u32,
2159 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2160 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002161 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2162
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002163 let destination = match destination.domain {
2164 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2165 Domain::SELINUX => (*destination).clone(),
2166 domain => {
2167 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2168 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2169 }
2170 };
2171
2172 // Security critical: Must return immediately on failure. Do not remove the '?';
2173 check_permission(&destination)
2174 .context("In migrate_key_namespace: Trying to check permission.")?;
2175
2176 let alias = destination
2177 .alias
2178 .as_ref()
2179 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2180 .context("In migrate_key_namespace: Alias must be specified.")?;
2181
2182 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2183 // Query the destination location. If there is a key, the migration request fails.
2184 if tx
2185 .query_row(
2186 "SELECT id FROM persistent.keyentry
2187 WHERE alias = ? AND domain = ? AND namespace = ?;",
2188 params![alias, destination.domain.0, destination.nspace],
2189 |_| Ok(()),
2190 )
2191 .optional()
2192 .context("Failed to query destination.")?
2193 .is_some()
2194 {
2195 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2196 .context("Target already exists.");
2197 }
2198
2199 let updated = tx
2200 .execute(
2201 "UPDATE persistent.keyentry
2202 SET alias = ?, domain = ?, namespace = ?
2203 WHERE id = ?;",
2204 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2205 )
2206 .context("Failed to update key entry.")?;
2207
2208 if updated != 1 {
2209 return Err(KsError::sys())
2210 .context(format!("Update succeeded, but {} rows were updated.", updated));
2211 }
2212 Ok(()).no_gc()
2213 })
2214 .context("In migrate_key_namespace:")
2215 }
2216
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002217 /// Store a new key in a single transaction.
2218 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2219 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002220 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2221 /// is now unreferenced and needs to be collected.
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002222 #[allow(clippy::clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002223 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002224 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002225 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002226 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002227 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002228 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002229 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002230 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002231 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002232 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002233 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2234
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002235 let (alias, domain, namespace) = match key {
2236 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2237 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2238 (alias, key.domain, nspace)
2239 }
2240 _ => {
2241 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2242 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2243 }
2244 };
2245 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002246 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002247 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002248 let (blob, blob_metadata) = *blob_info;
2249 Self::set_blob_internal(
2250 tx,
2251 key_id.id(),
2252 SubComponentType::KEY_BLOB,
2253 Some(blob),
2254 Some(&blob_metadata),
2255 )
2256 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002257 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002258 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002259 .context("Trying to insert the certificate.")?;
2260 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002261 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002262 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002263 tx,
2264 key_id.id(),
2265 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002266 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002267 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002268 )
2269 .context("Trying to insert the certificate chain.")?;
2270 }
2271 Self::insert_keyparameter_internal(tx, &key_id, params)
2272 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002273 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002274 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace, key_type)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002275 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002276 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002277 })
2278 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002279 }
2280
Janis Danisevskis377d1002021-01-27 19:07:48 -08002281 /// Store a new certificate
2282 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2283 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002284 pub fn store_new_certificate(
2285 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002286 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002287 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002288 cert: &[u8],
2289 km_uuid: &Uuid,
2290 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002291 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2292
Janis Danisevskis377d1002021-01-27 19:07:48 -08002293 let (alias, domain, namespace) = match key {
2294 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2295 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2296 (alias, key.domain, nspace)
2297 }
2298 _ => {
2299 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2300 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2301 )
2302 }
2303 };
2304 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002305 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002306 .context("Trying to create new key entry.")?;
2307
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002308 Self::set_blob_internal(
2309 tx,
2310 key_id.id(),
2311 SubComponentType::CERT_CHAIN,
2312 Some(cert),
2313 None,
2314 )
2315 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002316
2317 let mut metadata = KeyMetaData::new();
2318 metadata.add(KeyMetaEntry::CreationDate(
2319 DateTime::now().context("Trying to make creation time.")?,
2320 ));
2321
2322 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2323
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002324 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002325 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002326 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002327 })
2328 .context("In store_new_certificate.")
2329 }
2330
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002331 // Helper function loading the key_id given the key descriptor
2332 // tuple comprising domain, namespace, and alias.
2333 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002334 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002335 let alias = key
2336 .alias
2337 .as_ref()
2338 .map_or_else(|| Err(KsError::sys()), Ok)
2339 .context("In load_key_entry_id: Alias must be specified.")?;
2340 let mut stmt = tx
2341 .prepare(
2342 "SELECT id FROM persistent.keyentry
2343 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002344 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002345 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002346 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002347 AND alias = ?
2348 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002349 )
2350 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2351 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002352 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002353 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002354 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002355 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002356 .get(0)
2357 .context("Failed to unpack id.")
2358 })
2359 .context("In load_key_entry_id.")
2360 }
2361
2362 /// This helper function completes the access tuple of a key, which is required
2363 /// to perform access control. The strategy depends on the `domain` field in the
2364 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002365 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002366 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002367 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002368 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002369 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002370 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002371 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002372 /// `namespace`.
2373 /// In each case the information returned is sufficient to perform the access
2374 /// check and the key id can be used to load further key artifacts.
2375 fn load_access_tuple(
2376 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002377 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002378 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002379 caller_uid: u32,
2380 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2381 match key.domain {
2382 // Domain App or SELinux. In this case we load the key_id from
2383 // the keyentry database for further loading of key components.
2384 // We already have the full access tuple to perform access control.
2385 // The only distinction is that we use the caller_uid instead
2386 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002387 // Domain::APP.
2388 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002389 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002390 if access_key.domain == Domain::APP {
2391 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002392 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002393 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002394 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002395
2396 Ok((key_id, access_key, None))
2397 }
2398
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002399 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002400 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002401 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002402 let mut stmt = tx
2403 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002404 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002405 WHERE grantee = ? AND id = ? AND
2406 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002407 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002408 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002409 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002410 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002411 .context("Domain:Grant: query failed.")?;
2412 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002413 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002414 let r =
2415 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002416 Ok((
2417 r.get(0).context("Failed to unpack key_id.")?,
2418 r.get(1).context("Failed to unpack access_vector.")?,
2419 ))
2420 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002421 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002422 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002423 }
2424
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002425 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002426 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002427 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002428 let (domain, namespace): (Domain, i64) = {
2429 let mut stmt = tx
2430 .prepare(
2431 "SELECT domain, namespace FROM persistent.keyentry
2432 WHERE
2433 id = ?
2434 AND state = ?;",
2435 )
2436 .context("Domain::KEY_ID: prepare statement failed")?;
2437 let mut rows = stmt
2438 .query(params![key.nspace, KeyLifeCycle::Live])
2439 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002440 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002441 let r =
2442 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002443 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002444 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002445 r.get(1).context("Failed to unpack namespace.")?,
2446 ))
2447 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002448 .context("Domain::KEY_ID.")?
2449 };
2450
2451 // We may use a key by id after loading it by grant.
2452 // In this case we have to check if the caller has a grant for this particular
2453 // key. We can skip this if we already know that the caller is the owner.
2454 // But we cannot know this if domain is anything but App. E.g. in the case
2455 // of Domain::SELINUX we have to speculatively check for grants because we have to
2456 // consult the SEPolicy before we know if the caller is the owner.
2457 let access_vector: Option<KeyPermSet> =
2458 if domain != Domain::APP || namespace != caller_uid as i64 {
2459 let access_vector: Option<i32> = tx
2460 .query_row(
2461 "SELECT access_vector FROM persistent.grant
2462 WHERE grantee = ? AND keyentryid = ?;",
2463 params![caller_uid as i64, key.nspace],
2464 |row| row.get(0),
2465 )
2466 .optional()
2467 .context("Domain::KEY_ID: query grant failed.")?;
2468 access_vector.map(|p| p.into())
2469 } else {
2470 None
2471 };
2472
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002473 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002474 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002475 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002476 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002477
Janis Danisevskis45760022021-01-19 16:34:10 -08002478 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002479 }
2480 _ => Err(anyhow!(KsError::sys())),
2481 }
2482 }
2483
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002484 fn load_blob_components(
2485 key_id: i64,
2486 load_bits: KeyEntryLoadBits,
2487 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002488 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002489 let mut stmt = tx
2490 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002491 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002492 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2493 )
2494 .context("In load_blob_components: prepare statement failed.")?;
2495
2496 let mut rows =
2497 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2498
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002499 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002500 let mut cert_blob: Option<Vec<u8>> = None;
2501 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002502 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002503 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002504 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002505 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002506 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002507 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2508 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002509 key_blob = Some((
2510 row.get(0).context("Failed to extract key blob id.")?,
2511 row.get(2).context("Failed to extract key blob.")?,
2512 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002513 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002514 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002515 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002516 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002517 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002518 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002519 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002520 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002521 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002522 (SubComponentType::CERT, _, _)
2523 | (SubComponentType::CERT_CHAIN, _, _)
2524 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002525 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2526 }
2527 Ok(())
2528 })
2529 .context("In load_blob_components.")?;
2530
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002531 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2532 Ok(Some((
2533 blob,
2534 BlobMetaData::load_from_db(blob_id, tx)
2535 .context("In load_blob_components: Trying to load blob_metadata.")?,
2536 )))
2537 })?;
2538
2539 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002540 }
2541
2542 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2543 let mut stmt = tx
2544 .prepare(
2545 "SELECT tag, data, security_level from persistent.keyparameter
2546 WHERE keyentryid = ?;",
2547 )
2548 .context("In load_key_parameters: prepare statement failed.")?;
2549
2550 let mut parameters: Vec<KeyParameter> = Vec::new();
2551
2552 let mut rows =
2553 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002554 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002555 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2556 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002557 parameters.push(
2558 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2559 .context("Failed to read KeyParameter.")?,
2560 );
2561 Ok(())
2562 })
2563 .context("In load_key_parameters.")?;
2564
2565 Ok(parameters)
2566 }
2567
Qi Wub9433b52020-12-01 14:52:46 +08002568 /// Decrements the usage count of a limited use key. This function first checks whether the
2569 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2570 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2571 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002572 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002573 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2574
Qi Wub9433b52020-12-01 14:52:46 +08002575 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2576 let limit: Option<i32> = tx
2577 .query_row(
2578 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2579 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2580 |row| row.get(0),
2581 )
2582 .optional()
2583 .context("Trying to load usage count")?;
2584
2585 let limit = limit
2586 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2587 .context("The Key no longer exists. Key is exhausted.")?;
2588
2589 tx.execute(
2590 "UPDATE persistent.keyparameter
2591 SET data = data - 1
2592 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2593 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2594 )
2595 .context("Failed to update key usage count.")?;
2596
2597 match limit {
2598 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002599 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002600 .context("Trying to mark limited use key for deletion."),
2601 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002602 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002603 }
2604 })
2605 .context("In check_and_update_key_usage_count.")
2606 }
2607
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002608 /// Load a key entry by the given key descriptor.
2609 /// It uses the `check_permission` callback to verify if the access is allowed
2610 /// given the key access tuple read from the database using `load_access_tuple`.
2611 /// With `load_bits` the caller may specify which blobs shall be loaded from
2612 /// the blob database.
2613 pub fn load_key_entry(
2614 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002615 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002616 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002617 load_bits: KeyEntryLoadBits,
2618 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002619 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2620 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002621 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2622
Janis Danisevskis66784c42021-01-27 08:40:25 -08002623 loop {
2624 match self.load_key_entry_internal(
2625 key,
2626 key_type,
2627 load_bits,
2628 caller_uid,
2629 &check_permission,
2630 ) {
2631 Ok(result) => break Ok(result),
2632 Err(e) => {
2633 if Self::is_locked_error(&e) {
2634 std::thread::sleep(std::time::Duration::from_micros(500));
2635 continue;
2636 } else {
2637 return Err(e).context("In load_key_entry.");
2638 }
2639 }
2640 }
2641 }
2642 }
2643
2644 fn load_key_entry_internal(
2645 &mut self,
2646 key: &KeyDescriptor,
2647 key_type: KeyType,
2648 load_bits: KeyEntryLoadBits,
2649 caller_uid: u32,
2650 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002651 ) -> Result<(KeyIdGuard, KeyEntry)> {
2652 // KEY ID LOCK 1/2
2653 // If we got a key descriptor with a key id we can get the lock right away.
2654 // Otherwise we have to defer it until we know the key id.
2655 let key_id_guard = match key.domain {
2656 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2657 _ => None,
2658 };
2659
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002660 let tx = self
2661 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002662 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002663 .context("In load_key_entry: Failed to initialize transaction.")?;
2664
2665 // Load the key_id and complete the access control tuple.
2666 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002667 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2668 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002669
2670 // Perform access control. It is vital that we return here if the permission is denied.
2671 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002672 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002673
Janis Danisevskisaec14592020-11-12 09:41:49 -08002674 // KEY ID LOCK 2/2
2675 // If we did not get a key id lock by now, it was because we got a key descriptor
2676 // without a key id. At this point we got the key id, so we can try and get a lock.
2677 // However, we cannot block here, because we are in the middle of the transaction.
2678 // So first we try to get the lock non blocking. If that fails, we roll back the
2679 // transaction and block until we get the lock. After we successfully got the lock,
2680 // we start a new transaction and load the access tuple again.
2681 //
2682 // We don't need to perform access control again, because we already established
2683 // that the caller had access to the given key. But we need to make sure that the
2684 // key id still exists. So we have to load the key entry by key id this time.
2685 let (key_id_guard, tx) = match key_id_guard {
2686 None => match KEY_ID_LOCK.try_get(key_id) {
2687 None => {
2688 // Roll back the transaction.
2689 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002690
Janis Danisevskisaec14592020-11-12 09:41:49 -08002691 // Block until we have a key id lock.
2692 let key_id_guard = KEY_ID_LOCK.get(key_id);
2693
2694 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002695 let tx = self
2696 .conn
2697 .unchecked_transaction()
2698 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002699
2700 Self::load_access_tuple(
2701 &tx,
2702 // This time we have to load the key by the retrieved key id, because the
2703 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002704 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002705 domain: Domain::KEY_ID,
2706 nspace: key_id,
2707 ..Default::default()
2708 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002709 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002710 caller_uid,
2711 )
2712 .context("In load_key_entry. (deferred key lock)")?;
2713 (key_id_guard, tx)
2714 }
2715 Some(l) => (l, tx),
2716 },
2717 Some(key_id_guard) => (key_id_guard, tx),
2718 };
2719
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002720 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2721 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002722
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002723 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2724
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002725 Ok((key_id_guard, key_entry))
2726 }
2727
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002728 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002729 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002730 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2731 .context("Trying to delete keyentry.")?;
2732 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2733 .context("Trying to delete keymetadata.")?;
2734 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2735 .context("Trying to delete keyparameters.")?;
2736 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2737 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002738 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002739 }
2740
2741 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002742 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002743 pub fn unbind_key(
2744 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002745 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002746 key_type: KeyType,
2747 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002748 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002749 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002750 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2751
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002752 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2753 let (key_id, access_key_descriptor, access_vector) =
2754 Self::load_access_tuple(tx, key, key_type, caller_uid)
2755 .context("Trying to get access tuple.")?;
2756
2757 // Perform access control. It is vital that we return here if the permission is denied.
2758 // So do not touch that '?' at the end.
2759 check_permission(&access_key_descriptor, access_vector)
2760 .context("While checking permission.")?;
2761
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002762 Self::mark_unreferenced(tx, key_id)
2763 .map(|need_gc| (need_gc, ()))
2764 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002765 })
2766 .context("In unbind_key.")
2767 }
2768
Max Bires8e93d2b2021-01-14 13:17:59 -08002769 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2770 tx.query_row(
2771 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2772 params![key_id],
2773 |row| row.get(0),
2774 )
2775 .context("In get_key_km_uuid.")
2776 }
2777
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002778 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2779 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2780 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002781 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2782
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002783 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2784 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2785 .context("In unbind_keys_for_namespace.");
2786 }
2787 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2788 tx.execute(
2789 "DELETE FROM persistent.keymetadata
2790 WHERE keyentryid IN (
2791 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002792 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002793 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002794 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002795 )
2796 .context("Trying to delete keymetadata.")?;
2797 tx.execute(
2798 "DELETE FROM persistent.keyparameter
2799 WHERE keyentryid IN (
2800 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002801 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002802 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002803 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002804 )
2805 .context("Trying to delete keyparameters.")?;
2806 tx.execute(
2807 "DELETE FROM persistent.grant
2808 WHERE keyentryid IN (
2809 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002810 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002811 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002812 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002813 )
2814 .context("Trying to delete grants.")?;
2815 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002816 "DELETE FROM persistent.keyentry
2817 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2818 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002819 )
2820 .context("Trying to delete keyentry.")?;
2821 Ok(()).need_gc()
2822 })
2823 .context("In unbind_keys_for_namespace")
2824 }
2825
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002826 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2827 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2828 {
2829 tx.execute(
2830 "DELETE FROM persistent.keymetadata
2831 WHERE keyentryid IN (
2832 SELECT id FROM persistent.keyentry
2833 WHERE state = ?
2834 );",
2835 params![KeyLifeCycle::Unreferenced],
2836 )
2837 .context("Trying to delete keymetadata.")?;
2838 tx.execute(
2839 "DELETE FROM persistent.keyparameter
2840 WHERE keyentryid IN (
2841 SELECT id FROM persistent.keyentry
2842 WHERE state = ?
2843 );",
2844 params![KeyLifeCycle::Unreferenced],
2845 )
2846 .context("Trying to delete keyparameters.")?;
2847 tx.execute(
2848 "DELETE FROM persistent.grant
2849 WHERE keyentryid IN (
2850 SELECT id FROM persistent.keyentry
2851 WHERE state = ?
2852 );",
2853 params![KeyLifeCycle::Unreferenced],
2854 )
2855 .context("Trying to delete grants.")?;
2856 tx.execute(
2857 "DELETE FROM persistent.keyentry
2858 WHERE state = ?;",
2859 params![KeyLifeCycle::Unreferenced],
2860 )
2861 .context("Trying to delete keyentry.")?;
2862 Result::<()>::Ok(())
2863 }
2864 .context("In cleanup_unreferenced")
2865 }
2866
Hasini Gunasingheda895552021-01-27 19:34:37 +00002867 /// Delete the keys created on behalf of the user, denoted by the user id.
2868 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2869 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2870 /// The caller of this function should notify the gc if the returned value is true.
2871 pub fn unbind_keys_for_user(
2872 &mut self,
2873 user_id: u32,
2874 keep_non_super_encrypted_keys: bool,
2875 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002876 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2877
Hasini Gunasingheda895552021-01-27 19:34:37 +00002878 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2879 let mut stmt = tx
2880 .prepare(&format!(
2881 "SELECT id from persistent.keyentry
2882 WHERE (
2883 key_type = ?
2884 AND domain = ?
2885 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2886 AND state = ?
2887 ) OR (
2888 key_type = ?
2889 AND namespace = ?
2890 AND alias = ?
2891 AND state = ?
2892 );",
2893 aid_user_offset = AID_USER_OFFSET
2894 ))
2895 .context(concat!(
2896 "In unbind_keys_for_user. ",
2897 "Failed to prepare the query to find the keys created by apps."
2898 ))?;
2899
2900 let mut rows = stmt
2901 .query(params![
2902 // WHERE client key:
2903 KeyType::Client,
2904 Domain::APP.0 as u32,
2905 user_id,
2906 KeyLifeCycle::Live,
2907 // OR super key:
2908 KeyType::Super,
2909 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002910 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002911 KeyLifeCycle::Live
2912 ])
2913 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2914
2915 let mut key_ids: Vec<i64> = Vec::new();
2916 db_utils::with_rows_extract_all(&mut rows, |row| {
2917 key_ids
2918 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2919 Ok(())
2920 })
2921 .context("In unbind_keys_for_user.")?;
2922
2923 let mut notify_gc = false;
2924 for key_id in key_ids {
2925 if keep_non_super_encrypted_keys {
2926 // Load metadata and filter out non-super-encrypted keys.
2927 if let (_, Some((_, blob_metadata)), _, _) =
2928 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2929 .context("In unbind_keys_for_user: Trying to load blob info.")?
2930 {
2931 if blob_metadata.encrypted_by().is_none() {
2932 continue;
2933 }
2934 }
2935 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002936 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002937 .context("In unbind_keys_for_user.")?
2938 || notify_gc;
2939 }
2940 Ok(()).do_gc(notify_gc)
2941 })
2942 .context("In unbind_keys_for_user.")
2943 }
2944
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002945 fn load_key_components(
2946 tx: &Transaction,
2947 load_bits: KeyEntryLoadBits,
2948 key_id: i64,
2949 ) -> Result<KeyEntry> {
2950 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2951
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002952 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002953 Self::load_blob_components(key_id, load_bits, &tx)
2954 .context("In load_key_components.")?;
2955
Max Bires8e93d2b2021-01-14 13:17:59 -08002956 let parameters = Self::load_key_parameters(key_id, &tx)
2957 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002958
Max Bires8e93d2b2021-01-14 13:17:59 -08002959 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2960 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002961
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002962 Ok(KeyEntry {
2963 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002964 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002965 cert: cert_blob,
2966 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002967 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002968 parameters,
2969 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002970 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002971 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002972 }
2973
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002974 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2975 /// The key descriptors will have the domain, nspace, and alias field set.
2976 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07002977 pub fn list(
2978 &mut self,
2979 domain: Domain,
2980 namespace: i64,
2981 key_type: KeyType,
2982 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002983 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2984
Janis Danisevskis66784c42021-01-27 08:40:25 -08002985 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2986 let mut stmt = tx
2987 .prepare(
2988 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002989 WHERE domain = ?
2990 AND namespace = ?
2991 AND alias IS NOT NULL
2992 AND state = ?
2993 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002994 )
2995 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002996
Janis Danisevskis66784c42021-01-27 08:40:25 -08002997 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07002998 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08002999 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003000
Janis Danisevskis66784c42021-01-27 08:40:25 -08003001 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3002 db_utils::with_rows_extract_all(&mut rows, |row| {
3003 descriptors.push(KeyDescriptor {
3004 domain,
3005 nspace: namespace,
3006 alias: Some(row.get(0).context("Trying to extract alias.")?),
3007 blob: None,
3008 });
3009 Ok(())
3010 })
3011 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003012 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003013 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003014 }
3015
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003016 /// Adds a grant to the grant table.
3017 /// Like `load_key_entry` this function loads the access tuple before
3018 /// it uses the callback for a permission check. Upon success,
3019 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3020 /// grant table. The new row will have a randomized id, which is used as
3021 /// grant id in the namespace field of the resulting KeyDescriptor.
3022 pub fn grant(
3023 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003024 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003025 caller_uid: u32,
3026 grantee_uid: u32,
3027 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003028 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003029 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003030 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3031
Janis Danisevskis66784c42021-01-27 08:40:25 -08003032 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3033 // Load the key_id and complete the access control tuple.
3034 // We ignore the access vector here because grants cannot be granted.
3035 // The access vector returned here expresses the permissions the
3036 // grantee has if key.domain == Domain::GRANT. But this vector
3037 // cannot include the grant permission by design, so there is no way the
3038 // subsequent permission check can pass.
3039 // We could check key.domain == Domain::GRANT and fail early.
3040 // But even if we load the access tuple by grant here, the permission
3041 // check denies the attempt to create a grant by grant descriptor.
3042 let (key_id, access_key_descriptor, _) =
3043 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3044 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003045
Janis Danisevskis66784c42021-01-27 08:40:25 -08003046 // Perform access control. It is vital that we return here if the permission
3047 // was denied. So do not touch that '?' at the end of the line.
3048 // This permission check checks if the caller has the grant permission
3049 // for the given key and in addition to all of the permissions
3050 // expressed in `access_vector`.
3051 check_permission(&access_key_descriptor, &access_vector)
3052 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003053
Janis Danisevskis66784c42021-01-27 08:40:25 -08003054 let grant_id = if let Some(grant_id) = tx
3055 .query_row(
3056 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003057 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003058 params![key_id, grantee_uid],
3059 |row| row.get(0),
3060 )
3061 .optional()
3062 .context("In grant: Failed get optional existing grant id.")?
3063 {
3064 tx.execute(
3065 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003066 SET access_vector = ?
3067 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003068 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003069 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003070 .context("In grant: Failed to update existing grant.")?;
3071 grant_id
3072 } else {
3073 Self::insert_with_retry(|id| {
3074 tx.execute(
3075 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3076 VALUES (?, ?, ?, ?);",
3077 params![id, grantee_uid, key_id, i32::from(access_vector)],
3078 )
3079 })
3080 .context("In grant")?
3081 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003082
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003084 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003085 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003086 }
3087
3088 /// This function checks permissions like `grant` and `load_key_entry`
3089 /// before removing a grant from the grant table.
3090 pub fn ungrant(
3091 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003092 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003093 caller_uid: u32,
3094 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003096 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003097 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3098
Janis Danisevskis66784c42021-01-27 08:40:25 -08003099 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3100 // Load the key_id and complete the access control tuple.
3101 // We ignore the access vector here because grants cannot be granted.
3102 let (key_id, access_key_descriptor, _) =
3103 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3104 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003105
Janis Danisevskis66784c42021-01-27 08:40:25 -08003106 // Perform access control. We must return here if the permission
3107 // was denied. So do not touch the '?' at the end of this line.
3108 check_permission(&access_key_descriptor)
3109 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003110
Janis Danisevskis66784c42021-01-27 08:40:25 -08003111 tx.execute(
3112 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003113 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003114 params![key_id, grantee_uid],
3115 )
3116 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003117
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003118 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003119 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003120 }
3121
Joel Galenson845f74b2020-09-09 14:11:55 -07003122 // Generates a random id and passes it to the given function, which will
3123 // try to insert it into a database. If that insertion fails, retry;
3124 // otherwise return the id.
3125 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3126 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003127 let newid: i64 = match random() {
3128 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3129 i => i,
3130 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003131 match inserter(newid) {
3132 // If the id already existed, try again.
3133 Err(rusqlite::Error::SqliteFailure(
3134 libsqlite3_sys::Error {
3135 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3136 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3137 },
3138 _,
3139 )) => (),
3140 Err(e) => {
3141 return Err(e).context("In insert_with_retry: failed to insert into database.")
3142 }
3143 _ => return Ok(newid),
3144 }
3145 }
3146 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003147
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003148 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3149 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3150 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3151 auth_token.clone(),
3152 MonotonicRawTime::now(),
3153 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003154 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003155
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003156 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003157 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003158 where
3159 F: Fn(&AuthTokenEntry) -> bool,
3160 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003161 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003162 }
3163
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003164 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003165 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3166 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003167 }
3168
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003169 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003170 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3171 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003172 }
3173
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003174 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003175 fn get_last_off_body(&self) -> MonotonicRawTime {
3176 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003177 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003178
3179 /// Load descriptor of a key by key id
3180 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3181 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3182
3183 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3184 tx.query_row(
3185 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3186 params![key_id],
3187 |row| {
3188 Ok(KeyDescriptor {
3189 domain: Domain(row.get(0)?),
3190 nspace: row.get(1)?,
3191 alias: row.get(2)?,
3192 blob: None,
3193 })
3194 },
3195 )
3196 .optional()
3197 .context("Trying to load key descriptor")
3198 .no_gc()
3199 })
3200 .context("In load_key_descriptor.")
3201 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003202}
3203
3204#[cfg(test)]
3205mod tests {
3206
3207 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003208 use crate::key_parameter::{
3209 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3210 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3211 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003212 use crate::key_perm_set;
3213 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003214 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003215 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003216 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3217 HardwareAuthToken::HardwareAuthToken,
3218 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003219 };
3220 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003221 Timestamp::Timestamp,
3222 };
Seth Moore472fcbb2021-05-12 10:07:51 -07003223 use rusqlite::DatabaseName::Attached;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003224 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003225 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003226 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003227 use std::collections::BTreeMap;
3228 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003229 use std::sync::atomic::{AtomicU8, Ordering};
3230 use std::sync::Arc;
3231 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003232 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003233 #[cfg(disabled)]
3234 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003235
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003236 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003237 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003238
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003239 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003240 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003241 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003242 })?;
3243 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003244 }
3245
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003246 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3247 where
3248 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3249 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003250 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003251
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003252 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003253 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003254
Janis Danisevskis3395f862021-05-06 10:54:17 -07003255 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003256 }
3257
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003258 fn rebind_alias(
3259 db: &mut KeystoreDB,
3260 newid: &KeyIdGuard,
3261 alias: &str,
3262 domain: Domain,
3263 namespace: i64,
3264 ) -> Result<bool> {
3265 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003266 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003267 })
3268 .context("In rebind_alias.")
3269 }
3270
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003271 #[test]
3272 fn datetime() -> Result<()> {
3273 let conn = Connection::open_in_memory()?;
3274 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3275 let now = SystemTime::now();
3276 let duration = Duration::from_secs(1000);
3277 let then = now.checked_sub(duration).unwrap();
3278 let soon = now.checked_add(duration).unwrap();
3279 conn.execute(
3280 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3281 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3282 )?;
3283 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3284 let mut rows = stmt.query(NO_PARAMS)?;
3285 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3286 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3287 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3288 assert!(rows.next()?.is_none());
3289 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3290 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3291 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3292 Ok(())
3293 }
3294
Joel Galenson0891bc12020-07-20 10:37:03 -07003295 // Ensure that we're using the "injected" random function, not the real one.
3296 #[test]
3297 fn test_mocked_random() {
3298 let rand1 = random();
3299 let rand2 = random();
3300 let rand3 = random();
3301 if rand1 == rand2 {
3302 assert_eq!(rand2 + 1, rand3);
3303 } else {
3304 assert_eq!(rand1 + 1, rand2);
3305 assert_eq!(rand2, rand3);
3306 }
3307 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003308
Joel Galenson26f4d012020-07-17 14:57:21 -07003309 // Test that we have the correct tables.
3310 #[test]
3311 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003312 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003313 let tables = db
3314 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003315 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003316 .query_map(params![], |row| row.get(0))?
3317 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003318 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003319 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003320 assert_eq!(tables[1], "blobmetadata");
3321 assert_eq!(tables[2], "grant");
3322 assert_eq!(tables[3], "keyentry");
3323 assert_eq!(tables[4], "keymetadata");
3324 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003325 Ok(())
3326 }
3327
3328 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003329 fn test_auth_token_table_invariant() -> Result<()> {
3330 let mut db = new_test_db()?;
3331 let auth_token1 = HardwareAuthToken {
3332 challenge: i64::MAX,
3333 userId: 200,
3334 authenticatorId: 200,
3335 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3336 timestamp: Timestamp { milliSeconds: 500 },
3337 mac: String::from("mac").into_bytes(),
3338 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003339 db.insert_auth_token(&auth_token1);
3340 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003341 assert_eq!(auth_tokens_returned.len(), 1);
3342
3343 // insert another auth token with the same values for the columns in the UNIQUE constraint
3344 // of the auth token table and different value for timestamp
3345 let auth_token2 = HardwareAuthToken {
3346 challenge: i64::MAX,
3347 userId: 200,
3348 authenticatorId: 200,
3349 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3350 timestamp: Timestamp { milliSeconds: 600 },
3351 mac: String::from("mac").into_bytes(),
3352 };
3353
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003354 db.insert_auth_token(&auth_token2);
3355 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003356 assert_eq!(auth_tokens_returned.len(), 1);
3357
3358 if let Some(auth_token) = auth_tokens_returned.pop() {
3359 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3360 }
3361
3362 // insert another auth token with the different values for the columns in the UNIQUE
3363 // constraint of the auth token table
3364 let auth_token3 = HardwareAuthToken {
3365 challenge: i64::MAX,
3366 userId: 201,
3367 authenticatorId: 200,
3368 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3369 timestamp: Timestamp { milliSeconds: 600 },
3370 mac: String::from("mac").into_bytes(),
3371 };
3372
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003373 db.insert_auth_token(&auth_token3);
3374 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003375 assert_eq!(auth_tokens_returned.len(), 2);
3376
3377 Ok(())
3378 }
3379
3380 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003381 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3382 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003383 }
3384
3385 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003386 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003387 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003388 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003389
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003390 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003391 let entries = get_keyentry(&db)?;
3392 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003393
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003394 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003395
3396 let entries_new = get_keyentry(&db)?;
3397 assert_eq!(entries, entries_new);
3398 Ok(())
3399 }
3400
3401 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003402 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003403 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3404 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003405 }
3406
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003407 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003408
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003409 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3410 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003411
3412 let entries = get_keyentry(&db)?;
3413 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003414 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3415 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003416
3417 // Test that we must pass in a valid Domain.
3418 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003419 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003420 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003421 );
3422 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003423 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003424 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003425 );
3426 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003427 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003428 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003429 );
3430
3431 Ok(())
3432 }
3433
Joel Galenson33c04ad2020-08-03 11:04:38 -07003434 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003435 fn test_add_unsigned_key() -> Result<()> {
3436 let mut db = new_test_db()?;
3437 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3438 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3439 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3440 db.create_attestation_key_entry(
3441 &public_key,
3442 &raw_public_key,
3443 &private_key,
3444 &KEYSTORE_UUID,
3445 )?;
3446 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3447 assert_eq!(keys.len(), 1);
3448 assert_eq!(keys[0], public_key);
3449 Ok(())
3450 }
3451
3452 #[test]
3453 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3454 let mut db = new_test_db()?;
3455 let expiration_date: i64 = 20;
3456 let namespace: i64 = 30;
3457 let base_byte: u8 = 1;
3458 let loaded_values =
3459 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3460 let chain =
3461 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3462 assert_eq!(true, chain.is_some());
3463 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003464 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003465 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3466 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003467 Ok(())
3468 }
3469
3470 #[test]
3471 fn test_get_attestation_pool_status() -> Result<()> {
3472 let mut db = new_test_db()?;
3473 let namespace: i64 = 30;
3474 load_attestation_key_pool(
3475 &mut db, 10, /* expiration */
3476 namespace, 0x01, /* base_byte */
3477 )?;
3478 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3479 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3480 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3481 assert_eq!(status.expiring, 0);
3482 assert_eq!(status.attested, 3);
3483 assert_eq!(status.unassigned, 0);
3484 assert_eq!(status.total, 3);
3485 assert_eq!(
3486 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3487 1
3488 );
3489 assert_eq!(
3490 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3491 2
3492 );
3493 assert_eq!(
3494 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3495 3
3496 );
3497 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3498 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3499 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3500 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003501 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003502 db.create_attestation_key_entry(
3503 &public_key,
3504 &raw_public_key,
3505 &private_key,
3506 &KEYSTORE_UUID,
3507 )?;
3508 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3509 assert_eq!(status.attested, 3);
3510 assert_eq!(status.unassigned, 0);
3511 assert_eq!(status.total, 4);
3512 db.store_signed_attestation_certificate_chain(
3513 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003514 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003515 &cert_chain,
3516 20,
3517 &KEYSTORE_UUID,
3518 )?;
3519 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3520 assert_eq!(status.attested, 4);
3521 assert_eq!(status.unassigned, 1);
3522 assert_eq!(status.total, 4);
3523 Ok(())
3524 }
3525
3526 #[test]
3527 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003528 let temp_dir =
3529 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3530 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003531 let expiration_date: i64 =
3532 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3533 let namespace: i64 = 30;
3534 let namespace_del1: i64 = 45;
3535 let namespace_del2: i64 = 60;
3536 let entry_values = load_attestation_key_pool(
3537 &mut db,
3538 expiration_date,
3539 namespace,
3540 0x01, /* base_byte */
3541 )?;
3542 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3543 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003544
3545 let blob_entry_row_count: u32 = db
3546 .conn
3547 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3548 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003549 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3550 // one key, one certificate chain, and one certificate.
3551 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003552
Max Bires2b2e6562020-09-22 11:22:36 -07003553 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3554
3555 let mut cert_chain =
3556 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003557 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003558 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003559 assert_eq!(entry_values.batch_cert, value.batch_cert);
3560 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003561 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003562
3563 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3564 Domain::APP,
3565 namespace_del1,
3566 &KEYSTORE_UUID,
3567 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003568 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003569 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3570 Domain::APP,
3571 namespace_del2,
3572 &KEYSTORE_UUID,
3573 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003574 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003575
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003576 // Give the garbage collector half a second to catch up.
3577 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003578
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003579 let blob_entry_row_count: u32 = db
3580 .conn
3581 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3582 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003583 // There shound be 3 blob entries left, because we deleted two of the attestation
3584 // key entries with three blobs each.
3585 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003586
Max Bires2b2e6562020-09-22 11:22:36 -07003587 Ok(())
3588 }
3589
3590 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003591 fn test_delete_all_attestation_keys() -> Result<()> {
3592 let mut db = new_test_db()?;
3593 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3594 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003595 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003596 let result = db.delete_all_attestation_keys()?;
3597
3598 // Give the garbage collector half a second to catch up.
3599 std::thread::sleep(Duration::from_millis(500));
3600
3601 // Attestation keys should be deleted, and the regular key should remain.
3602 assert_eq!(result, 2);
3603
3604 Ok(())
3605 }
3606
3607 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003608 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003609 fn extractor(
3610 ke: &KeyEntryRow,
3611 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3612 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003613 }
3614
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003615 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003616 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3617 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003618 let entries = get_keyentry(&db)?;
3619 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003620 assert_eq!(
3621 extractor(&entries[0]),
3622 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3623 );
3624 assert_eq!(
3625 extractor(&entries[1]),
3626 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3627 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003628
3629 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003630 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003631 let entries = get_keyentry(&db)?;
3632 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003633 assert_eq!(
3634 extractor(&entries[0]),
3635 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3636 );
3637 assert_eq!(
3638 extractor(&entries[1]),
3639 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3640 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003641
3642 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003643 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003644 let entries = get_keyentry(&db)?;
3645 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003646 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3647 assert_eq!(
3648 extractor(&entries[1]),
3649 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3650 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003651
3652 // Test that we must pass in a valid Domain.
3653 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003654 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003655 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003656 );
3657 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003658 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003659 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003660 );
3661 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003662 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003663 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003664 );
3665
3666 // Test that we correctly handle setting an alias for something that does not exist.
3667 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003668 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003669 "Expected to update a single entry but instead updated 0",
3670 );
3671 // Test that we correctly abort the transaction in this case.
3672 let entries = get_keyentry(&db)?;
3673 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003674 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3675 assert_eq!(
3676 extractor(&entries[1]),
3677 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3678 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003679
3680 Ok(())
3681 }
3682
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003683 #[test]
3684 fn test_grant_ungrant() -> Result<()> {
3685 const CALLER_UID: u32 = 15;
3686 const GRANTEE_UID: u32 = 12;
3687 const SELINUX_NAMESPACE: i64 = 7;
3688
3689 let mut db = new_test_db()?;
3690 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003691 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3692 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3693 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003694 )?;
3695 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003696 domain: super::Domain::APP,
3697 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003698 alias: Some("key".to_string()),
3699 blob: None,
3700 };
3701 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3702 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3703
3704 // Reset totally predictable random number generator in case we
3705 // are not the first test running on this thread.
3706 reset_random();
3707 let next_random = 0i64;
3708
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003709 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003710 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003711 assert_eq!(*a, PVEC1);
3712 assert_eq!(
3713 *k,
3714 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003715 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003716 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003717 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003718 alias: Some("key".to_string()),
3719 blob: None,
3720 }
3721 );
3722 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003723 })
3724 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725
3726 assert_eq!(
3727 app_granted_key,
3728 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003729 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003730 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003731 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003732 alias: None,
3733 blob: None,
3734 }
3735 );
3736
3737 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003738 domain: super::Domain::SELINUX,
3739 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003740 alias: Some("yek".to_string()),
3741 blob: None,
3742 };
3743
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003744 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003745 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003746 assert_eq!(*a, PVEC1);
3747 assert_eq!(
3748 *k,
3749 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003750 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003751 // namespace must be the supplied SELinux
3752 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003753 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754 alias: Some("yek".to_string()),
3755 blob: None,
3756 }
3757 );
3758 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003759 })
3760 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003761
3762 assert_eq!(
3763 selinux_granted_key,
3764 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003765 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003766 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003767 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003768 alias: None,
3769 blob: None,
3770 }
3771 );
3772
3773 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003774 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003775 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003776 assert_eq!(*a, PVEC2);
3777 assert_eq!(
3778 *k,
3779 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003780 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003781 // namespace must be the supplied SELinux
3782 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003783 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003784 alias: Some("yek".to_string()),
3785 blob: None,
3786 }
3787 );
3788 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003789 })
3790 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003791
3792 assert_eq!(
3793 selinux_granted_key,
3794 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003795 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003796 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003797 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003798 alias: None,
3799 blob: None,
3800 }
3801 );
3802
3803 {
3804 // Limiting scope of stmt, because it borrows db.
3805 let mut stmt = db
3806 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003807 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003808 let mut rows =
3809 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3810 Ok((
3811 row.get(0)?,
3812 row.get(1)?,
3813 row.get(2)?,
3814 KeyPermSet::from(row.get::<_, i32>(3)?),
3815 ))
3816 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003817
3818 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003819 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003820 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003821 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003822 assert!(rows.next().is_none());
3823 }
3824
3825 debug_dump_keyentry_table(&mut db)?;
3826 println!("app_key {:?}", app_key);
3827 println!("selinux_key {:?}", selinux_key);
3828
Janis Danisevskis66784c42021-01-27 08:40:25 -08003829 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3830 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003831
3832 Ok(())
3833 }
3834
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003835 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003836 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3837 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3838
3839 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003840 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003841 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003842 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003843 let mut blob_metadata = BlobMetaData::new();
3844 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3845 db.set_blob(
3846 &key_id,
3847 SubComponentType::KEY_BLOB,
3848 Some(TEST_KEY_BLOB),
3849 Some(&blob_metadata),
3850 )?;
3851 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3852 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003853 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003854
3855 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003856 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003857 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003858 )?;
3859 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003860 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3861 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003862 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003863 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003864 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003865 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003866 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003867 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003868 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003869
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003870 drop(rows);
3871 drop(stmt);
3872
3873 assert_eq!(
3874 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3875 BlobMetaData::load_from_db(id, tx).no_gc()
3876 })
3877 .expect("Should find blob metadata."),
3878 blob_metadata
3879 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003880 Ok(())
3881 }
3882
3883 static TEST_ALIAS: &str = "my super duper key";
3884
3885 #[test]
3886 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3887 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003888 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003889 .context("test_insert_and_load_full_keyentry_domain_app")?
3890 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003891 let (_key_guard, key_entry) = db
3892 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003893 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003894 domain: Domain::APP,
3895 nspace: 0,
3896 alias: Some(TEST_ALIAS.to_string()),
3897 blob: None,
3898 },
3899 KeyType::Client,
3900 KeyEntryLoadBits::BOTH,
3901 1,
3902 |_k, _av| Ok(()),
3903 )
3904 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003905 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003906
3907 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003908 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003909 domain: Domain::APP,
3910 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003911 alias: Some(TEST_ALIAS.to_string()),
3912 blob: None,
3913 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003914 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003915 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003916 |_, _| Ok(()),
3917 )
3918 .unwrap();
3919
3920 assert_eq!(
3921 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3922 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003923 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003924 domain: Domain::APP,
3925 nspace: 0,
3926 alias: Some(TEST_ALIAS.to_string()),
3927 blob: None,
3928 },
3929 KeyType::Client,
3930 KeyEntryLoadBits::NONE,
3931 1,
3932 |_k, _av| Ok(()),
3933 )
3934 .unwrap_err()
3935 .root_cause()
3936 .downcast_ref::<KsError>()
3937 );
3938
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003939 Ok(())
3940 }
3941
3942 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003943 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3944 let mut db = new_test_db()?;
3945
3946 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003947 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003948 domain: Domain::APP,
3949 nspace: 1,
3950 alias: Some(TEST_ALIAS.to_string()),
3951 blob: None,
3952 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003953 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003954 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003955 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003956 )
3957 .expect("Trying to insert cert.");
3958
3959 let (_key_guard, mut key_entry) = db
3960 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003961 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003962 domain: Domain::APP,
3963 nspace: 1,
3964 alias: Some(TEST_ALIAS.to_string()),
3965 blob: None,
3966 },
3967 KeyType::Client,
3968 KeyEntryLoadBits::PUBLIC,
3969 1,
3970 |_k, _av| Ok(()),
3971 )
3972 .expect("Trying to read certificate entry.");
3973
3974 assert!(key_entry.pure_cert());
3975 assert!(key_entry.cert().is_none());
3976 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3977
3978 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003979 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003980 domain: Domain::APP,
3981 nspace: 1,
3982 alias: Some(TEST_ALIAS.to_string()),
3983 blob: None,
3984 },
3985 KeyType::Client,
3986 1,
3987 |_, _| Ok(()),
3988 )
3989 .unwrap();
3990
3991 assert_eq!(
3992 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3993 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003994 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003995 domain: Domain::APP,
3996 nspace: 1,
3997 alias: Some(TEST_ALIAS.to_string()),
3998 blob: None,
3999 },
4000 KeyType::Client,
4001 KeyEntryLoadBits::NONE,
4002 1,
4003 |_k, _av| Ok(()),
4004 )
4005 .unwrap_err()
4006 .root_cause()
4007 .downcast_ref::<KsError>()
4008 );
4009
4010 Ok(())
4011 }
4012
4013 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004014 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4015 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004016 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004017 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4018 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004019 let (_key_guard, key_entry) = db
4020 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004021 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004022 domain: Domain::SELINUX,
4023 nspace: 1,
4024 alias: Some(TEST_ALIAS.to_string()),
4025 blob: None,
4026 },
4027 KeyType::Client,
4028 KeyEntryLoadBits::BOTH,
4029 1,
4030 |_k, _av| Ok(()),
4031 )
4032 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004033 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004034
4035 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004036 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004037 domain: Domain::SELINUX,
4038 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004039 alias: Some(TEST_ALIAS.to_string()),
4040 blob: None,
4041 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004042 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004043 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004044 |_, _| Ok(()),
4045 )
4046 .unwrap();
4047
4048 assert_eq!(
4049 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4050 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004051 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004052 domain: Domain::SELINUX,
4053 nspace: 1,
4054 alias: Some(TEST_ALIAS.to_string()),
4055 blob: None,
4056 },
4057 KeyType::Client,
4058 KeyEntryLoadBits::NONE,
4059 1,
4060 |_k, _av| Ok(()),
4061 )
4062 .unwrap_err()
4063 .root_cause()
4064 .downcast_ref::<KsError>()
4065 );
4066
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004067 Ok(())
4068 }
4069
4070 #[test]
4071 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4072 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004073 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004074 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4075 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004076 let (_, key_entry) = db
4077 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004078 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004079 KeyType::Client,
4080 KeyEntryLoadBits::BOTH,
4081 1,
4082 |_k, _av| Ok(()),
4083 )
4084 .unwrap();
4085
Qi Wub9433b52020-12-01 14:52:46 +08004086 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004087
4088 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004089 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004090 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004091 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004092 |_, _| Ok(()),
4093 )
4094 .unwrap();
4095
4096 assert_eq!(
4097 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4098 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004099 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004100 KeyType::Client,
4101 KeyEntryLoadBits::NONE,
4102 1,
4103 |_k, _av| Ok(()),
4104 )
4105 .unwrap_err()
4106 .root_cause()
4107 .downcast_ref::<KsError>()
4108 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004109
4110 Ok(())
4111 }
4112
4113 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004114 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4115 let mut db = new_test_db()?;
4116 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4117 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4118 .0;
4119 // Update the usage count of the limited use key.
4120 db.check_and_update_key_usage_count(key_id)?;
4121
4122 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004123 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004124 KeyType::Client,
4125 KeyEntryLoadBits::BOTH,
4126 1,
4127 |_k, _av| Ok(()),
4128 )?;
4129
4130 // The usage count is decremented now.
4131 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4132
4133 Ok(())
4134 }
4135
4136 #[test]
4137 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4138 let mut db = new_test_db()?;
4139 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4140 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4141 .0;
4142 // Update the usage count of the limited use key.
4143 db.check_and_update_key_usage_count(key_id).expect(concat!(
4144 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4145 "This should succeed."
4146 ));
4147
4148 // Try to update the exhausted limited use key.
4149 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4150 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4151 "This should fail."
4152 ));
4153 assert_eq!(
4154 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4155 e.root_cause().downcast_ref::<KsError>().unwrap()
4156 );
4157
4158 Ok(())
4159 }
4160
4161 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004162 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4163 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004164 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004165 .context("test_insert_and_load_full_keyentry_from_grant")?
4166 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004167
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004168 let granted_key = db
4169 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004170 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004171 domain: Domain::APP,
4172 nspace: 0,
4173 alias: Some(TEST_ALIAS.to_string()),
4174 blob: None,
4175 },
4176 1,
4177 2,
4178 key_perm_set![KeyPerm::use_()],
4179 |_k, _av| Ok(()),
4180 )
4181 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004182
4183 debug_dump_grant_table(&mut db)?;
4184
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004185 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004186 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4187 assert_eq!(Domain::GRANT, k.domain);
4188 assert!(av.unwrap().includes(KeyPerm::use_()));
4189 Ok(())
4190 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004191 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004192
Qi Wub9433b52020-12-01 14:52:46 +08004193 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004194
Janis Danisevskis66784c42021-01-27 08:40:25 -08004195 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004196
4197 assert_eq!(
4198 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4199 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004200 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004201 KeyType::Client,
4202 KeyEntryLoadBits::NONE,
4203 2,
4204 |_k, _av| Ok(()),
4205 )
4206 .unwrap_err()
4207 .root_cause()
4208 .downcast_ref::<KsError>()
4209 );
4210
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004211 Ok(())
4212 }
4213
Janis Danisevskis45760022021-01-19 16:34:10 -08004214 // This test attempts to load a key by key id while the caller is not the owner
4215 // but a grant exists for the given key and the caller.
4216 #[test]
4217 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4218 let mut db = new_test_db()?;
4219 const OWNER_UID: u32 = 1u32;
4220 const GRANTEE_UID: u32 = 2u32;
4221 const SOMEONE_ELSE_UID: u32 = 3u32;
4222 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4223 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4224 .0;
4225
4226 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004227 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004228 domain: Domain::APP,
4229 nspace: 0,
4230 alias: Some(TEST_ALIAS.to_string()),
4231 blob: None,
4232 },
4233 OWNER_UID,
4234 GRANTEE_UID,
4235 key_perm_set![KeyPerm::use_()],
4236 |_k, _av| Ok(()),
4237 )
4238 .unwrap();
4239
4240 debug_dump_grant_table(&mut db)?;
4241
4242 let id_descriptor =
4243 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
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 GRANTEE_UID,
4251 |k, av| {
4252 assert_eq!(Domain::APP, k.domain);
4253 assert_eq!(OWNER_UID as i64, k.nspace);
4254 assert!(av.unwrap().includes(KeyPerm::use_()));
4255 Ok(())
4256 },
4257 )
4258 .unwrap();
4259
4260 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4261
4262 let (_, key_entry) = db
4263 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004264 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004265 KeyType::Client,
4266 KeyEntryLoadBits::BOTH,
4267 SOMEONE_ELSE_UID,
4268 |k, av| {
4269 assert_eq!(Domain::APP, k.domain);
4270 assert_eq!(OWNER_UID as i64, k.nspace);
4271 assert!(av.is_none());
4272 Ok(())
4273 },
4274 )
4275 .unwrap();
4276
4277 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4278
Janis Danisevskis66784c42021-01-27 08:40:25 -08004279 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004280
4281 assert_eq!(
4282 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4283 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004284 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004285 KeyType::Client,
4286 KeyEntryLoadBits::NONE,
4287 GRANTEE_UID,
4288 |_k, _av| Ok(()),
4289 )
4290 .unwrap_err()
4291 .root_cause()
4292 .downcast_ref::<KsError>()
4293 );
4294
4295 Ok(())
4296 }
4297
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004298 // Creates a key migrates it to a different location and then tries to access it by the old
4299 // and new location.
4300 #[test]
4301 fn test_migrate_key_app_to_app() -> Result<()> {
4302 let mut db = new_test_db()?;
4303 const SOURCE_UID: u32 = 1u32;
4304 const DESTINATION_UID: u32 = 2u32;
4305 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4306 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4307 let key_id_guard =
4308 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4309 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4310
4311 let source_descriptor: KeyDescriptor = KeyDescriptor {
4312 domain: Domain::APP,
4313 nspace: -1,
4314 alias: Some(SOURCE_ALIAS.to_string()),
4315 blob: None,
4316 };
4317
4318 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4319 domain: Domain::APP,
4320 nspace: -1,
4321 alias: Some(DESTINATION_ALIAS.to_string()),
4322 blob: None,
4323 };
4324
4325 let key_id = key_id_guard.id();
4326
4327 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4328 Ok(())
4329 })
4330 .unwrap();
4331
4332 let (_, key_entry) = db
4333 .load_key_entry(
4334 &destination_descriptor,
4335 KeyType::Client,
4336 KeyEntryLoadBits::BOTH,
4337 DESTINATION_UID,
4338 |k, av| {
4339 assert_eq!(Domain::APP, k.domain);
4340 assert_eq!(DESTINATION_UID as i64, k.nspace);
4341 assert!(av.is_none());
4342 Ok(())
4343 },
4344 )
4345 .unwrap();
4346
4347 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4348
4349 assert_eq!(
4350 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4351 db.load_key_entry(
4352 &source_descriptor,
4353 KeyType::Client,
4354 KeyEntryLoadBits::NONE,
4355 SOURCE_UID,
4356 |_k, _av| Ok(()),
4357 )
4358 .unwrap_err()
4359 .root_cause()
4360 .downcast_ref::<KsError>()
4361 );
4362
4363 Ok(())
4364 }
4365
4366 // Creates a key migrates it to a different location and then tries to access it by the old
4367 // and new location.
4368 #[test]
4369 fn test_migrate_key_app_to_selinux() -> Result<()> {
4370 let mut db = new_test_db()?;
4371 const SOURCE_UID: u32 = 1u32;
4372 const DESTINATION_UID: u32 = 2u32;
4373 const DESTINATION_NAMESPACE: i64 = 1000i64;
4374 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4375 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4376 let key_id_guard =
4377 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4378 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4379
4380 let source_descriptor: KeyDescriptor = KeyDescriptor {
4381 domain: Domain::APP,
4382 nspace: -1,
4383 alias: Some(SOURCE_ALIAS.to_string()),
4384 blob: None,
4385 };
4386
4387 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4388 domain: Domain::SELINUX,
4389 nspace: DESTINATION_NAMESPACE,
4390 alias: Some(DESTINATION_ALIAS.to_string()),
4391 blob: None,
4392 };
4393
4394 let key_id = key_id_guard.id();
4395
4396 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4397 Ok(())
4398 })
4399 .unwrap();
4400
4401 let (_, key_entry) = db
4402 .load_key_entry(
4403 &destination_descriptor,
4404 KeyType::Client,
4405 KeyEntryLoadBits::BOTH,
4406 DESTINATION_UID,
4407 |k, av| {
4408 assert_eq!(Domain::SELINUX, k.domain);
4409 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4410 assert!(av.is_none());
4411 Ok(())
4412 },
4413 )
4414 .unwrap();
4415
4416 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4417
4418 assert_eq!(
4419 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4420 db.load_key_entry(
4421 &source_descriptor,
4422 KeyType::Client,
4423 KeyEntryLoadBits::NONE,
4424 SOURCE_UID,
4425 |_k, _av| Ok(()),
4426 )
4427 .unwrap_err()
4428 .root_cause()
4429 .downcast_ref::<KsError>()
4430 );
4431
4432 Ok(())
4433 }
4434
4435 // Creates two keys and tries to migrate the first to the location of the second which
4436 // is expected to fail.
4437 #[test]
4438 fn test_migrate_key_destination_occupied() -> Result<()> {
4439 let mut db = new_test_db()?;
4440 const SOURCE_UID: u32 = 1u32;
4441 const DESTINATION_UID: u32 = 2u32;
4442 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4443 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4444 let key_id_guard =
4445 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4446 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4447 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4448 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4449
4450 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4451 domain: Domain::APP,
4452 nspace: -1,
4453 alias: Some(DESTINATION_ALIAS.to_string()),
4454 blob: None,
4455 };
4456
4457 assert_eq!(
4458 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4459 db.migrate_key_namespace(
4460 key_id_guard,
4461 &destination_descriptor,
4462 DESTINATION_UID,
4463 |_k| Ok(())
4464 )
4465 .unwrap_err()
4466 .root_cause()
4467 .downcast_ref::<KsError>()
4468 );
4469
4470 Ok(())
4471 }
4472
Janis Danisevskisaec14592020-11-12 09:41:49 -08004473 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4474
Janis Danisevskisaec14592020-11-12 09:41:49 -08004475 #[test]
4476 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4477 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004478 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4479 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004480 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004481 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004482 .context("test_insert_and_load_full_keyentry_domain_app")?
4483 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004484 let (_key_guard, key_entry) = db
4485 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004486 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004487 domain: Domain::APP,
4488 nspace: 0,
4489 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4490 blob: None,
4491 },
4492 KeyType::Client,
4493 KeyEntryLoadBits::BOTH,
4494 33,
4495 |_k, _av| Ok(()),
4496 )
4497 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004498 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004499 let state = Arc::new(AtomicU8::new(1));
4500 let state2 = state.clone();
4501
4502 // Spawning a second thread that attempts to acquire the key id lock
4503 // for the same key as the primary thread. The primary thread then
4504 // waits, thereby forcing the secondary thread into the second stage
4505 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4506 // The test succeeds if the secondary thread observes the transition
4507 // of `state` from 1 to 2, despite having a whole second to overtake
4508 // the primary thread.
4509 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004510 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004511 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004512 assert!(db
4513 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004514 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004515 domain: Domain::APP,
4516 nspace: 0,
4517 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4518 blob: None,
4519 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004520 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004521 KeyEntryLoadBits::BOTH,
4522 33,
4523 |_k, _av| Ok(()),
4524 )
4525 .is_ok());
4526 // We should only see a 2 here because we can only return
4527 // from load_key_entry when the `_key_guard` expires,
4528 // which happens at the end of the scope.
4529 assert_eq!(2, state2.load(Ordering::Relaxed));
4530 });
4531
4532 thread::sleep(std::time::Duration::from_millis(1000));
4533
4534 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4535
4536 // Return the handle from this scope so we can join with the
4537 // secondary thread after the key id lock has expired.
4538 handle
4539 // This is where the `_key_guard` goes out of scope,
4540 // which is the reason for concurrent load_key_entry on the same key
4541 // to unblock.
4542 };
4543 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4544 // main test thread. We will not see failing asserts in secondary threads otherwise.
4545 handle.join().unwrap();
4546 Ok(())
4547 }
4548
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004549 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004550 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004551 let temp_dir =
4552 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4553
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004554 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4555 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004556
4557 let _tx1 = db1
4558 .conn
4559 .transaction_with_behavior(TransactionBehavior::Immediate)
4560 .expect("Failed to create first transaction.");
4561
4562 let error = db2
4563 .conn
4564 .transaction_with_behavior(TransactionBehavior::Immediate)
4565 .context("Transaction begin failed.")
4566 .expect_err("This should fail.");
4567 let root_cause = error.root_cause();
4568 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4569 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4570 {
4571 return;
4572 }
4573 panic!(
4574 "Unexpected error {:?} \n{:?} \n{:?}",
4575 error,
4576 root_cause,
4577 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4578 )
4579 }
4580
4581 #[cfg(disabled)]
4582 #[test]
4583 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4584 let temp_dir = Arc::new(
4585 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4586 .expect("Failed to create temp dir."),
4587 );
4588
4589 let test_begin = Instant::now();
4590
4591 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4592 const KEY_COUNT: u32 = 500u32;
4593 const OPEN_DB_COUNT: u32 = 50u32;
4594
4595 let mut actual_key_count = KEY_COUNT;
4596 // First insert KEY_COUNT keys.
4597 for count in 0..KEY_COUNT {
4598 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4599 actual_key_count = count;
4600 break;
4601 }
4602 let alias = format!("test_alias_{}", count);
4603 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4604 .expect("Failed to make key entry.");
4605 }
4606
4607 // Insert more keys from a different thread and into a different namespace.
4608 let temp_dir1 = temp_dir.clone();
4609 let handle1 = thread::spawn(move || {
4610 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4611
4612 for count in 0..actual_key_count {
4613 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4614 return;
4615 }
4616 let alias = format!("test_alias_{}", count);
4617 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4618 .expect("Failed to make key entry.");
4619 }
4620
4621 // then unbind them again.
4622 for count in 0..actual_key_count {
4623 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4624 return;
4625 }
4626 let key = KeyDescriptor {
4627 domain: Domain::APP,
4628 nspace: -1,
4629 alias: Some(format!("test_alias_{}", count)),
4630 blob: None,
4631 };
4632 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4633 }
4634 });
4635
4636 // And start unbinding the first set of keys.
4637 let temp_dir2 = temp_dir.clone();
4638 let handle2 = thread::spawn(move || {
4639 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4640
4641 for count in 0..actual_key_count {
4642 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4643 return;
4644 }
4645 let key = KeyDescriptor {
4646 domain: Domain::APP,
4647 nspace: -1,
4648 alias: Some(format!("test_alias_{}", count)),
4649 blob: None,
4650 };
4651 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4652 }
4653 });
4654
4655 let stop_deleting = Arc::new(AtomicU8::new(0));
4656 let stop_deleting2 = stop_deleting.clone();
4657
4658 // And delete anything that is unreferenced keys.
4659 let temp_dir3 = temp_dir.clone();
4660 let handle3 = thread::spawn(move || {
4661 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4662
4663 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4664 while let Some((key_guard, _key)) =
4665 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4666 {
4667 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4668 return;
4669 }
4670 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4671 }
4672 std::thread::sleep(std::time::Duration::from_millis(100));
4673 }
4674 });
4675
4676 // While a lot of inserting and deleting is going on we have to open database connections
4677 // successfully and use them.
4678 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4679 // out of scope.
4680 #[allow(clippy::redundant_clone)]
4681 let temp_dir4 = temp_dir.clone();
4682 let handle4 = thread::spawn(move || {
4683 for count in 0..OPEN_DB_COUNT {
4684 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4685 return;
4686 }
4687 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4688
4689 let alias = format!("test_alias_{}", count);
4690 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4691 .expect("Failed to make key entry.");
4692 let key = KeyDescriptor {
4693 domain: Domain::APP,
4694 nspace: -1,
4695 alias: Some(alias),
4696 blob: None,
4697 };
4698 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4699 }
4700 });
4701
4702 handle1.join().expect("Thread 1 panicked.");
4703 handle2.join().expect("Thread 2 panicked.");
4704 handle4.join().expect("Thread 4 panicked.");
4705
4706 stop_deleting.store(1, Ordering::Relaxed);
4707 handle3.join().expect("Thread 3 panicked.");
4708
4709 Ok(())
4710 }
4711
4712 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004713 fn list() -> Result<()> {
4714 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004715 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004716 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4717 (Domain::APP, 1, "test1"),
4718 (Domain::APP, 1, "test2"),
4719 (Domain::APP, 1, "test3"),
4720 (Domain::APP, 1, "test4"),
4721 (Domain::APP, 1, "test5"),
4722 (Domain::APP, 1, "test6"),
4723 (Domain::APP, 1, "test7"),
4724 (Domain::APP, 2, "test1"),
4725 (Domain::APP, 2, "test2"),
4726 (Domain::APP, 2, "test3"),
4727 (Domain::APP, 2, "test4"),
4728 (Domain::APP, 2, "test5"),
4729 (Domain::APP, 2, "test6"),
4730 (Domain::APP, 2, "test8"),
4731 (Domain::SELINUX, 100, "test1"),
4732 (Domain::SELINUX, 100, "test2"),
4733 (Domain::SELINUX, 100, "test3"),
4734 (Domain::SELINUX, 100, "test4"),
4735 (Domain::SELINUX, 100, "test5"),
4736 (Domain::SELINUX, 100, "test6"),
4737 (Domain::SELINUX, 100, "test9"),
4738 ];
4739
4740 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4741 .iter()
4742 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004743 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4744 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004745 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4746 });
4747 (entry.id(), *ns)
4748 })
4749 .collect();
4750
4751 for (domain, namespace) in
4752 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4753 {
4754 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4755 .iter()
4756 .filter_map(|(domain, ns, alias)| match ns {
4757 ns if *ns == *namespace => Some(KeyDescriptor {
4758 domain: *domain,
4759 nspace: *ns,
4760 alias: Some(alias.to_string()),
4761 blob: None,
4762 }),
4763 _ => None,
4764 })
4765 .collect();
4766 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07004767 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004768 list_result.sort();
4769 assert_eq!(list_o_descriptors, list_result);
4770
4771 let mut list_o_ids: Vec<i64> = list_o_descriptors
4772 .into_iter()
4773 .map(|d| {
4774 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004775 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004776 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004777 KeyType::Client,
4778 KeyEntryLoadBits::NONE,
4779 *namespace as u32,
4780 |_, _| Ok(()),
4781 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004782 .unwrap();
4783 entry.id()
4784 })
4785 .collect();
4786 list_o_ids.sort_unstable();
4787 let mut loaded_entries: Vec<i64> = list_o_keys
4788 .iter()
4789 .filter_map(|(id, ns)| match ns {
4790 ns if *ns == *namespace => Some(*id),
4791 _ => None,
4792 })
4793 .collect();
4794 loaded_entries.sort_unstable();
4795 assert_eq!(list_o_ids, loaded_entries);
4796 }
Janis Danisevskis18313832021-05-17 13:30:32 -07004797 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004798
4799 Ok(())
4800 }
4801
Joel Galenson0891bc12020-07-20 10:37:03 -07004802 // Helpers
4803
4804 // Checks that the given result is an error containing the given string.
4805 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4806 let error_str = format!(
4807 "{:#?}",
4808 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4809 );
4810 assert!(
4811 error_str.contains(target),
4812 "The string \"{}\" should contain \"{}\"",
4813 error_str,
4814 target
4815 );
4816 }
4817
Joel Galenson2aab4432020-07-22 15:27:57 -07004818 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004819 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004820 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004821 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004822 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004823 namespace: Option<i64>,
4824 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004825 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004826 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004827 }
4828
4829 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4830 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004831 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004832 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004833 Ok(KeyEntryRow {
4834 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004835 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004836 domain: match row.get(2)? {
4837 Some(i) => Some(Domain(i)),
4838 None => None,
4839 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004840 namespace: row.get(3)?,
4841 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004842 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004843 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004844 })
4845 })?
4846 .map(|r| r.context("Could not read keyentry row."))
4847 .collect::<Result<Vec<_>>>()
4848 }
4849
Max Biresb2e1d032021-02-08 21:35:05 -08004850 struct RemoteProvValues {
4851 cert_chain: Vec<u8>,
4852 priv_key: Vec<u8>,
4853 batch_cert: Vec<u8>,
4854 }
4855
Max Bires2b2e6562020-09-22 11:22:36 -07004856 fn load_attestation_key_pool(
4857 db: &mut KeystoreDB,
4858 expiration_date: i64,
4859 namespace: i64,
4860 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004861 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004862 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4863 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4864 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4865 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004866 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004867 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4868 db.store_signed_attestation_certificate_chain(
4869 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004870 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004871 &cert_chain,
4872 expiration_date,
4873 &KEYSTORE_UUID,
4874 )?;
4875 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004876 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004877 }
4878
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004879 // Note: The parameters and SecurityLevel associations are nonsensical. This
4880 // collection is only used to check if the parameters are preserved as expected by the
4881 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004882 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4883 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004884 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4885 KeyParameter::new(
4886 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4887 SecurityLevel::TRUSTED_ENVIRONMENT,
4888 ),
4889 KeyParameter::new(
4890 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4891 SecurityLevel::TRUSTED_ENVIRONMENT,
4892 ),
4893 KeyParameter::new(
4894 KeyParameterValue::Algorithm(Algorithm::RSA),
4895 SecurityLevel::TRUSTED_ENVIRONMENT,
4896 ),
4897 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4898 KeyParameter::new(
4899 KeyParameterValue::BlockMode(BlockMode::ECB),
4900 SecurityLevel::TRUSTED_ENVIRONMENT,
4901 ),
4902 KeyParameter::new(
4903 KeyParameterValue::BlockMode(BlockMode::GCM),
4904 SecurityLevel::TRUSTED_ENVIRONMENT,
4905 ),
4906 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4907 KeyParameter::new(
4908 KeyParameterValue::Digest(Digest::MD5),
4909 SecurityLevel::TRUSTED_ENVIRONMENT,
4910 ),
4911 KeyParameter::new(
4912 KeyParameterValue::Digest(Digest::SHA_2_224),
4913 SecurityLevel::TRUSTED_ENVIRONMENT,
4914 ),
4915 KeyParameter::new(
4916 KeyParameterValue::Digest(Digest::SHA_2_256),
4917 SecurityLevel::STRONGBOX,
4918 ),
4919 KeyParameter::new(
4920 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4921 SecurityLevel::TRUSTED_ENVIRONMENT,
4922 ),
4923 KeyParameter::new(
4924 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4925 SecurityLevel::TRUSTED_ENVIRONMENT,
4926 ),
4927 KeyParameter::new(
4928 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4929 SecurityLevel::STRONGBOX,
4930 ),
4931 KeyParameter::new(
4932 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4933 SecurityLevel::TRUSTED_ENVIRONMENT,
4934 ),
4935 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4936 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4937 KeyParameter::new(
4938 KeyParameterValue::EcCurve(EcCurve::P_224),
4939 SecurityLevel::TRUSTED_ENVIRONMENT,
4940 ),
4941 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4942 KeyParameter::new(
4943 KeyParameterValue::EcCurve(EcCurve::P_384),
4944 SecurityLevel::TRUSTED_ENVIRONMENT,
4945 ),
4946 KeyParameter::new(
4947 KeyParameterValue::EcCurve(EcCurve::P_521),
4948 SecurityLevel::TRUSTED_ENVIRONMENT,
4949 ),
4950 KeyParameter::new(
4951 KeyParameterValue::RSAPublicExponent(3),
4952 SecurityLevel::TRUSTED_ENVIRONMENT,
4953 ),
4954 KeyParameter::new(
4955 KeyParameterValue::IncludeUniqueID,
4956 SecurityLevel::TRUSTED_ENVIRONMENT,
4957 ),
4958 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4959 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4960 KeyParameter::new(
4961 KeyParameterValue::ActiveDateTime(1234567890),
4962 SecurityLevel::STRONGBOX,
4963 ),
4964 KeyParameter::new(
4965 KeyParameterValue::OriginationExpireDateTime(1234567890),
4966 SecurityLevel::TRUSTED_ENVIRONMENT,
4967 ),
4968 KeyParameter::new(
4969 KeyParameterValue::UsageExpireDateTime(1234567890),
4970 SecurityLevel::TRUSTED_ENVIRONMENT,
4971 ),
4972 KeyParameter::new(
4973 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4974 SecurityLevel::TRUSTED_ENVIRONMENT,
4975 ),
4976 KeyParameter::new(
4977 KeyParameterValue::MaxUsesPerBoot(1234567890),
4978 SecurityLevel::TRUSTED_ENVIRONMENT,
4979 ),
4980 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4981 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4982 KeyParameter::new(
4983 KeyParameterValue::NoAuthRequired,
4984 SecurityLevel::TRUSTED_ENVIRONMENT,
4985 ),
4986 KeyParameter::new(
4987 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4988 SecurityLevel::TRUSTED_ENVIRONMENT,
4989 ),
4990 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4991 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4992 KeyParameter::new(
4993 KeyParameterValue::TrustedUserPresenceRequired,
4994 SecurityLevel::TRUSTED_ENVIRONMENT,
4995 ),
4996 KeyParameter::new(
4997 KeyParameterValue::TrustedConfirmationRequired,
4998 SecurityLevel::TRUSTED_ENVIRONMENT,
4999 ),
5000 KeyParameter::new(
5001 KeyParameterValue::UnlockedDeviceRequired,
5002 SecurityLevel::TRUSTED_ENVIRONMENT,
5003 ),
5004 KeyParameter::new(
5005 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5006 SecurityLevel::SOFTWARE,
5007 ),
5008 KeyParameter::new(
5009 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5010 SecurityLevel::SOFTWARE,
5011 ),
5012 KeyParameter::new(
5013 KeyParameterValue::CreationDateTime(12345677890),
5014 SecurityLevel::SOFTWARE,
5015 ),
5016 KeyParameter::new(
5017 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5018 SecurityLevel::TRUSTED_ENVIRONMENT,
5019 ),
5020 KeyParameter::new(
5021 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5022 SecurityLevel::TRUSTED_ENVIRONMENT,
5023 ),
5024 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5025 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5026 KeyParameter::new(
5027 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5028 SecurityLevel::SOFTWARE,
5029 ),
5030 KeyParameter::new(
5031 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5032 SecurityLevel::TRUSTED_ENVIRONMENT,
5033 ),
5034 KeyParameter::new(
5035 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5036 SecurityLevel::TRUSTED_ENVIRONMENT,
5037 ),
5038 KeyParameter::new(
5039 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5040 SecurityLevel::TRUSTED_ENVIRONMENT,
5041 ),
5042 KeyParameter::new(
5043 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5044 SecurityLevel::TRUSTED_ENVIRONMENT,
5045 ),
5046 KeyParameter::new(
5047 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5048 SecurityLevel::TRUSTED_ENVIRONMENT,
5049 ),
5050 KeyParameter::new(
5051 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5052 SecurityLevel::TRUSTED_ENVIRONMENT,
5053 ),
5054 KeyParameter::new(
5055 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5056 SecurityLevel::TRUSTED_ENVIRONMENT,
5057 ),
5058 KeyParameter::new(
5059 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5060 SecurityLevel::TRUSTED_ENVIRONMENT,
5061 ),
5062 KeyParameter::new(
5063 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5064 SecurityLevel::TRUSTED_ENVIRONMENT,
5065 ),
5066 KeyParameter::new(
5067 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5068 SecurityLevel::TRUSTED_ENVIRONMENT,
5069 ),
5070 KeyParameter::new(
5071 KeyParameterValue::VendorPatchLevel(3),
5072 SecurityLevel::TRUSTED_ENVIRONMENT,
5073 ),
5074 KeyParameter::new(
5075 KeyParameterValue::BootPatchLevel(4),
5076 SecurityLevel::TRUSTED_ENVIRONMENT,
5077 ),
5078 KeyParameter::new(
5079 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5080 SecurityLevel::TRUSTED_ENVIRONMENT,
5081 ),
5082 KeyParameter::new(
5083 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5084 SecurityLevel::TRUSTED_ENVIRONMENT,
5085 ),
5086 KeyParameter::new(
5087 KeyParameterValue::MacLength(256),
5088 SecurityLevel::TRUSTED_ENVIRONMENT,
5089 ),
5090 KeyParameter::new(
5091 KeyParameterValue::ResetSinceIdRotation,
5092 SecurityLevel::TRUSTED_ENVIRONMENT,
5093 ),
5094 KeyParameter::new(
5095 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5096 SecurityLevel::TRUSTED_ENVIRONMENT,
5097 ),
Qi Wub9433b52020-12-01 14:52:46 +08005098 ];
5099 if let Some(value) = max_usage_count {
5100 params.push(KeyParameter::new(
5101 KeyParameterValue::UsageCountLimit(value),
5102 SecurityLevel::SOFTWARE,
5103 ));
5104 }
5105 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005106 }
5107
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005108 fn make_test_key_entry(
5109 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005110 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005111 namespace: i64,
5112 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005113 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005114 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005115 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005116 let mut blob_metadata = BlobMetaData::new();
5117 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5118 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5119 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5120 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5121 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5122
5123 db.set_blob(
5124 &key_id,
5125 SubComponentType::KEY_BLOB,
5126 Some(TEST_KEY_BLOB),
5127 Some(&blob_metadata),
5128 )?;
5129 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5130 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005131
5132 let params = make_test_params(max_usage_count);
5133 db.insert_keyparameter(&key_id, &params)?;
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 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005138 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005139 Ok(key_id)
5140 }
5141
Qi Wub9433b52020-12-01 14:52:46 +08005142 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5143 let params = make_test_params(max_usage_count);
5144
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005145 let mut blob_metadata = BlobMetaData::new();
5146 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5147 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5148 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5149 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5150 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5151
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005152 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005153 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005154
5155 KeyEntry {
5156 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005157 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005158 cert: Some(TEST_CERT_BLOB.to_vec()),
5159 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005160 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005161 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005162 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005163 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005164 }
5165 }
5166
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005167 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005168 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005169 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005170 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005171 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005172 NO_PARAMS,
5173 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005174 Ok((
5175 row.get(0)?,
5176 row.get(1)?,
5177 row.get(2)?,
5178 row.get(3)?,
5179 row.get(4)?,
5180 row.get(5)?,
5181 row.get(6)?,
5182 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005183 },
5184 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005185
5186 println!("Key entry table rows:");
5187 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005188 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005189 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005190 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5191 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005192 );
5193 }
5194 Ok(())
5195 }
5196
5197 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005198 let mut stmt = db
5199 .conn
5200 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005201 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5202 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5203 })?;
5204
5205 println!("Grant table rows:");
5206 for r in rows {
5207 let (id, gt, ki, av) = r.unwrap();
5208 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5209 }
5210 Ok(())
5211 }
5212
Joel Galenson0891bc12020-07-20 10:37:03 -07005213 // Use a custom random number generator that repeats each number once.
5214 // This allows us to test repeated elements.
5215
5216 thread_local! {
5217 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5218 }
5219
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005220 fn reset_random() {
5221 RANDOM_COUNTER.with(|counter| {
5222 *counter.borrow_mut() = 0;
5223 })
5224 }
5225
Joel Galenson0891bc12020-07-20 10:37:03 -07005226 pub fn random() -> i64 {
5227 RANDOM_COUNTER.with(|counter| {
5228 let result = *counter.borrow() / 2;
5229 *counter.borrow_mut() += 1;
5230 result
5231 })
5232 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005233
5234 #[test]
5235 fn test_last_off_body() -> Result<()> {
5236 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005237 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005238 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005239 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005240 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005241 let one_second = Duration::from_secs(1);
5242 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005243 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005244 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005245 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005246 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005247 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005248 Ok(())
5249 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005250
5251 #[test]
5252 fn test_unbind_keys_for_user() -> Result<()> {
5253 let mut db = new_test_db()?;
5254 db.unbind_keys_for_user(1, false)?;
5255
5256 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5257 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5258 db.unbind_keys_for_user(2, false)?;
5259
Janis Danisevskis18313832021-05-17 13:30:32 -07005260 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5261 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005262
5263 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005264 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005265
5266 Ok(())
5267 }
5268
5269 #[test]
5270 fn test_store_super_key() -> Result<()> {
5271 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005272 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005273 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005274 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005275 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005276 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005277
5278 let (encrypted_super_key, metadata) =
5279 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005280 db.store_super_key(
5281 1,
5282 &USER_SUPER_KEY,
5283 &encrypted_super_key,
5284 &metadata,
5285 &KeyMetaData::new(),
5286 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005287
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005288 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005289 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005290
Paul Crowley7a658392021-03-18 17:08:20 -07005291 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005292 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5293 USER_SUPER_KEY.algorithm,
5294 key_entry,
5295 &pw,
5296 None,
5297 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005298
Paul Crowley7a658392021-03-18 17:08:20 -07005299 let decrypted_secret_bytes =
5300 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5301 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005302 Ok(())
5303 }
Seth Moore78c091f2021-04-09 21:38:30 +00005304
5305 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5306 vec![
5307 StatsdStorageType::KeyEntry,
5308 StatsdStorageType::KeyEntryIdIndex,
5309 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5310 StatsdStorageType::BlobEntry,
5311 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5312 StatsdStorageType::KeyParameter,
5313 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5314 StatsdStorageType::KeyMetadata,
5315 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5316 StatsdStorageType::Grant,
5317 StatsdStorageType::AuthToken,
5318 StatsdStorageType::BlobMetadata,
5319 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5320 ]
5321 }
5322
5323 /// Perform a simple check to ensure that we can query all the storage types
5324 /// that are supported by the DB. Check for reasonable values.
5325 #[test]
5326 fn test_query_all_valid_table_sizes() -> Result<()> {
5327 const PAGE_SIZE: i64 = 4096;
5328
5329 let mut db = new_test_db()?;
5330
5331 for t in get_valid_statsd_storage_types() {
5332 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005333 // AuthToken can be less than a page since it's in a btree, not sqlite
5334 // TODO(b/187474736) stop using if-let here
5335 if let StatsdStorageType::AuthToken = t {
5336 } else {
5337 assert!(stat.size >= PAGE_SIZE);
5338 }
Seth Moore78c091f2021-04-09 21:38:30 +00005339 assert!(stat.size >= stat.unused_size);
5340 }
5341
5342 Ok(())
5343 }
5344
5345 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5346 get_valid_statsd_storage_types()
5347 .into_iter()
5348 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5349 .collect()
5350 }
5351
5352 fn assert_storage_increased(
5353 db: &mut KeystoreDB,
5354 increased_storage_types: Vec<StatsdStorageType>,
5355 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5356 ) {
5357 for storage in increased_storage_types {
5358 // Verify the expected storage increased.
5359 let new = db.get_storage_stat(storage).unwrap();
5360 let storage = storage as i32;
5361 let old = &baseline[&storage];
5362 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5363 assert!(
5364 new.unused_size <= old.unused_size,
5365 "{}: {} <= {}",
5366 storage,
5367 new.unused_size,
5368 old.unused_size
5369 );
5370
5371 // Update the baseline with the new value so that it succeeds in the
5372 // later comparison.
5373 baseline.insert(storage, new);
5374 }
5375
5376 // Get an updated map of the storage and verify there were no unexpected changes.
5377 let updated_stats = get_storage_stats_map(db);
5378 assert_eq!(updated_stats.len(), baseline.len());
5379
5380 for &k in baseline.keys() {
5381 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5382 let mut s = String::new();
5383 for &k in map.keys() {
5384 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5385 .expect("string concat failed");
5386 }
5387 s
5388 };
5389
5390 assert!(
5391 updated_stats[&k].size == baseline[&k].size
5392 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5393 "updated_stats:\n{}\nbaseline:\n{}",
5394 stringify(&updated_stats),
5395 stringify(&baseline)
5396 );
5397 }
5398 }
5399
5400 #[test]
5401 fn test_verify_key_table_size_reporting() -> Result<()> {
5402 let mut db = new_test_db()?;
5403 let mut working_stats = get_storage_stats_map(&mut db);
5404
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005405 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005406 assert_storage_increased(
5407 &mut db,
5408 vec![
5409 StatsdStorageType::KeyEntry,
5410 StatsdStorageType::KeyEntryIdIndex,
5411 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5412 ],
5413 &mut working_stats,
5414 );
5415
5416 let mut blob_metadata = BlobMetaData::new();
5417 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5418 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5419 assert_storage_increased(
5420 &mut db,
5421 vec![
5422 StatsdStorageType::BlobEntry,
5423 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5424 StatsdStorageType::BlobMetadata,
5425 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5426 ],
5427 &mut working_stats,
5428 );
5429
5430 let params = make_test_params(None);
5431 db.insert_keyparameter(&key_id, &params)?;
5432 assert_storage_increased(
5433 &mut db,
5434 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5435 &mut working_stats,
5436 );
5437
5438 let mut metadata = KeyMetaData::new();
5439 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5440 db.insert_key_metadata(&key_id, &metadata)?;
5441 assert_storage_increased(
5442 &mut db,
5443 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5444 &mut working_stats,
5445 );
5446
5447 let mut sum = 0;
5448 for stat in working_stats.values() {
5449 sum += stat.size;
5450 }
5451 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5452 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5453
5454 Ok(())
5455 }
5456
5457 #[test]
5458 fn test_verify_auth_table_size_reporting() -> Result<()> {
5459 let mut db = new_test_db()?;
5460 let mut working_stats = get_storage_stats_map(&mut db);
5461 db.insert_auth_token(&HardwareAuthToken {
5462 challenge: 123,
5463 userId: 456,
5464 authenticatorId: 789,
5465 authenticatorType: kmhw_authenticator_type::ANY,
5466 timestamp: Timestamp { milliSeconds: 10 },
5467 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005468 });
Seth Moore78c091f2021-04-09 21:38:30 +00005469 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5470 Ok(())
5471 }
5472
5473 #[test]
5474 fn test_verify_grant_table_size_reporting() -> Result<()> {
5475 const OWNER: i64 = 1;
5476 let mut db = new_test_db()?;
5477 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5478
5479 let mut working_stats = get_storage_stats_map(&mut db);
5480 db.grant(
5481 &KeyDescriptor {
5482 domain: Domain::APP,
5483 nspace: 0,
5484 alias: Some(TEST_ALIAS.to_string()),
5485 blob: None,
5486 },
5487 OWNER as u32,
5488 123,
5489 key_perm_set![KeyPerm::use_()],
5490 |_, _| Ok(()),
5491 )?;
5492
5493 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5494
5495 Ok(())
5496 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005497
5498 #[test]
5499 fn find_auth_token_entry_returns_latest() -> Result<()> {
5500 let mut db = new_test_db()?;
5501 db.insert_auth_token(&HardwareAuthToken {
5502 challenge: 123,
5503 userId: 456,
5504 authenticatorId: 789,
5505 authenticatorType: kmhw_authenticator_type::ANY,
5506 timestamp: Timestamp { milliSeconds: 10 },
5507 mac: b"mac0".to_vec(),
5508 });
5509 std::thread::sleep(std::time::Duration::from_millis(1));
5510 db.insert_auth_token(&HardwareAuthToken {
5511 challenge: 123,
5512 userId: 457,
5513 authenticatorId: 789,
5514 authenticatorType: kmhw_authenticator_type::ANY,
5515 timestamp: Timestamp { milliSeconds: 12 },
5516 mac: b"mac1".to_vec(),
5517 });
5518 std::thread::sleep(std::time::Duration::from_millis(1));
5519 db.insert_auth_token(&HardwareAuthToken {
5520 challenge: 123,
5521 userId: 458,
5522 authenticatorId: 789,
5523 authenticatorType: kmhw_authenticator_type::ANY,
5524 timestamp: Timestamp { milliSeconds: 3 },
5525 mac: b"mac2".to_vec(),
5526 });
5527 // All three entries are in the database
5528 assert_eq!(db.perboot.auth_tokens_len(), 3);
5529 // It selected the most recent timestamp
5530 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5531 Ok(())
5532 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005533
5534 #[test]
5535 fn test_set_wal_mode() -> Result<()> {
5536 let temp_dir = TempDir::new("test_set_wal_mode")?;
5537 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
5538 let mode: String =
5539 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5540 row.get(0)
5541 })?;
5542 assert_eq!(mode, "delete");
5543 db.conn.close().expect("Close didn't work");
5544
5545 KeystoreDB::set_wal_mode(temp_dir.path())?;
5546
5547 db = KeystoreDB::new(temp_dir.path(), None)?;
5548 let mode: String =
5549 db.conn.pragma_query_value(Some(Attached("persistent")), "journal_mode", |row| {
5550 row.get(0)
5551 })?;
5552 assert_eq!(mode, "wal");
5553 Ok(())
5554 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01005555
5556 #[test]
5557 fn test_load_key_descriptor() -> Result<()> {
5558 let mut db = new_test_db()?;
5559 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5560
5561 let key = db.load_key_descriptor(key_id)?.unwrap();
5562
5563 assert_eq!(key.domain, Domain::APP);
5564 assert_eq!(key.nspace, 1);
5565 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5566
5567 // No such id
5568 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5569 Ok(())
5570 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005571}