blob: da482f1549bde1f356069d645ac4e57ec558cb1d [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Jeff Vander Stoep46bbc612021-04-09 08:55:21 +020044#![allow(clippy::needless_question_mark)]
45
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080047use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070048use crate::permission::KeyPermSet;
Hasini Gunasingheda895552021-01-27 19:34:37 +000049use crate::utils::{get_current_time_in_seconds, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080050use crate::{
51 db_utils::{self, SqlField},
52 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070053 super_key::USER_SUPER_KEY,
54};
55use crate::{
56 error::{Error as KsError, ErrorCode, ResponseCode},
57 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080058};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080059use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080060use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070061
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080063 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080065};
66use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000067 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000068};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070069use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070070 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070071};
Max Bires2b2e6562020-09-22 11:22:36 -070072use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
73 AttestationPoolStatus::AttestationPoolStatus,
74};
75
76use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080077use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000078use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070079#[cfg(not(test))]
80use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070081use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080082 params,
83 types::FromSql,
84 types::FromSqlResult,
85 types::ToSqlOutput,
86 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080087 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070088};
Max Bires2b2e6562020-09-22 11:22:36 -070089
Janis Danisevskisaec14592020-11-12 09:41:49 -080090use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080091 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080092 path::Path,
93 sync::{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,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800191 // --- ADD NEW META DATA FIELDS HERE ---
192 // For backwards compatibility add new entries only to
193 // end of this list and above this comment.
194 };
195);
196
197impl BlobMetaData {
198 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
199 let mut stmt = tx
200 .prepare(
201 "SELECT tag, data from persistent.blobmetadata
202 WHERE blobentryid = ?;",
203 )
204 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
205
206 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
207
208 let mut rows =
209 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
210 db_utils::with_rows_extract_all(&mut rows, |row| {
211 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
212 metadata.insert(
213 db_tag,
214 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
215 .context("Failed to read BlobMetaEntry.")?,
216 );
217 Ok(())
218 })
219 .context("In BlobMetaData::load_from_db.")?;
220
221 Ok(Self { data: metadata })
222 }
223
224 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
225 let mut stmt = tx
226 .prepare(
227 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
228 VALUES (?, ?, ?);",
229 )
230 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
231
232 let iter = self.data.iter();
233 for (tag, entry) in iter {
234 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
235 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
236 })?;
237 }
238 Ok(())
239 }
240}
241
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800242/// Indicates the type of the keyentry.
243#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
244pub enum KeyType {
245 /// This is a client key type. These keys are created or imported through the Keystore 2.0
246 /// AIDL interface android.system.keystore2.
247 Client,
248 /// This is a super key type. These keys are created by keystore itself and used to encrypt
249 /// other key blobs to provide LSKF binding.
250 Super,
251 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
252 Attestation,
253}
254
255impl ToSql for KeyType {
256 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
257 Ok(ToSqlOutput::Owned(Value::Integer(match self {
258 KeyType::Client => 0,
259 KeyType::Super => 1,
260 KeyType::Attestation => 2,
261 })))
262 }
263}
264
265impl FromSql for KeyType {
266 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
267 match i64::column_result(value)? {
268 0 => Ok(KeyType::Client),
269 1 => Ok(KeyType::Super),
270 2 => Ok(KeyType::Attestation),
271 v => Err(FromSqlError::OutOfRange(v)),
272 }
273 }
274}
275
Max Bires8e93d2b2021-01-14 13:17:59 -0800276/// Uuid representation that can be stored in the database.
277/// Right now it can only be initialized from SecurityLevel.
278/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
279#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
280pub struct Uuid([u8; 16]);
281
282impl Deref for Uuid {
283 type Target = [u8; 16];
284
285 fn deref(&self) -> &Self::Target {
286 &self.0
287 }
288}
289
290impl From<SecurityLevel> for Uuid {
291 fn from(sec_level: SecurityLevel) -> Self {
292 Self((sec_level.0 as u128).to_be_bytes())
293 }
294}
295
296impl ToSql for Uuid {
297 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
298 self.0.to_sql()
299 }
300}
301
302impl FromSql for Uuid {
303 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
304 let blob = Vec::<u8>::column_result(value)?;
305 if blob.len() != 16 {
306 return Err(FromSqlError::OutOfRange(blob.len() as i64));
307 }
308 let mut arr = [0u8; 16];
309 arr.copy_from_slice(&blob);
310 Ok(Self(arr))
311 }
312}
313
314/// Key entries that are not associated with any KeyMint instance, such as pure certificate
315/// entries are associated with this UUID.
316pub static KEYSTORE_UUID: Uuid = Uuid([
317 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
318]);
319
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800320/// Indicates how the sensitive part of this key blob is encrypted.
321#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
322pub enum EncryptedBy {
323 /// The keyblob is encrypted by a user password.
324 /// In the database this variant is represented as NULL.
325 Password,
326 /// The keyblob is encrypted by another key with wrapped key id.
327 /// In the database this variant is represented as non NULL value
328 /// that is convertible to i64, typically NUMERIC.
329 KeyId(i64),
330}
331
332impl ToSql for EncryptedBy {
333 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
334 match self {
335 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
336 Self::KeyId(id) => id.to_sql(),
337 }
338 }
339}
340
341impl FromSql for EncryptedBy {
342 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
343 match value {
344 ValueRef::Null => Ok(Self::Password),
345 _ => Ok(Self::KeyId(i64::column_result(value)?)),
346 }
347 }
348}
349
350/// A database representation of wall clock time. DateTime stores unix epoch time as
351/// i64 in milliseconds.
352#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
353pub struct DateTime(i64);
354
355/// Error type returned when creating DateTime or converting it from and to
356/// SystemTime.
357#[derive(thiserror::Error, Debug)]
358pub enum DateTimeError {
359 /// This is returned when SystemTime and Duration computations fail.
360 #[error(transparent)]
361 SystemTimeError(#[from] SystemTimeError),
362
363 /// This is returned when type conversions fail.
364 #[error(transparent)]
365 TypeConversion(#[from] std::num::TryFromIntError),
366
367 /// This is returned when checked time arithmetic failed.
368 #[error("Time arithmetic failed.")]
369 TimeArithmetic,
370}
371
372impl DateTime {
373 /// Constructs a new DateTime object denoting the current time. This may fail during
374 /// conversion to unix epoch time and during conversion to the internal i64 representation.
375 pub fn now() -> Result<Self, DateTimeError> {
376 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
377 }
378
379 /// Constructs a new DateTime object from milliseconds.
380 pub fn from_millis_epoch(millis: i64) -> Self {
381 Self(millis)
382 }
383
384 /// Returns unix epoch time in milliseconds.
385 pub fn to_millis_epoch(&self) -> i64 {
386 self.0
387 }
388
389 /// Returns unix epoch time in seconds.
390 pub fn to_secs_epoch(&self) -> i64 {
391 self.0 / 1000
392 }
393}
394
395impl ToSql for DateTime {
396 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
397 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
398 }
399}
400
401impl FromSql for DateTime {
402 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
403 Ok(Self(i64::column_result(value)?))
404 }
405}
406
407impl TryInto<SystemTime> for DateTime {
408 type Error = DateTimeError;
409
410 fn try_into(self) -> Result<SystemTime, Self::Error> {
411 // We want to construct a SystemTime representation equivalent to self, denoting
412 // a point in time THEN, but we cannot set the time directly. We can only construct
413 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
414 // and between EPOCH and THEN. With this common reference we can construct the
415 // duration between NOW and THEN which we can add to our SystemTime representation
416 // of NOW to get a SystemTime representation of THEN.
417 // Durations can only be positive, thus the if statement below.
418 let now = SystemTime::now();
419 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
420 let then_epoch = Duration::from_millis(self.0.try_into()?);
421 Ok(if now_epoch > then_epoch {
422 // then = now - (now_epoch - then_epoch)
423 now_epoch
424 .checked_sub(then_epoch)
425 .and_then(|d| now.checked_sub(d))
426 .ok_or(DateTimeError::TimeArithmetic)?
427 } else {
428 // then = now + (then_epoch - now_epoch)
429 then_epoch
430 .checked_sub(now_epoch)
431 .and_then(|d| now.checked_add(d))
432 .ok_or(DateTimeError::TimeArithmetic)?
433 })
434 }
435}
436
437impl TryFrom<SystemTime> for DateTime {
438 type Error = DateTimeError;
439
440 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
441 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
442 }
443}
444
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800445#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
446enum KeyLifeCycle {
447 /// Existing keys have a key ID but are not fully populated yet.
448 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
449 /// them to Unreferenced for garbage collection.
450 Existing,
451 /// A live key is fully populated and usable by clients.
452 Live,
453 /// An unreferenced key is scheduled for garbage collection.
454 Unreferenced,
455}
456
457impl ToSql for KeyLifeCycle {
458 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
459 match self {
460 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
461 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
462 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
463 }
464 }
465}
466
467impl FromSql for KeyLifeCycle {
468 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
469 match i64::column_result(value)? {
470 0 => Ok(KeyLifeCycle::Existing),
471 1 => Ok(KeyLifeCycle::Live),
472 2 => Ok(KeyLifeCycle::Unreferenced),
473 v => Err(FromSqlError::OutOfRange(v)),
474 }
475 }
476}
477
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700478/// Keys have a KeyMint blob component and optional public certificate and
479/// certificate chain components.
480/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
481/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800482#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700483pub struct KeyEntryLoadBits(u32);
484
485impl KeyEntryLoadBits {
486 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
487 pub const NONE: KeyEntryLoadBits = Self(0);
488 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
489 pub const KM: KeyEntryLoadBits = Self(1);
490 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
491 pub const PUBLIC: KeyEntryLoadBits = Self(2);
492 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
493 pub const BOTH: KeyEntryLoadBits = Self(3);
494
495 /// Returns true if this object indicates that the public components shall be loaded.
496 pub const fn load_public(&self) -> bool {
497 self.0 & Self::PUBLIC.0 != 0
498 }
499
500 /// Returns true if the object indicates that the KeyMint component shall be loaded.
501 pub const fn load_km(&self) -> bool {
502 self.0 & Self::KM.0 != 0
503 }
504}
505
Janis Danisevskisaec14592020-11-12 09:41:49 -0800506lazy_static! {
507 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
508}
509
510struct KeyIdLockDb {
511 locked_keys: Mutex<HashSet<i64>>,
512 cond_var: Condvar,
513}
514
515/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
516/// from the database a second time. Most functions manipulating the key blob database
517/// require a KeyIdGuard.
518#[derive(Debug)]
519pub struct KeyIdGuard(i64);
520
521impl KeyIdLockDb {
522 fn new() -> Self {
523 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
524 }
525
526 /// This function blocks until an exclusive lock for the given key entry id can
527 /// be acquired. It returns a guard object, that represents the lifecycle of the
528 /// acquired lock.
529 pub fn get(&self, key_id: i64) -> KeyIdGuard {
530 let mut locked_keys = self.locked_keys.lock().unwrap();
531 while locked_keys.contains(&key_id) {
532 locked_keys = self.cond_var.wait(locked_keys).unwrap();
533 }
534 locked_keys.insert(key_id);
535 KeyIdGuard(key_id)
536 }
537
538 /// This function attempts to acquire an exclusive lock on a given key id. If the
539 /// given key id is already taken the function returns None immediately. If a lock
540 /// can be acquired this function returns a guard object, that represents the
541 /// lifecycle of the acquired lock.
542 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
543 let mut locked_keys = self.locked_keys.lock().unwrap();
544 if locked_keys.insert(key_id) {
545 Some(KeyIdGuard(key_id))
546 } else {
547 None
548 }
549 }
550}
551
552impl KeyIdGuard {
553 /// Get the numeric key id of the locked key.
554 pub fn id(&self) -> i64 {
555 self.0
556 }
557}
558
559impl Drop for KeyIdGuard {
560 fn drop(&mut self) {
561 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
562 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800563 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800564 KEY_ID_LOCK.cond_var.notify_all();
565 }
566}
567
Max Bires8e93d2b2021-01-14 13:17:59 -0800568/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700569#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800570pub struct CertificateInfo {
571 cert: Option<Vec<u8>>,
572 cert_chain: Option<Vec<u8>>,
573}
574
575impl CertificateInfo {
576 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
577 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
578 Self { cert, cert_chain }
579 }
580
581 /// Take the cert
582 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
583 self.cert.take()
584 }
585
586 /// Take the cert chain
587 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
588 self.cert_chain.take()
589 }
590}
591
Max Bires2b2e6562020-09-22 11:22:36 -0700592/// This type represents a certificate chain with a private key corresponding to the leaf
593/// 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 -0700594pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800595 /// A KM key blob
596 pub private_key: ZVec,
597 /// A batch cert for private_key
598 pub batch_cert: Vec<u8>,
599 /// A full certificate chain from root signing authority to private_key, including batch_cert
600 /// for convenience.
601 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700602}
603
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700604/// This type represents a Keystore 2.0 key entry.
605/// An entry has a unique `id` by which it can be found in the database.
606/// It has a security level field, key parameters, and three optional fields
607/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800608#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700609pub struct KeyEntry {
610 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800611 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700612 cert: Option<Vec<u8>>,
613 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800614 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700615 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800616 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800617 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700618}
619
620impl KeyEntry {
621 /// Returns the unique id of the Key entry.
622 pub fn id(&self) -> i64 {
623 self.id
624 }
625 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800626 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
627 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700628 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800629 /// Extracts the Optional KeyMint blob including its metadata.
630 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
631 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700632 }
633 /// Exposes the optional public certificate.
634 pub fn cert(&self) -> &Option<Vec<u8>> {
635 &self.cert
636 }
637 /// Extracts the optional public certificate.
638 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
639 self.cert.take()
640 }
641 /// Exposes the optional public certificate chain.
642 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
643 &self.cert_chain
644 }
645 /// Extracts the optional public certificate_chain.
646 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
647 self.cert_chain.take()
648 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800649 /// Returns the uuid of the owning KeyMint instance.
650 pub fn km_uuid(&self) -> &Uuid {
651 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700652 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700653 /// Exposes the key parameters of this key entry.
654 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
655 &self.parameters
656 }
657 /// Consumes this key entry and extracts the keyparameters from it.
658 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
659 self.parameters
660 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800661 /// Exposes the key metadata of this key entry.
662 pub fn metadata(&self) -> &KeyMetaData {
663 &self.metadata
664 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800665 /// This returns true if the entry is a pure certificate entry with no
666 /// private key component.
667 pub fn pure_cert(&self) -> bool {
668 self.pure_cert
669 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000670 /// Consumes this key entry and extracts the keyparameters and metadata from it.
671 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
672 (self.parameters, self.metadata)
673 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700674}
675
676/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800677#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700678pub struct SubComponentType(u32);
679impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800680 /// Persistent identifier for a key blob.
681 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700682 /// Persistent identifier for a certificate blob.
683 pub const CERT: SubComponentType = Self(1);
684 /// Persistent identifier for a certificate chain blob.
685 pub const CERT_CHAIN: SubComponentType = Self(2);
686}
687
688impl ToSql for SubComponentType {
689 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
690 self.0.to_sql()
691 }
692}
693
694impl FromSql for SubComponentType {
695 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
696 Ok(Self(u32::column_result(value)?))
697 }
698}
699
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800700/// This trait is private to the database module. It is used to convey whether or not the garbage
701/// collector shall be invoked after a database access. All closures passed to
702/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
703/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
704/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
705/// `.need_gc()`.
706trait DoGc<T> {
707 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
708
709 fn no_gc(self) -> Result<(bool, T)>;
710
711 fn need_gc(self) -> Result<(bool, T)>;
712}
713
714impl<T> DoGc<T> for Result<T> {
715 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
716 self.map(|r| (need_gc, r))
717 }
718
719 fn no_gc(self) -> Result<(bool, T)> {
720 self.do_gc(false)
721 }
722
723 fn need_gc(self) -> Result<(bool, T)> {
724 self.do_gc(true)
725 }
726}
727
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700728/// KeystoreDB wraps a connection to an SQLite database and tracks its
729/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700730pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700731 conn: Connection,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800732 gc: Option<Gc>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700733}
734
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000735/// Database representation of the monotonic time retrieved from the system call clock_gettime with
736/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
737#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
738pub struct MonotonicRawTime(i64);
739
740impl MonotonicRawTime {
741 /// Constructs a new MonotonicRawTime
742 pub fn now() -> Self {
743 Self(get_current_time_in_seconds())
744 }
745
David Drysdale0e45a612021-02-25 17:24:36 +0000746 /// Constructs a new MonotonicRawTime from a given number of seconds.
747 pub fn from_secs(val: i64) -> Self {
748 Self(val)
749 }
750
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000751 /// Returns the integer value of MonotonicRawTime as i64
752 pub fn seconds(&self) -> i64 {
753 self.0
754 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800755
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000756 /// Returns the value of MonotonicRawTime in milli seconds as i64
757 pub fn milli_seconds(&self) -> i64 {
758 self.0 * 1000
759 }
760
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800761 /// Like i64::checked_sub.
762 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
763 self.0.checked_sub(other.0).map(Self)
764 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000765}
766
767impl ToSql for MonotonicRawTime {
768 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
769 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
770 }
771}
772
773impl FromSql for MonotonicRawTime {
774 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
775 Ok(Self(i64::column_result(value)?))
776 }
777}
778
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000779/// This struct encapsulates the information to be stored in the database about the auth tokens
780/// received by keystore.
781pub struct AuthTokenEntry {
782 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000783 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000784}
785
786impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000787 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000788 AuthTokenEntry { auth_token, time_received }
789 }
790
791 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800792 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000793 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800794 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
795 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000796 })
797 }
798
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000799 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800800 pub fn auth_token(&self) -> &HardwareAuthToken {
801 &self.auth_token
802 }
803
804 /// Returns the auth token wrapped by the AuthTokenEntry
805 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000806 self.auth_token
807 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800808
809 /// Returns the time that this auth token was received.
810 pub fn time_received(&self) -> MonotonicRawTime {
811 self.time_received
812 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000813
814 /// Returns the challenge value of the auth token.
815 pub fn challenge(&self) -> i64 {
816 self.auth_token.challenge
817 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818}
819
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800820/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
821/// This object does not allow access to the database connection. But it keeps a database
822/// connection alive in order to keep the in memory per boot database alive.
823pub struct PerBootDbKeepAlive(Connection);
824
Joel Galenson26f4d012020-07-17 14:57:21 -0700825impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800826 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800827 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
828
829 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
830 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
831 let conn = Connection::open_in_memory()
832 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
833
834 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
835 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
836 Ok(PerBootDbKeepAlive(conn))
837 }
838
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700839 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800840 /// files persistent.sqlite and perboot.sqlite in the given directory.
841 /// It also attempts to initialize all of the tables.
842 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700843 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800844 pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800845 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800846 let mut persistent_path = db_root.to_path_buf();
847 persistent_path.push("persistent.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700848
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800849 // Now convert them to strings prefixed with "file:"
850 let mut persistent_path_str = "file:".to_owned();
851 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800852
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800853 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800854
Janis Danisevskis66784c42021-01-27 08:40:25 -0800855 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
856 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
857
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800858 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800859 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800860 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800861 })?;
862 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700863 }
864
Janis Danisevskis66784c42021-01-27 08:40:25 -0800865 fn init_tables(tx: &Transaction) -> Result<()> {
866 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700867 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700868 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800869 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700870 domain INTEGER,
871 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800872 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800873 state INTEGER,
874 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700875 NO_PARAMS,
876 )
877 .context("Failed to initialize \"keyentry\" table.")?;
878
Janis Danisevskis66784c42021-01-27 08:40:25 -0800879 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800880 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
881 ON keyentry(id);",
882 NO_PARAMS,
883 )
884 .context("Failed to create index keyentry_id_index.")?;
885
886 tx.execute(
887 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
888 ON keyentry(domain, namespace, alias);",
889 NO_PARAMS,
890 )
891 .context("Failed to create index keyentry_domain_namespace_index.")?;
892
893 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700894 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
895 id INTEGER PRIMARY KEY,
896 subcomponent_type INTEGER,
897 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800898 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700899 NO_PARAMS,
900 )
901 .context("Failed to initialize \"blobentry\" table.")?;
902
Janis Danisevskis66784c42021-01-27 08:40:25 -0800903 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800904 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
905 ON blobentry(keyentryid);",
906 NO_PARAMS,
907 )
908 .context("Failed to create index blobentry_keyentryid_index.")?;
909
910 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800911 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
912 id INTEGER PRIMARY KEY,
913 blobentryid INTEGER,
914 tag INTEGER,
915 data ANY,
916 UNIQUE (blobentryid, tag));",
917 NO_PARAMS,
918 )
919 .context("Failed to initialize \"blobmetadata\" table.")?;
920
921 tx.execute(
922 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
923 ON blobmetadata(blobentryid);",
924 NO_PARAMS,
925 )
926 .context("Failed to create index blobmetadata_blobentryid_index.")?;
927
928 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700929 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000930 keyentryid INTEGER,
931 tag INTEGER,
932 data ANY,
933 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700934 NO_PARAMS,
935 )
936 .context("Failed to initialize \"keyparameter\" table.")?;
937
Janis Danisevskis66784c42021-01-27 08:40:25 -0800938 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800939 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
940 ON keyparameter(keyentryid);",
941 NO_PARAMS,
942 )
943 .context("Failed to create index keyparameter_keyentryid_index.")?;
944
945 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800946 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
947 keyentryid INTEGER,
948 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000949 data ANY,
950 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800951 NO_PARAMS,
952 )
953 .context("Failed to initialize \"keymetadata\" table.")?;
954
Janis Danisevskis66784c42021-01-27 08:40:25 -0800955 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800956 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
957 ON keymetadata(keyentryid);",
958 NO_PARAMS,
959 )
960 .context("Failed to create index keymetadata_keyentryid_index.")?;
961
962 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800963 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700964 id INTEGER UNIQUE,
965 grantee INTEGER,
966 keyentryid INTEGER,
967 access_vector INTEGER);",
968 NO_PARAMS,
969 )
970 .context("Failed to initialize \"grant\" table.")?;
971
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000972 //TODO: only drop the following two perboot tables if this is the first start up
973 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800974 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000975 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800976 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000977 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
978 id INTEGER PRIMARY KEY,
979 challenge INTEGER,
980 user_id INTEGER,
981 auth_id INTEGER,
982 authenticator_type INTEGER,
983 timestamp INTEGER,
984 mac BLOB,
985 time_received INTEGER,
986 UNIQUE(user_id, auth_id, authenticator_type));",
987 NO_PARAMS,
988 )
989 .context("Failed to initialize \"authtoken\" table.")?;
990
Janis Danisevskis66784c42021-01-27 08:40:25 -0800991 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000992 // .context("Failed to drop perboot.metadata table")?;
993 // metadata table stores certain miscellaneous information required for keystore functioning
994 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800995 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000996 "CREATE TABLE IF NOT EXISTS perboot.metadata (
997 key TEXT,
998 value BLOB,
999 UNIQUE(key));",
1000 NO_PARAMS,
1001 )
1002 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -07001003 Ok(())
1004 }
1005
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001006 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
1007 let conn =
1008 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1009
Janis Danisevskis66784c42021-01-27 08:40:25 -08001010 loop {
1011 if let Err(e) = conn
1012 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1013 .context("Failed to attach database persistent.")
1014 {
1015 if Self::is_locked_error(&e) {
1016 std::thread::sleep(std::time::Duration::from_micros(500));
1017 continue;
1018 } else {
1019 return Err(e);
1020 }
1021 }
1022 break;
1023 }
1024 loop {
1025 if let Err(e) = conn
1026 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1027 .context("Failed to attach database perboot.")
1028 {
1029 if Self::is_locked_error(&e) {
1030 std::thread::sleep(std::time::Duration::from_micros(500));
1031 continue;
1032 } else {
1033 return Err(e);
1034 }
1035 }
1036 break;
1037 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001038
1039 Ok(conn)
1040 }
1041
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001042 /// This function is intended to be used by the garbage collector.
1043 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1044 /// key blob that might need special handling by the garbage collector.
1045 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1046 /// need special handling and returns None.
1047 pub fn handle_next_superseded_blob(
1048 &mut self,
1049 blob_id_to_delete: Option<i64>,
1050 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001051 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001052 // Delete the given blob if one was given.
1053 if let Some(blob_id_to_delete) = blob_id_to_delete {
1054 tx.execute(
1055 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1056 params![blob_id_to_delete],
1057 )
1058 .context("Trying to delete blob metadata.")?;
1059 tx.execute(
1060 "DELETE FROM persistent.blobentry WHERE id = ?;",
1061 params![blob_id_to_delete],
1062 )
1063 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001064 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001065
1066 // Find another superseded keyblob load its metadata and return it.
1067 if let Some((blob_id, blob)) = tx
1068 .query_row(
1069 "SELECT id, blob FROM persistent.blobentry
1070 WHERE subcomponent_type = ?
1071 AND (
1072 id NOT IN (
1073 SELECT MAX(id) FROM persistent.blobentry
1074 WHERE subcomponent_type = ?
1075 GROUP BY keyentryid, subcomponent_type
1076 )
1077 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1078 );",
1079 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1080 |row| Ok((row.get(0)?, row.get(1)?)),
1081 )
1082 .optional()
1083 .context("Trying to query superseded blob.")?
1084 {
1085 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1086 .context("Trying to load blob metadata.")?;
1087 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1088 }
1089
1090 // We did not find any superseded key blob, so let's remove other superseded blob in
1091 // one transaction.
1092 tx.execute(
1093 "DELETE FROM persistent.blobentry
1094 WHERE NOT subcomponent_type = ?
1095 AND (
1096 id NOT IN (
1097 SELECT MAX(id) FROM persistent.blobentry
1098 WHERE NOT subcomponent_type = ?
1099 GROUP BY keyentryid, subcomponent_type
1100 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1101 );",
1102 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1103 )
1104 .context("Trying to purge superseded blobs.")?;
1105
1106 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001107 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001108 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001109 }
1110
1111 /// This maintenance function should be called only once before the database is used for the
1112 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1113 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1114 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1115 /// Keystore crashed at some point during key generation. Callers may want to log such
1116 /// occurrences.
1117 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1118 /// it to `KeyLifeCycle::Live` may have grants.
1119 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001120 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1121 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001122 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1123 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1124 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001125 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001126 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001127 })
1128 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001129 }
1130
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001131 /// Checks if a key exists with given key type and key descriptor properties.
1132 pub fn key_exists(
1133 &mut self,
1134 domain: Domain,
1135 nspace: i64,
1136 alias: &str,
1137 key_type: KeyType,
1138 ) -> Result<bool> {
1139 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1140 let key_descriptor =
1141 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1142 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1143 match result {
1144 Ok(_) => Ok(true),
1145 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1146 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1147 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1148 },
1149 }
1150 .no_gc()
1151 })
1152 .context("In key_exists.")
1153 }
1154
Hasini Gunasingheda895552021-01-27 19:34:37 +00001155 /// Stores a super key in the database.
1156 pub fn store_super_key(
1157 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001158 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001159 key_type: &SuperKeyType,
1160 blob: &[u8],
1161 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001162 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001163 ) -> Result<KeyEntry> {
1164 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1165 let key_id = Self::insert_with_retry(|id| {
1166 tx.execute(
1167 "INSERT into persistent.keyentry
1168 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001169 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001170 params![
1171 id,
1172 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001173 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001174 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001175 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001176 KeyLifeCycle::Live,
1177 &KEYSTORE_UUID,
1178 ],
1179 )
1180 })
1181 .context("Failed to insert into keyentry table.")?;
1182
Paul Crowley8d5b2532021-03-19 10:53:07 -07001183 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1184
Hasini Gunasingheda895552021-01-27 19:34:37 +00001185 Self::set_blob_internal(
1186 &tx,
1187 key_id,
1188 SubComponentType::KEY_BLOB,
1189 Some(blob),
1190 Some(blob_metadata),
1191 )
1192 .context("Failed to store key blob.")?;
1193
1194 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1195 .context("Trying to load key components.")
1196 .no_gc()
1197 })
1198 .context("In store_super_key.")
1199 }
1200
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001201 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001202 pub fn load_super_key(
1203 &mut self,
1204 key_type: &SuperKeyType,
1205 user_id: u32,
1206 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001207 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1208 let key_descriptor = KeyDescriptor {
1209 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001210 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001211 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001212 blob: None,
1213 };
1214 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1215 match id {
1216 Ok(id) => {
1217 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1218 .context("In load_super_key. Failed to load key entry.")?;
1219 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1220 }
1221 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1222 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1223 _ => Err(error).context("In load_super_key."),
1224 },
1225 }
1226 .no_gc()
1227 })
1228 .context("In load_super_key.")
1229 }
1230
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001231 /// Atomically loads a key entry and associated metadata or creates it using the
1232 /// callback create_new_key callback. The callback is called during a database
1233 /// transaction. This means that implementers should be mindful about using
1234 /// blocking operations such as IPC or grabbing mutexes.
1235 pub fn get_or_create_key_with<F>(
1236 &mut self,
1237 domain: Domain,
1238 namespace: i64,
1239 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001240 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001241 create_new_key: F,
1242 ) -> Result<(KeyIdGuard, KeyEntry)>
1243 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001244 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001245 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001246 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1247 let id = {
1248 let mut stmt = tx
1249 .prepare(
1250 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001251 WHERE
1252 key_type = ?
1253 AND domain = ?
1254 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001255 AND alias = ?
1256 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001257 )
1258 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1259 let mut rows = stmt
1260 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1261 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001262
Janis Danisevskis66784c42021-01-27 08:40:25 -08001263 db_utils::with_rows_extract_one(&mut rows, |row| {
1264 Ok(match row {
1265 Some(r) => r.get(0).context("Failed to unpack id.")?,
1266 None => None,
1267 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001268 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001269 .context("In get_or_create_key_with.")?
1270 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001271
Janis Danisevskis66784c42021-01-27 08:40:25 -08001272 let (id, entry) = match id {
1273 Some(id) => (
1274 id,
1275 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1276 .context("In get_or_create_key_with.")?,
1277 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001278
Janis Danisevskis66784c42021-01-27 08:40:25 -08001279 None => {
1280 let id = Self::insert_with_retry(|id| {
1281 tx.execute(
1282 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001283 (id, key_type, domain, namespace, alias, state, km_uuid)
1284 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001285 params![
1286 id,
1287 KeyType::Super,
1288 domain.0,
1289 namespace,
1290 alias,
1291 KeyLifeCycle::Live,
1292 km_uuid,
1293 ],
1294 )
1295 })
1296 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001297
Janis Danisevskis66784c42021-01-27 08:40:25 -08001298 let (blob, metadata) =
1299 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001300 Self::set_blob_internal(
1301 &tx,
1302 id,
1303 SubComponentType::KEY_BLOB,
1304 Some(&blob),
1305 Some(&metadata),
1306 )
Paul Crowley7a658392021-03-18 17:08:20 -07001307 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001308 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001309 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001310 KeyEntry {
1311 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001312 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001313 pure_cert: false,
1314 ..Default::default()
1315 },
1316 )
1317 }
1318 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001319 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001320 })
1321 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001322 }
1323
Janis Danisevskis66784c42021-01-27 08:40:25 -08001324 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1325 /// waiting for the database file to become available. This makes it
1326 /// impossible to successfully recover from a locked database when the
1327 /// transaction holding the device busy is in the same process on a
1328 /// different connection. As a result the busy handler has to time out and
1329 /// fail in order to make progress.
1330 ///
1331 /// Instead, we set the busy handler to None (return immediately). And catch
1332 /// Busy and Locked errors (the latter occur on in memory databases with
1333 /// shared cache, e.g., the per-boot database.) and restart the transaction
1334 /// after a grace period of half a millisecond.
1335 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001336 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001337 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1338 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001339 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1340 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001341 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001342 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001343 loop {
1344 match self
1345 .conn
1346 .transaction_with_behavior(behavior)
1347 .context("In with_transaction.")
1348 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1349 .and_then(|(result, tx)| {
1350 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1351 Ok(result)
1352 }) {
1353 Ok(result) => break Ok(result),
1354 Err(e) => {
1355 if Self::is_locked_error(&e) {
1356 std::thread::sleep(std::time::Duration::from_micros(500));
1357 continue;
1358 } else {
1359 return Err(e).context("In with_transaction.");
1360 }
1361 }
1362 }
1363 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001364 .map(|(need_gc, result)| {
1365 if need_gc {
1366 if let Some(ref gc) = self.gc {
1367 gc.notify_gc();
1368 }
1369 }
1370 result
1371 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001372 }
1373
1374 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001375 matches!(
1376 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1377 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1378 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1379 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001380 }
1381
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001382 /// Creates a new key entry and allocates a new randomized id for the new key.
1383 /// The key id gets associated with a domain and namespace but not with an alias.
1384 /// To complete key generation `rebind_alias` should be called after all of the
1385 /// key artifacts, i.e., blobs and parameters have been associated with the new
1386 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1387 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001388 pub fn create_key_entry(
1389 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001390 domain: &Domain,
1391 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001392 km_uuid: &Uuid,
1393 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001394 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001395 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001396 })
1397 .context("In create_key_entry.")
1398 }
1399
1400 fn create_key_entry_internal(
1401 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001402 domain: &Domain,
1403 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001404 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001405 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001406 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001407 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001408 _ => {
1409 return Err(KsError::sys())
1410 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1411 }
1412 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001413 Ok(KEY_ID_LOCK.get(
1414 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001415 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001416 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001417 (id, key_type, domain, namespace, alias, state, km_uuid)
1418 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001419 params![
1420 id,
1421 KeyType::Client,
1422 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001423 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001424 KeyLifeCycle::Existing,
1425 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001426 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001427 )
1428 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001429 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001430 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001431 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001432
Max Bires2b2e6562020-09-22 11:22:36 -07001433 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1434 /// The key id gets associated with a domain and namespace later but not with an alias. The
1435 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1436 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1437 /// a key.
1438 pub fn create_attestation_key_entry(
1439 &mut self,
1440 maced_public_key: &[u8],
1441 raw_public_key: &[u8],
1442 private_key: &[u8],
1443 km_uuid: &Uuid,
1444 ) -> Result<()> {
1445 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1446 let key_id = KEY_ID_LOCK.get(
1447 Self::insert_with_retry(|id| {
1448 tx.execute(
1449 "INSERT into persistent.keyentry
1450 (id, key_type, domain, namespace, alias, state, km_uuid)
1451 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1452 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1453 )
1454 })
1455 .context("In create_key_entry")?,
1456 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001457 Self::set_blob_internal(
1458 &tx,
1459 key_id.0,
1460 SubComponentType::KEY_BLOB,
1461 Some(private_key),
1462 None,
1463 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001464 let mut metadata = KeyMetaData::new();
1465 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1466 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1467 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001468 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001469 })
1470 .context("In create_attestation_key_entry")
1471 }
1472
Janis Danisevskis377d1002021-01-27 19:07:48 -08001473 /// Set a new blob and associates it with the given key id. Each blob
1474 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001475 /// Each key can have one of each sub component type associated. If more
1476 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001477 /// will get garbage collected.
1478 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1479 /// removed by setting blob to None.
1480 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001481 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001482 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001483 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001484 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001485 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001486 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001487 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001488 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001489 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001490 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001491 }
1492
Janis Danisevskiseed69842021-02-18 20:04:10 -08001493 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1494 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1495 /// We use this to insert key blobs into the database which can then be garbage collected
1496 /// lazily by the key garbage collector.
1497 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
1498 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1499 Self::set_blob_internal(
1500 &tx,
1501 Self::UNASSIGNED_KEY_ID,
1502 SubComponentType::KEY_BLOB,
1503 Some(blob),
1504 Some(blob_metadata),
1505 )
1506 .need_gc()
1507 })
1508 .context("In set_deleted_blob.")
1509 }
1510
Janis Danisevskis377d1002021-01-27 19:07:48 -08001511 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001512 tx: &Transaction,
1513 key_id: i64,
1514 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001515 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001516 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001517 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001518 match (blob, sc_type) {
1519 (Some(blob), _) => {
1520 tx.execute(
1521 "INSERT INTO persistent.blobentry
1522 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1523 params![sc_type, key_id, blob],
1524 )
1525 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001526 if let Some(blob_metadata) = blob_metadata {
1527 let blob_id = tx
1528 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1529 row.get(0)
1530 })
1531 .context("In set_blob_internal: Failed to get new blob id.")?;
1532 blob_metadata
1533 .store_in_db(blob_id, tx)
1534 .context("In set_blob_internal: Trying to store blob metadata.")?;
1535 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001536 }
1537 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1538 tx.execute(
1539 "DELETE FROM persistent.blobentry
1540 WHERE subcomponent_type = ? AND keyentryid = ?;",
1541 params![sc_type, key_id],
1542 )
1543 .context("In set_blob_internal: Failed to delete blob.")?;
1544 }
1545 (None, _) => {
1546 return Err(KsError::sys())
1547 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1548 }
1549 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001550 Ok(())
1551 }
1552
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001553 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1554 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001555 #[cfg(test)]
1556 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001557 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001558 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001559 })
1560 .context("In insert_keyparameter.")
1561 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001562
Janis Danisevskis66784c42021-01-27 08:40:25 -08001563 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001564 tx: &Transaction,
1565 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001566 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001567 ) -> Result<()> {
1568 let mut stmt = tx
1569 .prepare(
1570 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1571 VALUES (?, ?, ?, ?);",
1572 )
1573 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1574
Janis Danisevskis66784c42021-01-27 08:40:25 -08001575 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001576 stmt.insert(params![
1577 key_id.0,
1578 p.get_tag().0,
1579 p.key_parameter_value(),
1580 p.security_level().0
1581 ])
1582 .with_context(|| {
1583 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1584 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001585 }
1586 Ok(())
1587 }
1588
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001589 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001590 #[cfg(test)]
1591 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001592 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001593 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001594 })
1595 .context("In insert_key_metadata.")
1596 }
1597
Max Bires2b2e6562020-09-22 11:22:36 -07001598 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1599 /// on the public key.
1600 pub fn store_signed_attestation_certificate_chain(
1601 &mut self,
1602 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001603 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001604 cert_chain: &[u8],
1605 expiration_date: i64,
1606 km_uuid: &Uuid,
1607 ) -> Result<()> {
1608 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1609 let mut stmt = tx
1610 .prepare(
1611 "SELECT keyentryid
1612 FROM persistent.keymetadata
1613 WHERE tag = ? AND data = ? AND keyentryid IN
1614 (SELECT id
1615 FROM persistent.keyentry
1616 WHERE
1617 alias IS NULL AND
1618 domain IS NULL AND
1619 namespace IS NULL AND
1620 key_type = ? AND
1621 km_uuid = ?);",
1622 )
1623 .context("Failed to store attestation certificate chain.")?;
1624 let mut rows = stmt
1625 .query(params![
1626 KeyMetaData::AttestationRawPubKey,
1627 raw_public_key,
1628 KeyType::Attestation,
1629 km_uuid
1630 ])
1631 .context("Failed to fetch keyid")?;
1632 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1633 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1634 .get(0)
1635 .context("Failed to unpack id.")
1636 })
1637 .context("Failed to get key_id.")?;
1638 let num_updated = tx
1639 .execute(
1640 "UPDATE persistent.keyentry
1641 SET alias = ?
1642 WHERE id = ?;",
1643 params!["signed", key_id],
1644 )
1645 .context("Failed to update alias.")?;
1646 if num_updated != 1 {
1647 return Err(KsError::sys()).context("Alias not updated for the key.");
1648 }
1649 let mut metadata = KeyMetaData::new();
1650 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1651 expiration_date,
1652 )));
1653 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001654 Self::set_blob_internal(
1655 &tx,
1656 key_id,
1657 SubComponentType::CERT_CHAIN,
1658 Some(cert_chain),
1659 None,
1660 )
1661 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001662 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1663 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001664 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001665 })
1666 .context("In store_signed_attestation_certificate_chain: ")
1667 }
1668
1669 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1670 /// currently have a key assigned to it.
1671 pub fn assign_attestation_key(
1672 &mut self,
1673 domain: Domain,
1674 namespace: i64,
1675 km_uuid: &Uuid,
1676 ) -> Result<()> {
1677 match domain {
1678 Domain::APP | Domain::SELINUX => {}
1679 _ => {
1680 return Err(KsError::sys()).context(format!(
1681 concat!(
1682 "In assign_attestation_key: Domain {:?} ",
1683 "must be either App or SELinux.",
1684 ),
1685 domain
1686 ));
1687 }
1688 }
1689 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1690 let result = tx
1691 .execute(
1692 "UPDATE persistent.keyentry
1693 SET domain=?1, namespace=?2
1694 WHERE
1695 id =
1696 (SELECT MIN(id)
1697 FROM persistent.keyentry
1698 WHERE ALIAS IS NOT NULL
1699 AND domain IS NULL
1700 AND key_type IS ?3
1701 AND state IS ?4
1702 AND km_uuid IS ?5)
1703 AND
1704 (SELECT COUNT(*)
1705 FROM persistent.keyentry
1706 WHERE domain=?1
1707 AND namespace=?2
1708 AND key_type IS ?3
1709 AND state IS ?4
1710 AND km_uuid IS ?5) = 0;",
1711 params![
1712 domain.0 as u32,
1713 namespace,
1714 KeyType::Attestation,
1715 KeyLifeCycle::Live,
1716 km_uuid,
1717 ],
1718 )
1719 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001720 if result == 0 {
1721 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1722 } else if result > 1 {
1723 return Err(KsError::sys())
1724 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001725 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001726 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001727 })
1728 .context("In assign_attestation_key: ")
1729 }
1730
1731 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1732 /// provisioning server, or the maximum number available if there are not num_keys number of
1733 /// entries in the table.
1734 pub fn fetch_unsigned_attestation_keys(
1735 &mut self,
1736 num_keys: i32,
1737 km_uuid: &Uuid,
1738 ) -> Result<Vec<Vec<u8>>> {
1739 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1740 let mut stmt = tx
1741 .prepare(
1742 "SELECT data
1743 FROM persistent.keymetadata
1744 WHERE tag = ? AND keyentryid IN
1745 (SELECT id
1746 FROM persistent.keyentry
1747 WHERE
1748 alias IS NULL AND
1749 domain IS NULL AND
1750 namespace IS NULL AND
1751 key_type = ? AND
1752 km_uuid = ?
1753 LIMIT ?);",
1754 )
1755 .context("Failed to prepare statement")?;
1756 let rows = stmt
1757 .query_map(
1758 params![
1759 KeyMetaData::AttestationMacedPublicKey,
1760 KeyType::Attestation,
1761 km_uuid,
1762 num_keys
1763 ],
1764 |row| Ok(row.get(0)?),
1765 )?
1766 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1767 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001768 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001769 })
1770 .context("In fetch_unsigned_attestation_keys")
1771 }
1772
1773 /// Removes any keys that have expired as of the current time. Returns the number of keys
1774 /// marked unreferenced that are bound to be garbage collected.
1775 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
1776 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1777 let mut stmt = tx
1778 .prepare(
1779 "SELECT keyentryid, data
1780 FROM persistent.keymetadata
1781 WHERE tag = ? AND keyentryid IN
1782 (SELECT id
1783 FROM persistent.keyentry
1784 WHERE key_type = ?);",
1785 )
1786 .context("Failed to prepare query")?;
1787 let key_ids_to_check = stmt
1788 .query_map(
1789 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1790 |row| Ok((row.get(0)?, row.get(1)?)),
1791 )?
1792 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1793 .context("Failed to get date metadata")?;
1794 let curr_time = DateTime::from_millis_epoch(
1795 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1796 );
1797 let mut num_deleted = 0;
1798 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1799 if Self::mark_unreferenced(&tx, id)? {
1800 num_deleted += 1;
1801 }
1802 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001803 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001804 })
1805 .context("In delete_expired_attestation_keys: ")
1806 }
1807
Max Bires60d7ed12021-03-05 15:59:22 -08001808 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1809 /// they are in. This is useful primarily as a testing mechanism.
1810 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
1811 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1812 let mut stmt = tx
1813 .prepare(
1814 "SELECT id FROM persistent.keyentry
1815 WHERE key_type IS ?;",
1816 )
1817 .context("Failed to prepare statement")?;
1818 let keys_to_delete = stmt
1819 .query_map(params![KeyType::Attestation], |row| Ok(row.get(0)?))?
1820 .collect::<rusqlite::Result<Vec<i64>>>()
1821 .context("Failed to execute statement")?;
1822 let num_deleted = keys_to_delete
1823 .iter()
1824 .map(|id| Self::mark_unreferenced(&tx, *id))
1825 .collect::<Result<Vec<bool>>>()
1826 .context("Failed to execute mark_unreferenced on a keyid")?
1827 .into_iter()
1828 .filter(|result| *result)
1829 .count() as i64;
1830 Ok(num_deleted).do_gc(num_deleted != 0)
1831 })
1832 .context("In delete_all_attestation_keys: ")
1833 }
1834
Max Bires2b2e6562020-09-22 11:22:36 -07001835 /// Counts the number of keys that will expire by the provided epoch date and the number of
1836 /// keys not currently assigned to a domain.
1837 pub fn get_attestation_pool_status(
1838 &mut self,
1839 date: i64,
1840 km_uuid: &Uuid,
1841 ) -> Result<AttestationPoolStatus> {
1842 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1843 let mut stmt = tx.prepare(
1844 "SELECT data
1845 FROM persistent.keymetadata
1846 WHERE tag = ? AND keyentryid IN
1847 (SELECT id
1848 FROM persistent.keyentry
1849 WHERE alias IS NOT NULL
1850 AND key_type = ?
1851 AND km_uuid = ?
1852 AND state = ?);",
1853 )?;
1854 let times = stmt
1855 .query_map(
1856 params![
1857 KeyMetaData::AttestationExpirationDate,
1858 KeyType::Attestation,
1859 km_uuid,
1860 KeyLifeCycle::Live
1861 ],
1862 |row| Ok(row.get(0)?),
1863 )?
1864 .collect::<rusqlite::Result<Vec<DateTime>>>()
1865 .context("Failed to execute metadata statement")?;
1866 let expiring =
1867 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1868 as i32;
1869 stmt = tx.prepare(
1870 "SELECT alias, domain
1871 FROM persistent.keyentry
1872 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1873 )?;
1874 let rows = stmt
1875 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1876 Ok((row.get(0)?, row.get(1)?))
1877 })?
1878 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1879 .context("Failed to execute keyentry statement")?;
1880 let mut unassigned = 0i32;
1881 let mut attested = 0i32;
1882 let total = rows.len() as i32;
1883 for (alias, domain) in rows {
1884 match (alias, domain) {
1885 (Some(_alias), None) => {
1886 attested += 1;
1887 unassigned += 1;
1888 }
1889 (Some(_alias), Some(_domain)) => {
1890 attested += 1;
1891 }
1892 _ => {}
1893 }
1894 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001895 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001896 })
1897 .context("In get_attestation_pool_status: ")
1898 }
1899
1900 /// Fetches the private key and corresponding certificate chain assigned to a
1901 /// domain/namespace pair. Will either return nothing if the domain/namespace is
1902 /// not assigned, or one CertificateChain.
1903 pub fn retrieve_attestation_key_and_cert_chain(
1904 &mut self,
1905 domain: Domain,
1906 namespace: i64,
1907 km_uuid: &Uuid,
1908 ) -> Result<Option<CertificateChain>> {
1909 match domain {
1910 Domain::APP | Domain::SELINUX => {}
1911 _ => {
1912 return Err(KsError::sys())
1913 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1914 }
1915 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001916 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1917 let mut stmt = tx.prepare(
1918 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07001919 FROM persistent.blobentry
1920 WHERE keyentryid IN
1921 (SELECT id
1922 FROM persistent.keyentry
1923 WHERE key_type = ?
1924 AND domain = ?
1925 AND namespace = ?
1926 AND state = ?
1927 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001928 )?;
1929 let rows = stmt
1930 .query_map(
1931 params![
1932 KeyType::Attestation,
1933 domain.0 as u32,
1934 namespace,
1935 KeyLifeCycle::Live,
1936 km_uuid
1937 ],
1938 |row| Ok((row.get(0)?, row.get(1)?)),
1939 )?
1940 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08001941 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001942 if rows.is_empty() {
1943 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08001944 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001945 return Err(KsError::sys()).context(format!(
1946 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08001947 "Expected to get a single attestation",
1948 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
1949 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001950 rows.len()
1951 ));
Max Bires2b2e6562020-09-22 11:22:36 -07001952 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001953 let mut km_blob: Vec<u8> = Vec::new();
1954 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08001955 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001956 for row in rows {
1957 let sub_type: SubComponentType = row.0;
1958 match sub_type {
1959 SubComponentType::KEY_BLOB => {
1960 km_blob = row.1;
1961 }
1962 SubComponentType::CERT_CHAIN => {
1963 cert_chain_blob = row.1;
1964 }
Max Biresb2e1d032021-02-08 21:35:05 -08001965 SubComponentType::CERT => {
1966 batch_cert_blob = row.1;
1967 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001968 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
1969 }
1970 }
1971 Ok(Some(CertificateChain {
1972 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08001973 batch_cert: batch_cert_blob,
1974 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001975 }))
1976 .no_gc()
1977 })
Max Biresb2e1d032021-02-08 21:35:05 -08001978 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07001979 }
1980
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001981 /// Updates the alias column of the given key id `newid` with the given alias,
1982 /// and atomically, removes the alias, domain, and namespace from another row
1983 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001984 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1985 /// collector.
1986 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001987 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001988 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001989 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001990 domain: &Domain,
1991 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001992 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001993 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001994 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001995 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001996 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001997 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001998 domain
1999 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002000 }
2001 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002002 let updated = tx
2003 .execute(
2004 "UPDATE persistent.keyentry
2005 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002006 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002007 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2008 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002009 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002010 let result = tx
2011 .execute(
2012 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002013 SET alias = ?, state = ?
2014 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2015 params![
2016 alias,
2017 KeyLifeCycle::Live,
2018 newid.0,
2019 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002020 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002021 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002022 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002023 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002024 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002025 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002026 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002027 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002028 result
2029 ));
2030 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002031 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002032 }
2033
2034 /// Store a new key in a single transaction.
2035 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2036 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002037 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2038 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002039 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002040 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002041 key: &KeyDescriptor,
2042 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002043 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002044 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002045 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002046 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002047 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002048 let (alias, domain, namespace) = match key {
2049 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2050 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2051 (alias, key.domain, nspace)
2052 }
2053 _ => {
2054 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2055 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2056 }
2057 };
2058 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002059 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002060 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002061 let (blob, blob_metadata) = *blob_info;
2062 Self::set_blob_internal(
2063 tx,
2064 key_id.id(),
2065 SubComponentType::KEY_BLOB,
2066 Some(blob),
2067 Some(&blob_metadata),
2068 )
2069 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002070 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002071 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002072 .context("Trying to insert the certificate.")?;
2073 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002074 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002075 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002076 tx,
2077 key_id.id(),
2078 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002079 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002080 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002081 )
2082 .context("Trying to insert the certificate chain.")?;
2083 }
2084 Self::insert_keyparameter_internal(tx, &key_id, params)
2085 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002086 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002087 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002088 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002089 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002090 })
2091 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002092 }
2093
Janis Danisevskis377d1002021-01-27 19:07:48 -08002094 /// Store a new certificate
2095 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2096 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002097 pub fn store_new_certificate(
2098 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002099 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002100 cert: &[u8],
2101 km_uuid: &Uuid,
2102 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002103 let (alias, domain, namespace) = match key {
2104 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2105 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2106 (alias, key.domain, nspace)
2107 }
2108 _ => {
2109 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2110 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2111 )
2112 }
2113 };
2114 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002115 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002116 .context("Trying to create new key entry.")?;
2117
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002118 Self::set_blob_internal(
2119 tx,
2120 key_id.id(),
2121 SubComponentType::CERT_CHAIN,
2122 Some(cert),
2123 None,
2124 )
2125 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002126
2127 let mut metadata = KeyMetaData::new();
2128 metadata.add(KeyMetaEntry::CreationDate(
2129 DateTime::now().context("Trying to make creation time.")?,
2130 ));
2131
2132 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2133
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002134 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002135 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002136 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002137 })
2138 .context("In store_new_certificate.")
2139 }
2140
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002141 // Helper function loading the key_id given the key descriptor
2142 // tuple comprising domain, namespace, and alias.
2143 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002144 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002145 let alias = key
2146 .alias
2147 .as_ref()
2148 .map_or_else(|| Err(KsError::sys()), Ok)
2149 .context("In load_key_entry_id: Alias must be specified.")?;
2150 let mut stmt = tx
2151 .prepare(
2152 "SELECT id FROM persistent.keyentry
2153 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002154 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002155 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002156 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002157 AND alias = ?
2158 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002159 )
2160 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2161 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002162 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002163 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002164 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002165 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002166 .get(0)
2167 .context("Failed to unpack id.")
2168 })
2169 .context("In load_key_entry_id.")
2170 }
2171
2172 /// This helper function completes the access tuple of a key, which is required
2173 /// to perform access control. The strategy depends on the `domain` field in the
2174 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002175 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002176 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002177 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002178 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002179 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002180 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002181 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002182 /// `namespace`.
2183 /// In each case the information returned is sufficient to perform the access
2184 /// check and the key id can be used to load further key artifacts.
2185 fn load_access_tuple(
2186 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002187 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002188 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002189 caller_uid: u32,
2190 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2191 match key.domain {
2192 // Domain App or SELinux. In this case we load the key_id from
2193 // the keyentry database for further loading of key components.
2194 // We already have the full access tuple to perform access control.
2195 // The only distinction is that we use the caller_uid instead
2196 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002197 // Domain::APP.
2198 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002199 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002200 if access_key.domain == Domain::APP {
2201 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002202 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002203 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002204 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002205
2206 Ok((key_id, access_key, None))
2207 }
2208
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002209 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002210 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002211 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002212 let mut stmt = tx
2213 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002214 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002215 WHERE grantee = ? AND id = ?;",
2216 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002217 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002218 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002219 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002220 .context("Domain:Grant: query failed.")?;
2221 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002222 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002223 let r =
2224 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002225 Ok((
2226 r.get(0).context("Failed to unpack key_id.")?,
2227 r.get(1).context("Failed to unpack access_vector.")?,
2228 ))
2229 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002230 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002231 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002232 }
2233
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002234 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002235 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002236 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002237 let (domain, namespace): (Domain, i64) = {
2238 let mut stmt = tx
2239 .prepare(
2240 "SELECT domain, namespace FROM persistent.keyentry
2241 WHERE
2242 id = ?
2243 AND state = ?;",
2244 )
2245 .context("Domain::KEY_ID: prepare statement failed")?;
2246 let mut rows = stmt
2247 .query(params![key.nspace, KeyLifeCycle::Live])
2248 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002249 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002250 let r =
2251 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002252 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002253 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002254 r.get(1).context("Failed to unpack namespace.")?,
2255 ))
2256 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002257 .context("Domain::KEY_ID.")?
2258 };
2259
2260 // We may use a key by id after loading it by grant.
2261 // In this case we have to check if the caller has a grant for this particular
2262 // key. We can skip this if we already know that the caller is the owner.
2263 // But we cannot know this if domain is anything but App. E.g. in the case
2264 // of Domain::SELINUX we have to speculatively check for grants because we have to
2265 // consult the SEPolicy before we know if the caller is the owner.
2266 let access_vector: Option<KeyPermSet> =
2267 if domain != Domain::APP || namespace != caller_uid as i64 {
2268 let access_vector: Option<i32> = tx
2269 .query_row(
2270 "SELECT access_vector FROM persistent.grant
2271 WHERE grantee = ? AND keyentryid = ?;",
2272 params![caller_uid as i64, key.nspace],
2273 |row| row.get(0),
2274 )
2275 .optional()
2276 .context("Domain::KEY_ID: query grant failed.")?;
2277 access_vector.map(|p| p.into())
2278 } else {
2279 None
2280 };
2281
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002282 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002283 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002284 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002285 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002286
Janis Danisevskis45760022021-01-19 16:34:10 -08002287 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002288 }
2289 _ => Err(anyhow!(KsError::sys())),
2290 }
2291 }
2292
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002293 fn load_blob_components(
2294 key_id: i64,
2295 load_bits: KeyEntryLoadBits,
2296 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002297 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002298 let mut stmt = tx
2299 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002300 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002301 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2302 )
2303 .context("In load_blob_components: prepare statement failed.")?;
2304
2305 let mut rows =
2306 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2307
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002308 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002309 let mut cert_blob: Option<Vec<u8>> = None;
2310 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002311 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002312 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002313 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002314 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002315 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002316 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2317 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002318 key_blob = Some((
2319 row.get(0).context("Failed to extract key blob id.")?,
2320 row.get(2).context("Failed to extract key blob.")?,
2321 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002322 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002323 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002324 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002325 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002326 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002327 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002328 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002329 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002330 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002331 (SubComponentType::CERT, _, _)
2332 | (SubComponentType::CERT_CHAIN, _, _)
2333 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002334 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2335 }
2336 Ok(())
2337 })
2338 .context("In load_blob_components.")?;
2339
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002340 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2341 Ok(Some((
2342 blob,
2343 BlobMetaData::load_from_db(blob_id, tx)
2344 .context("In load_blob_components: Trying to load blob_metadata.")?,
2345 )))
2346 })?;
2347
2348 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002349 }
2350
2351 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2352 let mut stmt = tx
2353 .prepare(
2354 "SELECT tag, data, security_level from persistent.keyparameter
2355 WHERE keyentryid = ?;",
2356 )
2357 .context("In load_key_parameters: prepare statement failed.")?;
2358
2359 let mut parameters: Vec<KeyParameter> = Vec::new();
2360
2361 let mut rows =
2362 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002363 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002364 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2365 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002366 parameters.push(
2367 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2368 .context("Failed to read KeyParameter.")?,
2369 );
2370 Ok(())
2371 })
2372 .context("In load_key_parameters.")?;
2373
2374 Ok(parameters)
2375 }
2376
Qi Wub9433b52020-12-01 14:52:46 +08002377 /// Decrements the usage count of a limited use key. This function first checks whether the
2378 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2379 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2380 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002381 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002382 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2383 let limit: Option<i32> = tx
2384 .query_row(
2385 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2386 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2387 |row| row.get(0),
2388 )
2389 .optional()
2390 .context("Trying to load usage count")?;
2391
2392 let limit = limit
2393 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2394 .context("The Key no longer exists. Key is exhausted.")?;
2395
2396 tx.execute(
2397 "UPDATE persistent.keyparameter
2398 SET data = data - 1
2399 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2400 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2401 )
2402 .context("Failed to update key usage count.")?;
2403
2404 match limit {
2405 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002406 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002407 .context("Trying to mark limited use key for deletion."),
2408 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002409 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002410 }
2411 })
2412 .context("In check_and_update_key_usage_count.")
2413 }
2414
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002415 /// Load a key entry by the given key descriptor.
2416 /// It uses the `check_permission` callback to verify if the access is allowed
2417 /// given the key access tuple read from the database using `load_access_tuple`.
2418 /// With `load_bits` the caller may specify which blobs shall be loaded from
2419 /// the blob database.
2420 pub fn load_key_entry(
2421 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002422 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002423 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002424 load_bits: KeyEntryLoadBits,
2425 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002426 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2427 ) -> Result<(KeyIdGuard, KeyEntry)> {
2428 loop {
2429 match self.load_key_entry_internal(
2430 key,
2431 key_type,
2432 load_bits,
2433 caller_uid,
2434 &check_permission,
2435 ) {
2436 Ok(result) => break Ok(result),
2437 Err(e) => {
2438 if Self::is_locked_error(&e) {
2439 std::thread::sleep(std::time::Duration::from_micros(500));
2440 continue;
2441 } else {
2442 return Err(e).context("In load_key_entry.");
2443 }
2444 }
2445 }
2446 }
2447 }
2448
2449 fn load_key_entry_internal(
2450 &mut self,
2451 key: &KeyDescriptor,
2452 key_type: KeyType,
2453 load_bits: KeyEntryLoadBits,
2454 caller_uid: u32,
2455 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002456 ) -> Result<(KeyIdGuard, KeyEntry)> {
2457 // KEY ID LOCK 1/2
2458 // If we got a key descriptor with a key id we can get the lock right away.
2459 // Otherwise we have to defer it until we know the key id.
2460 let key_id_guard = match key.domain {
2461 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2462 _ => None,
2463 };
2464
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002465 let tx = self
2466 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002467 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002468 .context("In load_key_entry: Failed to initialize transaction.")?;
2469
2470 // Load the key_id and complete the access control tuple.
2471 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002472 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2473 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002474
2475 // Perform access control. It is vital that we return here if the permission is denied.
2476 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002477 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002478
Janis Danisevskisaec14592020-11-12 09:41:49 -08002479 // KEY ID LOCK 2/2
2480 // If we did not get a key id lock by now, it was because we got a key descriptor
2481 // without a key id. At this point we got the key id, so we can try and get a lock.
2482 // However, we cannot block here, because we are in the middle of the transaction.
2483 // So first we try to get the lock non blocking. If that fails, we roll back the
2484 // transaction and block until we get the lock. After we successfully got the lock,
2485 // we start a new transaction and load the access tuple again.
2486 //
2487 // We don't need to perform access control again, because we already established
2488 // that the caller had access to the given key. But we need to make sure that the
2489 // key id still exists. So we have to load the key entry by key id this time.
2490 let (key_id_guard, tx) = match key_id_guard {
2491 None => match KEY_ID_LOCK.try_get(key_id) {
2492 None => {
2493 // Roll back the transaction.
2494 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002495
Janis Danisevskisaec14592020-11-12 09:41:49 -08002496 // Block until we have a key id lock.
2497 let key_id_guard = KEY_ID_LOCK.get(key_id);
2498
2499 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002500 let tx = self
2501 .conn
2502 .unchecked_transaction()
2503 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002504
2505 Self::load_access_tuple(
2506 &tx,
2507 // This time we have to load the key by the retrieved key id, because the
2508 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002509 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002510 domain: Domain::KEY_ID,
2511 nspace: key_id,
2512 ..Default::default()
2513 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002514 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002515 caller_uid,
2516 )
2517 .context("In load_key_entry. (deferred key lock)")?;
2518 (key_id_guard, tx)
2519 }
2520 Some(l) => (l, tx),
2521 },
2522 Some(key_id_guard) => (key_id_guard, tx),
2523 };
2524
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002525 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2526 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002527
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002528 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2529
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002530 Ok((key_id_guard, key_entry))
2531 }
2532
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002533 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002534 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002535 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2536 .context("Trying to delete keyentry.")?;
2537 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2538 .context("Trying to delete keymetadata.")?;
2539 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2540 .context("Trying to delete keyparameters.")?;
2541 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2542 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002543 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002544 }
2545
2546 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002547 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002548 pub fn unbind_key(
2549 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002550 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002551 key_type: KeyType,
2552 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002553 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002554 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002555 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2556 let (key_id, access_key_descriptor, access_vector) =
2557 Self::load_access_tuple(tx, key, key_type, caller_uid)
2558 .context("Trying to get access tuple.")?;
2559
2560 // Perform access control. It is vital that we return here if the permission is denied.
2561 // So do not touch that '?' at the end.
2562 check_permission(&access_key_descriptor, access_vector)
2563 .context("While checking permission.")?;
2564
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002565 Self::mark_unreferenced(tx, key_id)
2566 .map(|need_gc| (need_gc, ()))
2567 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002568 })
2569 .context("In unbind_key.")
2570 }
2571
Max Bires8e93d2b2021-01-14 13:17:59 -08002572 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2573 tx.query_row(
2574 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2575 params![key_id],
2576 |row| row.get(0),
2577 )
2578 .context("In get_key_km_uuid.")
2579 }
2580
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002581 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2582 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2583 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
2584 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2585 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2586 .context("In unbind_keys_for_namespace.");
2587 }
2588 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2589 tx.execute(
2590 "DELETE FROM persistent.keymetadata
2591 WHERE keyentryid IN (
2592 SELECT id FROM persistent.keyentry
2593 WHERE domain = ? AND namespace = ?
2594 );",
2595 params![domain.0, namespace],
2596 )
2597 .context("Trying to delete keymetadata.")?;
2598 tx.execute(
2599 "DELETE FROM persistent.keyparameter
2600 WHERE keyentryid IN (
2601 SELECT id FROM persistent.keyentry
2602 WHERE domain = ? AND namespace = ?
2603 );",
2604 params![domain.0, namespace],
2605 )
2606 .context("Trying to delete keyparameters.")?;
2607 tx.execute(
2608 "DELETE FROM persistent.grant
2609 WHERE keyentryid IN (
2610 SELECT id FROM persistent.keyentry
2611 WHERE domain = ? AND namespace = ?
2612 );",
2613 params![domain.0, namespace],
2614 )
2615 .context("Trying to delete grants.")?;
2616 tx.execute(
2617 "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;",
2618 params![domain.0, namespace],
2619 )
2620 .context("Trying to delete keyentry.")?;
2621 Ok(()).need_gc()
2622 })
2623 .context("In unbind_keys_for_namespace")
2624 }
2625
Hasini Gunasingheda895552021-01-27 19:34:37 +00002626 /// Delete the keys created on behalf of the user, denoted by the user id.
2627 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2628 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2629 /// The caller of this function should notify the gc if the returned value is true.
2630 pub fn unbind_keys_for_user(
2631 &mut self,
2632 user_id: u32,
2633 keep_non_super_encrypted_keys: bool,
2634 ) -> Result<()> {
2635 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2636 let mut stmt = tx
2637 .prepare(&format!(
2638 "SELECT id from persistent.keyentry
2639 WHERE (
2640 key_type = ?
2641 AND domain = ?
2642 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2643 AND state = ?
2644 ) OR (
2645 key_type = ?
2646 AND namespace = ?
2647 AND alias = ?
2648 AND state = ?
2649 );",
2650 aid_user_offset = AID_USER_OFFSET
2651 ))
2652 .context(concat!(
2653 "In unbind_keys_for_user. ",
2654 "Failed to prepare the query to find the keys created by apps."
2655 ))?;
2656
2657 let mut rows = stmt
2658 .query(params![
2659 // WHERE client key:
2660 KeyType::Client,
2661 Domain::APP.0 as u32,
2662 user_id,
2663 KeyLifeCycle::Live,
2664 // OR super key:
2665 KeyType::Super,
2666 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002667 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002668 KeyLifeCycle::Live
2669 ])
2670 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2671
2672 let mut key_ids: Vec<i64> = Vec::new();
2673 db_utils::with_rows_extract_all(&mut rows, |row| {
2674 key_ids
2675 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2676 Ok(())
2677 })
2678 .context("In unbind_keys_for_user.")?;
2679
2680 let mut notify_gc = false;
2681 for key_id in key_ids {
2682 if keep_non_super_encrypted_keys {
2683 // Load metadata and filter out non-super-encrypted keys.
2684 if let (_, Some((_, blob_metadata)), _, _) =
2685 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2686 .context("In unbind_keys_for_user: Trying to load blob info.")?
2687 {
2688 if blob_metadata.encrypted_by().is_none() {
2689 continue;
2690 }
2691 }
2692 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002693 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002694 .context("In unbind_keys_for_user.")?
2695 || notify_gc;
2696 }
2697 Ok(()).do_gc(notify_gc)
2698 })
2699 .context("In unbind_keys_for_user.")
2700 }
2701
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002702 fn load_key_components(
2703 tx: &Transaction,
2704 load_bits: KeyEntryLoadBits,
2705 key_id: i64,
2706 ) -> Result<KeyEntry> {
2707 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2708
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002709 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002710 Self::load_blob_components(key_id, load_bits, &tx)
2711 .context("In load_key_components.")?;
2712
Max Bires8e93d2b2021-01-14 13:17:59 -08002713 let parameters = Self::load_key_parameters(key_id, &tx)
2714 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002715
Max Bires8e93d2b2021-01-14 13:17:59 -08002716 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2717 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002718
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002719 Ok(KeyEntry {
2720 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002721 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002722 cert: cert_blob,
2723 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002724 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002725 parameters,
2726 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002727 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002728 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002729 }
2730
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002731 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2732 /// The key descriptors will have the domain, nspace, and alias field set.
2733 /// Domain must be APP or SELINUX, the caller must make sure of that.
2734 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002735 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2736 let mut stmt = tx
2737 .prepare(
2738 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002739 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002740 )
2741 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002742
Janis Danisevskis66784c42021-01-27 08:40:25 -08002743 let mut rows = stmt
2744 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2745 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002746
Janis Danisevskis66784c42021-01-27 08:40:25 -08002747 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2748 db_utils::with_rows_extract_all(&mut rows, |row| {
2749 descriptors.push(KeyDescriptor {
2750 domain,
2751 nspace: namespace,
2752 alias: Some(row.get(0).context("Trying to extract alias.")?),
2753 blob: None,
2754 });
2755 Ok(())
2756 })
2757 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002758 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002759 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002760 }
2761
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002762 /// Adds a grant to the grant table.
2763 /// Like `load_key_entry` this function loads the access tuple before
2764 /// it uses the callback for a permission check. Upon success,
2765 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2766 /// grant table. The new row will have a randomized id, which is used as
2767 /// grant id in the namespace field of the resulting KeyDescriptor.
2768 pub fn grant(
2769 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002770 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002771 caller_uid: u32,
2772 grantee_uid: u32,
2773 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002774 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002775 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002776 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2777 // Load the key_id and complete the access control tuple.
2778 // We ignore the access vector here because grants cannot be granted.
2779 // The access vector returned here expresses the permissions the
2780 // grantee has if key.domain == Domain::GRANT. But this vector
2781 // cannot include the grant permission by design, so there is no way the
2782 // subsequent permission check can pass.
2783 // We could check key.domain == Domain::GRANT and fail early.
2784 // But even if we load the access tuple by grant here, the permission
2785 // check denies the attempt to create a grant by grant descriptor.
2786 let (key_id, access_key_descriptor, _) =
2787 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2788 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002789
Janis Danisevskis66784c42021-01-27 08:40:25 -08002790 // Perform access control. It is vital that we return here if the permission
2791 // was denied. So do not touch that '?' at the end of the line.
2792 // This permission check checks if the caller has the grant permission
2793 // for the given key and in addition to all of the permissions
2794 // expressed in `access_vector`.
2795 check_permission(&access_key_descriptor, &access_vector)
2796 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002797
Janis Danisevskis66784c42021-01-27 08:40:25 -08002798 let grant_id = if let Some(grant_id) = tx
2799 .query_row(
2800 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002801 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002802 params![key_id, grantee_uid],
2803 |row| row.get(0),
2804 )
2805 .optional()
2806 .context("In grant: Failed get optional existing grant id.")?
2807 {
2808 tx.execute(
2809 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002810 SET access_vector = ?
2811 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002812 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002813 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002814 .context("In grant: Failed to update existing grant.")?;
2815 grant_id
2816 } else {
2817 Self::insert_with_retry(|id| {
2818 tx.execute(
2819 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2820 VALUES (?, ?, ?, ?);",
2821 params![id, grantee_uid, key_id, i32::from(access_vector)],
2822 )
2823 })
2824 .context("In grant")?
2825 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002826
Janis Danisevskis66784c42021-01-27 08:40:25 -08002827 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002828 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002829 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002830 }
2831
2832 /// This function checks permissions like `grant` and `load_key_entry`
2833 /// before removing a grant from the grant table.
2834 pub fn ungrant(
2835 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002836 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002837 caller_uid: u32,
2838 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002839 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002840 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002841 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2842 // Load the key_id and complete the access control tuple.
2843 // We ignore the access vector here because grants cannot be granted.
2844 let (key_id, access_key_descriptor, _) =
2845 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2846 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002847
Janis Danisevskis66784c42021-01-27 08:40:25 -08002848 // Perform access control. We must return here if the permission
2849 // was denied. So do not touch the '?' at the end of this line.
2850 check_permission(&access_key_descriptor)
2851 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002852
Janis Danisevskis66784c42021-01-27 08:40:25 -08002853 tx.execute(
2854 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002855 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002856 params![key_id, grantee_uid],
2857 )
2858 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002859
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002860 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002861 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002862 }
2863
Joel Galenson845f74b2020-09-09 14:11:55 -07002864 // Generates a random id and passes it to the given function, which will
2865 // try to insert it into a database. If that insertion fails, retry;
2866 // otherwise return the id.
2867 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2868 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002869 let newid: i64 = match random() {
2870 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2871 i => i,
2872 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002873 match inserter(newid) {
2874 // If the id already existed, try again.
2875 Err(rusqlite::Error::SqliteFailure(
2876 libsqlite3_sys::Error {
2877 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2878 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2879 },
2880 _,
2881 )) => (),
2882 Err(e) => {
2883 return Err(e).context("In insert_with_retry: failed to insert into database.")
2884 }
2885 _ => return Ok(newid),
2886 }
2887 }
2888 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002889
2890 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
2891 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002892 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2893 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002894 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
2895 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
2896 params![
2897 auth_token.challenge,
2898 auth_token.userId,
2899 auth_token.authenticatorId,
2900 auth_token.authenticatorType.0 as i32,
2901 auth_token.timestamp.milliSeconds as i64,
2902 auth_token.mac,
2903 MonotonicRawTime::now(),
2904 ],
2905 )
2906 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002907 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002908 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002909 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002910
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002911 /// Find the newest auth token matching the given predicate.
2912 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002913 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002914 p: F,
2915 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
2916 where
2917 F: Fn(&AuthTokenEntry) -> bool,
2918 {
2919 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2920 let mut stmt = tx
2921 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
2922 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002923
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002924 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002925
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002926 while let Some(row) = rows.next().context("Failed to get next row.")? {
2927 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002928 HardwareAuthToken {
2929 challenge: row.get(1)?,
2930 userId: row.get(2)?,
2931 authenticatorId: row.get(3)?,
2932 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2933 timestamp: Timestamp { milliSeconds: row.get(5)? },
2934 mac: row.get(6)?,
2935 },
2936 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002937 );
2938 if p(&entry) {
2939 return Ok(Some((
2940 entry,
2941 Self::get_last_off_body(tx)
2942 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002943 )))
2944 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002945 }
2946 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002947 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002948 })
2949 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002950 }
2951
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002952 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08002953 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2954 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2955 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002956 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
2957 params!["last_off_body", last_off_body],
2958 )
2959 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002960 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002961 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002962 }
2963
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002964 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08002965 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2966 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2967 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002968 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
2969 params![last_off_body, "last_off_body"],
2970 )
2971 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002972 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002973 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002974 }
2975
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002976 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002977 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002978 tx.query_row(
2979 "SELECT value from perboot.metadata WHERE key = ?;",
2980 params!["last_off_body"],
2981 |row| Ok(row.get(0)?),
2982 )
2983 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002984 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002985}
2986
2987#[cfg(test)]
2988mod tests {
2989
2990 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002991 use crate::key_parameter::{
2992 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2993 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2994 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002995 use crate::key_perm_set;
2996 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00002997 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002998 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002999 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3000 HardwareAuthToken::HardwareAuthToken,
3001 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003002 };
3003 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003004 Timestamp::Timestamp,
3005 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003006 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003007 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003008 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003009 use std::sync::atomic::{AtomicU8, Ordering};
3010 use std::sync::Arc;
3011 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003012 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003013 #[cfg(disabled)]
3014 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003015
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003016 fn new_test_db() -> Result<KeystoreDB> {
3017 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3018
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003019 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003020 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003021 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003022 })?;
3023 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003024 }
3025
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003026 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3027 where
3028 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3029 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003030 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003031
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003032 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003033 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003034
3035 KeystoreDB::new(path, Some(gc))
3036 }
3037
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003038 fn rebind_alias(
3039 db: &mut KeystoreDB,
3040 newid: &KeyIdGuard,
3041 alias: &str,
3042 domain: Domain,
3043 namespace: i64,
3044 ) -> Result<bool> {
3045 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003046 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003047 })
3048 .context("In rebind_alias.")
3049 }
3050
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003051 #[test]
3052 fn datetime() -> Result<()> {
3053 let conn = Connection::open_in_memory()?;
3054 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3055 let now = SystemTime::now();
3056 let duration = Duration::from_secs(1000);
3057 let then = now.checked_sub(duration).unwrap();
3058 let soon = now.checked_add(duration).unwrap();
3059 conn.execute(
3060 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3061 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3062 )?;
3063 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3064 let mut rows = stmt.query(NO_PARAMS)?;
3065 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3066 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3067 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3068 assert!(rows.next()?.is_none());
3069 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3070 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3071 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3072 Ok(())
3073 }
3074
Joel Galenson0891bc12020-07-20 10:37:03 -07003075 // Ensure that we're using the "injected" random function, not the real one.
3076 #[test]
3077 fn test_mocked_random() {
3078 let rand1 = random();
3079 let rand2 = random();
3080 let rand3 = random();
3081 if rand1 == rand2 {
3082 assert_eq!(rand2 + 1, rand3);
3083 } else {
3084 assert_eq!(rand1 + 1, rand2);
3085 assert_eq!(rand2, rand3);
3086 }
3087 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003088
Joel Galenson26f4d012020-07-17 14:57:21 -07003089 // Test that we have the correct tables.
3090 #[test]
3091 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003092 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003093 let tables = db
3094 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003095 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003096 .query_map(params![], |row| row.get(0))?
3097 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003098 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003099 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003100 assert_eq!(tables[1], "blobmetadata");
3101 assert_eq!(tables[2], "grant");
3102 assert_eq!(tables[3], "keyentry");
3103 assert_eq!(tables[4], "keymetadata");
3104 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003105 let tables = db
3106 .conn
3107 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3108 .query_map(params![], |row| row.get(0))?
3109 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003110
3111 assert_eq!(tables.len(), 2);
3112 assert_eq!(tables[0], "authtoken");
3113 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003114 Ok(())
3115 }
3116
3117 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003118 fn test_auth_token_table_invariant() -> Result<()> {
3119 let mut db = new_test_db()?;
3120 let auth_token1 = HardwareAuthToken {
3121 challenge: i64::MAX,
3122 userId: 200,
3123 authenticatorId: 200,
3124 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3125 timestamp: Timestamp { milliSeconds: 500 },
3126 mac: String::from("mac").into_bytes(),
3127 };
3128 db.insert_auth_token(&auth_token1)?;
3129 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3130 assert_eq!(auth_tokens_returned.len(), 1);
3131
3132 // insert another auth token with the same values for the columns in the UNIQUE constraint
3133 // of the auth token table and different value for timestamp
3134 let auth_token2 = HardwareAuthToken {
3135 challenge: i64::MAX,
3136 userId: 200,
3137 authenticatorId: 200,
3138 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3139 timestamp: Timestamp { milliSeconds: 600 },
3140 mac: String::from("mac").into_bytes(),
3141 };
3142
3143 db.insert_auth_token(&auth_token2)?;
3144 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3145 assert_eq!(auth_tokens_returned.len(), 1);
3146
3147 if let Some(auth_token) = auth_tokens_returned.pop() {
3148 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3149 }
3150
3151 // insert another auth token with the different values for the columns in the UNIQUE
3152 // constraint of the auth token table
3153 let auth_token3 = HardwareAuthToken {
3154 challenge: i64::MAX,
3155 userId: 201,
3156 authenticatorId: 200,
3157 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3158 timestamp: Timestamp { milliSeconds: 600 },
3159 mac: String::from("mac").into_bytes(),
3160 };
3161
3162 db.insert_auth_token(&auth_token3)?;
3163 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3164 assert_eq!(auth_tokens_returned.len(), 2);
3165
3166 Ok(())
3167 }
3168
3169 // utility function for test_auth_token_table_invariant()
3170 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3171 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3172
3173 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3174 .query_map(NO_PARAMS, |row| {
3175 Ok(AuthTokenEntry::new(
3176 HardwareAuthToken {
3177 challenge: row.get(1)?,
3178 userId: row.get(2)?,
3179 authenticatorId: row.get(3)?,
3180 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3181 timestamp: Timestamp { milliSeconds: row.get(5)? },
3182 mac: row.get(6)?,
3183 },
3184 row.get(7)?,
3185 ))
3186 })?
3187 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3188 Ok(auth_token_entries)
3189 }
3190
3191 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003192 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003193 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003194 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003195
Janis Danisevskis66784c42021-01-27 08:40:25 -08003196 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003197 let entries = get_keyentry(&db)?;
3198 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003199
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003200 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003201
3202 let entries_new = get_keyentry(&db)?;
3203 assert_eq!(entries, entries_new);
3204 Ok(())
3205 }
3206
3207 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003208 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003209 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3210 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003211 }
3212
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003213 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003214
Janis Danisevskis66784c42021-01-27 08:40:25 -08003215 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3216 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003217
3218 let entries = get_keyentry(&db)?;
3219 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003220 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3221 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003222
3223 // Test that we must pass in a valid Domain.
3224 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003225 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003226 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003227 );
3228 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003229 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003230 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003231 );
3232 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003233 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003234 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003235 );
3236
3237 Ok(())
3238 }
3239
Joel Galenson33c04ad2020-08-03 11:04:38 -07003240 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003241 fn test_add_unsigned_key() -> Result<()> {
3242 let mut db = new_test_db()?;
3243 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3244 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3245 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3246 db.create_attestation_key_entry(
3247 &public_key,
3248 &raw_public_key,
3249 &private_key,
3250 &KEYSTORE_UUID,
3251 )?;
3252 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3253 assert_eq!(keys.len(), 1);
3254 assert_eq!(keys[0], public_key);
3255 Ok(())
3256 }
3257
3258 #[test]
3259 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3260 let mut db = new_test_db()?;
3261 let expiration_date: i64 = 20;
3262 let namespace: i64 = 30;
3263 let base_byte: u8 = 1;
3264 let loaded_values =
3265 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3266 let chain =
3267 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3268 assert_eq!(true, chain.is_some());
3269 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003270 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003271 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3272 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003273 Ok(())
3274 }
3275
3276 #[test]
3277 fn test_get_attestation_pool_status() -> Result<()> {
3278 let mut db = new_test_db()?;
3279 let namespace: i64 = 30;
3280 load_attestation_key_pool(
3281 &mut db, 10, /* expiration */
3282 namespace, 0x01, /* base_byte */
3283 )?;
3284 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3285 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3286 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3287 assert_eq!(status.expiring, 0);
3288 assert_eq!(status.attested, 3);
3289 assert_eq!(status.unassigned, 0);
3290 assert_eq!(status.total, 3);
3291 assert_eq!(
3292 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3293 1
3294 );
3295 assert_eq!(
3296 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3297 2
3298 );
3299 assert_eq!(
3300 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3301 3
3302 );
3303 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3304 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3305 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3306 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003307 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003308 db.create_attestation_key_entry(
3309 &public_key,
3310 &raw_public_key,
3311 &private_key,
3312 &KEYSTORE_UUID,
3313 )?;
3314 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3315 assert_eq!(status.attested, 3);
3316 assert_eq!(status.unassigned, 0);
3317 assert_eq!(status.total, 4);
3318 db.store_signed_attestation_certificate_chain(
3319 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003320 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003321 &cert_chain,
3322 20,
3323 &KEYSTORE_UUID,
3324 )?;
3325 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3326 assert_eq!(status.attested, 4);
3327 assert_eq!(status.unassigned, 1);
3328 assert_eq!(status.total, 4);
3329 Ok(())
3330 }
3331
3332 #[test]
3333 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003334 let temp_dir =
3335 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3336 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003337 let expiration_date: i64 =
3338 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3339 let namespace: i64 = 30;
3340 let namespace_del1: i64 = 45;
3341 let namespace_del2: i64 = 60;
3342 let entry_values = load_attestation_key_pool(
3343 &mut db,
3344 expiration_date,
3345 namespace,
3346 0x01, /* base_byte */
3347 )?;
3348 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3349 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003350
3351 let blob_entry_row_count: u32 = db
3352 .conn
3353 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3354 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003355 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3356 // one key, one certificate chain, and one certificate.
3357 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003358
Max Bires2b2e6562020-09-22 11:22:36 -07003359 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3360
3361 let mut cert_chain =
3362 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003363 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003364 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003365 assert_eq!(entry_values.batch_cert, value.batch_cert);
3366 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003367 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003368
3369 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3370 Domain::APP,
3371 namespace_del1,
3372 &KEYSTORE_UUID,
3373 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003374 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003375 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3376 Domain::APP,
3377 namespace_del2,
3378 &KEYSTORE_UUID,
3379 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003380 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003381
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003382 // Give the garbage collector half a second to catch up.
3383 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003384
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003385 let blob_entry_row_count: u32 = db
3386 .conn
3387 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3388 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003389 // There shound be 3 blob entries left, because we deleted two of the attestation
3390 // key entries with three blobs each.
3391 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003392
Max Bires2b2e6562020-09-22 11:22:36 -07003393 Ok(())
3394 }
3395
3396 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003397 fn test_delete_all_attestation_keys() -> Result<()> {
3398 let mut db = new_test_db()?;
3399 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3400 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3401 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3402 let result = db.delete_all_attestation_keys()?;
3403
3404 // Give the garbage collector half a second to catch up.
3405 std::thread::sleep(Duration::from_millis(500));
3406
3407 // Attestation keys should be deleted, and the regular key should remain.
3408 assert_eq!(result, 2);
3409
3410 Ok(())
3411 }
3412
3413 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003414 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003415 fn extractor(
3416 ke: &KeyEntryRow,
3417 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3418 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003419 }
3420
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003421 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003422 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3423 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003424 let entries = get_keyentry(&db)?;
3425 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003426 assert_eq!(
3427 extractor(&entries[0]),
3428 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3429 );
3430 assert_eq!(
3431 extractor(&entries[1]),
3432 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3433 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003434
3435 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003436 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003437 let entries = get_keyentry(&db)?;
3438 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003439 assert_eq!(
3440 extractor(&entries[0]),
3441 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3442 );
3443 assert_eq!(
3444 extractor(&entries[1]),
3445 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3446 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003447
3448 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003449 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003450 let entries = get_keyentry(&db)?;
3451 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003452 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3453 assert_eq!(
3454 extractor(&entries[1]),
3455 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3456 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003457
3458 // Test that we must pass in a valid Domain.
3459 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003460 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003461 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003462 );
3463 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003464 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003465 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003466 );
3467 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003468 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003469 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003470 );
3471
3472 // Test that we correctly handle setting an alias for something that does not exist.
3473 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003474 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003475 "Expected to update a single entry but instead updated 0",
3476 );
3477 // Test that we correctly abort the transaction in this case.
3478 let entries = get_keyentry(&db)?;
3479 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003480 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3481 assert_eq!(
3482 extractor(&entries[1]),
3483 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3484 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003485
3486 Ok(())
3487 }
3488
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003489 #[test]
3490 fn test_grant_ungrant() -> Result<()> {
3491 const CALLER_UID: u32 = 15;
3492 const GRANTEE_UID: u32 = 12;
3493 const SELINUX_NAMESPACE: i64 = 7;
3494
3495 let mut db = new_test_db()?;
3496 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003497 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3498 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3499 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003500 )?;
3501 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003502 domain: super::Domain::APP,
3503 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003504 alias: Some("key".to_string()),
3505 blob: None,
3506 };
3507 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3508 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3509
3510 // Reset totally predictable random number generator in case we
3511 // are not the first test running on this thread.
3512 reset_random();
3513 let next_random = 0i64;
3514
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003515 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003516 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003517 assert_eq!(*a, PVEC1);
3518 assert_eq!(
3519 *k,
3520 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003521 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003522 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003523 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003524 alias: Some("key".to_string()),
3525 blob: None,
3526 }
3527 );
3528 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003529 })
3530 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003531
3532 assert_eq!(
3533 app_granted_key,
3534 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003535 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003536 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003537 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003538 alias: None,
3539 blob: None,
3540 }
3541 );
3542
3543 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003544 domain: super::Domain::SELINUX,
3545 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003546 alias: Some("yek".to_string()),
3547 blob: None,
3548 };
3549
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003550 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003551 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003552 assert_eq!(*a, PVEC1);
3553 assert_eq!(
3554 *k,
3555 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003556 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003557 // namespace must be the supplied SELinux
3558 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003559 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003560 alias: Some("yek".to_string()),
3561 blob: None,
3562 }
3563 );
3564 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003565 })
3566 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003567
3568 assert_eq!(
3569 selinux_granted_key,
3570 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003571 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003572 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003573 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003574 alias: None,
3575 blob: None,
3576 }
3577 );
3578
3579 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003580 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003581 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003582 assert_eq!(*a, PVEC2);
3583 assert_eq!(
3584 *k,
3585 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003586 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003587 // namespace must be the supplied SELinux
3588 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003589 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003590 alias: Some("yek".to_string()),
3591 blob: None,
3592 }
3593 );
3594 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003595 })
3596 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003597
3598 assert_eq!(
3599 selinux_granted_key,
3600 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003601 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003602 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003603 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003604 alias: None,
3605 blob: None,
3606 }
3607 );
3608
3609 {
3610 // Limiting scope of stmt, because it borrows db.
3611 let mut stmt = db
3612 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003613 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003614 let mut rows =
3615 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3616 Ok((
3617 row.get(0)?,
3618 row.get(1)?,
3619 row.get(2)?,
3620 KeyPermSet::from(row.get::<_, i32>(3)?),
3621 ))
3622 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003623
3624 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003625 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003626 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003627 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003628 assert!(rows.next().is_none());
3629 }
3630
3631 debug_dump_keyentry_table(&mut db)?;
3632 println!("app_key {:?}", app_key);
3633 println!("selinux_key {:?}", selinux_key);
3634
Janis Danisevskis66784c42021-01-27 08:40:25 -08003635 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3636 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003637
3638 Ok(())
3639 }
3640
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003641 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003642 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3643 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3644
3645 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003646 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003647 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003648 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003649 let mut blob_metadata = BlobMetaData::new();
3650 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3651 db.set_blob(
3652 &key_id,
3653 SubComponentType::KEY_BLOB,
3654 Some(TEST_KEY_BLOB),
3655 Some(&blob_metadata),
3656 )?;
3657 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3658 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003659 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003660
3661 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003662 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003663 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003664 )?;
3665 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003666 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3667 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003668 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003669 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003670 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003671 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003672 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003673 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003674 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003675
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003676 drop(rows);
3677 drop(stmt);
3678
3679 assert_eq!(
3680 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3681 BlobMetaData::load_from_db(id, tx).no_gc()
3682 })
3683 .expect("Should find blob metadata."),
3684 blob_metadata
3685 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003686 Ok(())
3687 }
3688
3689 static TEST_ALIAS: &str = "my super duper key";
3690
3691 #[test]
3692 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3693 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003694 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003695 .context("test_insert_and_load_full_keyentry_domain_app")?
3696 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003697 let (_key_guard, key_entry) = db
3698 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003699 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003700 domain: Domain::APP,
3701 nspace: 0,
3702 alias: Some(TEST_ALIAS.to_string()),
3703 blob: None,
3704 },
3705 KeyType::Client,
3706 KeyEntryLoadBits::BOTH,
3707 1,
3708 |_k, _av| Ok(()),
3709 )
3710 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003711 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003712
3713 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003714 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003715 domain: Domain::APP,
3716 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003717 alias: Some(TEST_ALIAS.to_string()),
3718 blob: None,
3719 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003720 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003721 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003722 |_, _| Ok(()),
3723 )
3724 .unwrap();
3725
3726 assert_eq!(
3727 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3728 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003729 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003730 domain: Domain::APP,
3731 nspace: 0,
3732 alias: Some(TEST_ALIAS.to_string()),
3733 blob: None,
3734 },
3735 KeyType::Client,
3736 KeyEntryLoadBits::NONE,
3737 1,
3738 |_k, _av| Ok(()),
3739 )
3740 .unwrap_err()
3741 .root_cause()
3742 .downcast_ref::<KsError>()
3743 );
3744
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003745 Ok(())
3746 }
3747
3748 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003749 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3750 let mut db = new_test_db()?;
3751
3752 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003753 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003754 domain: Domain::APP,
3755 nspace: 1,
3756 alias: Some(TEST_ALIAS.to_string()),
3757 blob: None,
3758 },
3759 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003760 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003761 )
3762 .expect("Trying to insert cert.");
3763
3764 let (_key_guard, mut key_entry) = db
3765 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003766 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003767 domain: Domain::APP,
3768 nspace: 1,
3769 alias: Some(TEST_ALIAS.to_string()),
3770 blob: None,
3771 },
3772 KeyType::Client,
3773 KeyEntryLoadBits::PUBLIC,
3774 1,
3775 |_k, _av| Ok(()),
3776 )
3777 .expect("Trying to read certificate entry.");
3778
3779 assert!(key_entry.pure_cert());
3780 assert!(key_entry.cert().is_none());
3781 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3782
3783 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003784 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003785 domain: Domain::APP,
3786 nspace: 1,
3787 alias: Some(TEST_ALIAS.to_string()),
3788 blob: None,
3789 },
3790 KeyType::Client,
3791 1,
3792 |_, _| Ok(()),
3793 )
3794 .unwrap();
3795
3796 assert_eq!(
3797 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3798 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003799 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003800 domain: Domain::APP,
3801 nspace: 1,
3802 alias: Some(TEST_ALIAS.to_string()),
3803 blob: None,
3804 },
3805 KeyType::Client,
3806 KeyEntryLoadBits::NONE,
3807 1,
3808 |_k, _av| Ok(()),
3809 )
3810 .unwrap_err()
3811 .root_cause()
3812 .downcast_ref::<KsError>()
3813 );
3814
3815 Ok(())
3816 }
3817
3818 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003819 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3820 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003821 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003822 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3823 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003824 let (_key_guard, key_entry) = db
3825 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003826 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003827 domain: Domain::SELINUX,
3828 nspace: 1,
3829 alias: Some(TEST_ALIAS.to_string()),
3830 blob: None,
3831 },
3832 KeyType::Client,
3833 KeyEntryLoadBits::BOTH,
3834 1,
3835 |_k, _av| Ok(()),
3836 )
3837 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003838 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003839
3840 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003841 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003842 domain: Domain::SELINUX,
3843 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003844 alias: Some(TEST_ALIAS.to_string()),
3845 blob: None,
3846 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003847 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003848 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003849 |_, _| Ok(()),
3850 )
3851 .unwrap();
3852
3853 assert_eq!(
3854 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3855 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003856 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003857 domain: Domain::SELINUX,
3858 nspace: 1,
3859 alias: Some(TEST_ALIAS.to_string()),
3860 blob: None,
3861 },
3862 KeyType::Client,
3863 KeyEntryLoadBits::NONE,
3864 1,
3865 |_k, _av| Ok(()),
3866 )
3867 .unwrap_err()
3868 .root_cause()
3869 .downcast_ref::<KsError>()
3870 );
3871
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003872 Ok(())
3873 }
3874
3875 #[test]
3876 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3877 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003878 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003879 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3880 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003881 let (_, key_entry) = db
3882 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003883 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003884 KeyType::Client,
3885 KeyEntryLoadBits::BOTH,
3886 1,
3887 |_k, _av| Ok(()),
3888 )
3889 .unwrap();
3890
Qi Wub9433b52020-12-01 14:52:46 +08003891 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003892
3893 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003894 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003895 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003896 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003897 |_, _| Ok(()),
3898 )
3899 .unwrap();
3900
3901 assert_eq!(
3902 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3903 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003904 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003905 KeyType::Client,
3906 KeyEntryLoadBits::NONE,
3907 1,
3908 |_k, _av| Ok(()),
3909 )
3910 .unwrap_err()
3911 .root_cause()
3912 .downcast_ref::<KsError>()
3913 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003914
3915 Ok(())
3916 }
3917
3918 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003919 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3920 let mut db = new_test_db()?;
3921 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3922 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3923 .0;
3924 // Update the usage count of the limited use key.
3925 db.check_and_update_key_usage_count(key_id)?;
3926
3927 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003928 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003929 KeyType::Client,
3930 KeyEntryLoadBits::BOTH,
3931 1,
3932 |_k, _av| Ok(()),
3933 )?;
3934
3935 // The usage count is decremented now.
3936 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3937
3938 Ok(())
3939 }
3940
3941 #[test]
3942 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3943 let mut db = new_test_db()?;
3944 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3945 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3946 .0;
3947 // Update the usage count of the limited use key.
3948 db.check_and_update_key_usage_count(key_id).expect(concat!(
3949 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3950 "This should succeed."
3951 ));
3952
3953 // Try to update the exhausted limited use key.
3954 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3955 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3956 "This should fail."
3957 ));
3958 assert_eq!(
3959 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3960 e.root_cause().downcast_ref::<KsError>().unwrap()
3961 );
3962
3963 Ok(())
3964 }
3965
3966 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003967 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3968 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003969 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003970 .context("test_insert_and_load_full_keyentry_from_grant")?
3971 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003972
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003973 let granted_key = db
3974 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003975 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003976 domain: Domain::APP,
3977 nspace: 0,
3978 alias: Some(TEST_ALIAS.to_string()),
3979 blob: None,
3980 },
3981 1,
3982 2,
3983 key_perm_set![KeyPerm::use_()],
3984 |_k, _av| Ok(()),
3985 )
3986 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003987
3988 debug_dump_grant_table(&mut db)?;
3989
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003990 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003991 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3992 assert_eq!(Domain::GRANT, k.domain);
3993 assert!(av.unwrap().includes(KeyPerm::use_()));
3994 Ok(())
3995 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003996 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003997
Qi Wub9433b52020-12-01 14:52:46 +08003998 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003999
Janis Danisevskis66784c42021-01-27 08:40:25 -08004000 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004001
4002 assert_eq!(
4003 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4004 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004005 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004006 KeyType::Client,
4007 KeyEntryLoadBits::NONE,
4008 2,
4009 |_k, _av| Ok(()),
4010 )
4011 .unwrap_err()
4012 .root_cause()
4013 .downcast_ref::<KsError>()
4014 );
4015
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004016 Ok(())
4017 }
4018
Janis Danisevskis45760022021-01-19 16:34:10 -08004019 // This test attempts to load a key by key id while the caller is not the owner
4020 // but a grant exists for the given key and the caller.
4021 #[test]
4022 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4023 let mut db = new_test_db()?;
4024 const OWNER_UID: u32 = 1u32;
4025 const GRANTEE_UID: u32 = 2u32;
4026 const SOMEONE_ELSE_UID: u32 = 3u32;
4027 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4028 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4029 .0;
4030
4031 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004032 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004033 domain: Domain::APP,
4034 nspace: 0,
4035 alias: Some(TEST_ALIAS.to_string()),
4036 blob: None,
4037 },
4038 OWNER_UID,
4039 GRANTEE_UID,
4040 key_perm_set![KeyPerm::use_()],
4041 |_k, _av| Ok(()),
4042 )
4043 .unwrap();
4044
4045 debug_dump_grant_table(&mut db)?;
4046
4047 let id_descriptor =
4048 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4049
4050 let (_, key_entry) = db
4051 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004052 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004053 KeyType::Client,
4054 KeyEntryLoadBits::BOTH,
4055 GRANTEE_UID,
4056 |k, av| {
4057 assert_eq!(Domain::APP, k.domain);
4058 assert_eq!(OWNER_UID as i64, k.nspace);
4059 assert!(av.unwrap().includes(KeyPerm::use_()));
4060 Ok(())
4061 },
4062 )
4063 .unwrap();
4064
4065 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4066
4067 let (_, key_entry) = db
4068 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004069 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004070 KeyType::Client,
4071 KeyEntryLoadBits::BOTH,
4072 SOMEONE_ELSE_UID,
4073 |k, av| {
4074 assert_eq!(Domain::APP, k.domain);
4075 assert_eq!(OWNER_UID as i64, k.nspace);
4076 assert!(av.is_none());
4077 Ok(())
4078 },
4079 )
4080 .unwrap();
4081
4082 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4083
Janis Danisevskis66784c42021-01-27 08:40:25 -08004084 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004085
4086 assert_eq!(
4087 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4088 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004089 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004090 KeyType::Client,
4091 KeyEntryLoadBits::NONE,
4092 GRANTEE_UID,
4093 |_k, _av| Ok(()),
4094 )
4095 .unwrap_err()
4096 .root_cause()
4097 .downcast_ref::<KsError>()
4098 );
4099
4100 Ok(())
4101 }
4102
Janis Danisevskisaec14592020-11-12 09:41:49 -08004103 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4104
Janis Danisevskisaec14592020-11-12 09:41:49 -08004105 #[test]
4106 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4107 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004108 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4109 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004110 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004111 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004112 .context("test_insert_and_load_full_keyentry_domain_app")?
4113 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004114 let (_key_guard, key_entry) = db
4115 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004116 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004117 domain: Domain::APP,
4118 nspace: 0,
4119 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4120 blob: None,
4121 },
4122 KeyType::Client,
4123 KeyEntryLoadBits::BOTH,
4124 33,
4125 |_k, _av| Ok(()),
4126 )
4127 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004128 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004129 let state = Arc::new(AtomicU8::new(1));
4130 let state2 = state.clone();
4131
4132 // Spawning a second thread that attempts to acquire the key id lock
4133 // for the same key as the primary thread. The primary thread then
4134 // waits, thereby forcing the secondary thread into the second stage
4135 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4136 // The test succeeds if the secondary thread observes the transition
4137 // of `state` from 1 to 2, despite having a whole second to overtake
4138 // the primary thread.
4139 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004140 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004141 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004142 assert!(db
4143 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004144 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004145 domain: Domain::APP,
4146 nspace: 0,
4147 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4148 blob: None,
4149 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004150 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004151 KeyEntryLoadBits::BOTH,
4152 33,
4153 |_k, _av| Ok(()),
4154 )
4155 .is_ok());
4156 // We should only see a 2 here because we can only return
4157 // from load_key_entry when the `_key_guard` expires,
4158 // which happens at the end of the scope.
4159 assert_eq!(2, state2.load(Ordering::Relaxed));
4160 });
4161
4162 thread::sleep(std::time::Duration::from_millis(1000));
4163
4164 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4165
4166 // Return the handle from this scope so we can join with the
4167 // secondary thread after the key id lock has expired.
4168 handle
4169 // This is where the `_key_guard` goes out of scope,
4170 // which is the reason for concurrent load_key_entry on the same key
4171 // to unblock.
4172 };
4173 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4174 // main test thread. We will not see failing asserts in secondary threads otherwise.
4175 handle.join().unwrap();
4176 Ok(())
4177 }
4178
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004179 #[test]
Janis Danisevskis66784c42021-01-27 08:40:25 -08004180 fn teset_database_busy_error_code() {
4181 let temp_dir =
4182 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4183
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004184 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4185 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004186
4187 let _tx1 = db1
4188 .conn
4189 .transaction_with_behavior(TransactionBehavior::Immediate)
4190 .expect("Failed to create first transaction.");
4191
4192 let error = db2
4193 .conn
4194 .transaction_with_behavior(TransactionBehavior::Immediate)
4195 .context("Transaction begin failed.")
4196 .expect_err("This should fail.");
4197 let root_cause = error.root_cause();
4198 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4199 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4200 {
4201 return;
4202 }
4203 panic!(
4204 "Unexpected error {:?} \n{:?} \n{:?}",
4205 error,
4206 root_cause,
4207 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4208 )
4209 }
4210
4211 #[cfg(disabled)]
4212 #[test]
4213 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4214 let temp_dir = Arc::new(
4215 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4216 .expect("Failed to create temp dir."),
4217 );
4218
4219 let test_begin = Instant::now();
4220
4221 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4222 const KEY_COUNT: u32 = 500u32;
4223 const OPEN_DB_COUNT: u32 = 50u32;
4224
4225 let mut actual_key_count = KEY_COUNT;
4226 // First insert KEY_COUNT keys.
4227 for count in 0..KEY_COUNT {
4228 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4229 actual_key_count = count;
4230 break;
4231 }
4232 let alias = format!("test_alias_{}", count);
4233 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4234 .expect("Failed to make key entry.");
4235 }
4236
4237 // Insert more keys from a different thread and into a different namespace.
4238 let temp_dir1 = temp_dir.clone();
4239 let handle1 = thread::spawn(move || {
4240 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4241
4242 for count in 0..actual_key_count {
4243 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4244 return;
4245 }
4246 let alias = format!("test_alias_{}", count);
4247 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4248 .expect("Failed to make key entry.");
4249 }
4250
4251 // then unbind them again.
4252 for count in 0..actual_key_count {
4253 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4254 return;
4255 }
4256 let key = KeyDescriptor {
4257 domain: Domain::APP,
4258 nspace: -1,
4259 alias: Some(format!("test_alias_{}", count)),
4260 blob: None,
4261 };
4262 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4263 }
4264 });
4265
4266 // And start unbinding the first set of keys.
4267 let temp_dir2 = temp_dir.clone();
4268 let handle2 = thread::spawn(move || {
4269 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4270
4271 for count in 0..actual_key_count {
4272 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4273 return;
4274 }
4275 let key = KeyDescriptor {
4276 domain: Domain::APP,
4277 nspace: -1,
4278 alias: Some(format!("test_alias_{}", count)),
4279 blob: None,
4280 };
4281 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4282 }
4283 });
4284
4285 let stop_deleting = Arc::new(AtomicU8::new(0));
4286 let stop_deleting2 = stop_deleting.clone();
4287
4288 // And delete anything that is unreferenced keys.
4289 let temp_dir3 = temp_dir.clone();
4290 let handle3 = thread::spawn(move || {
4291 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4292
4293 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4294 while let Some((key_guard, _key)) =
4295 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4296 {
4297 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4298 return;
4299 }
4300 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4301 }
4302 std::thread::sleep(std::time::Duration::from_millis(100));
4303 }
4304 });
4305
4306 // While a lot of inserting and deleting is going on we have to open database connections
4307 // successfully and use them.
4308 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4309 // out of scope.
4310 #[allow(clippy::redundant_clone)]
4311 let temp_dir4 = temp_dir.clone();
4312 let handle4 = thread::spawn(move || {
4313 for count in 0..OPEN_DB_COUNT {
4314 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4315 return;
4316 }
4317 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4318
4319 let alias = format!("test_alias_{}", count);
4320 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4321 .expect("Failed to make key entry.");
4322 let key = KeyDescriptor {
4323 domain: Domain::APP,
4324 nspace: -1,
4325 alias: Some(alias),
4326 blob: None,
4327 };
4328 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4329 }
4330 });
4331
4332 handle1.join().expect("Thread 1 panicked.");
4333 handle2.join().expect("Thread 2 panicked.");
4334 handle4.join().expect("Thread 4 panicked.");
4335
4336 stop_deleting.store(1, Ordering::Relaxed);
4337 handle3.join().expect("Thread 3 panicked.");
4338
4339 Ok(())
4340 }
4341
4342 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004343 fn list() -> Result<()> {
4344 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004345 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004346 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4347 (Domain::APP, 1, "test1"),
4348 (Domain::APP, 1, "test2"),
4349 (Domain::APP, 1, "test3"),
4350 (Domain::APP, 1, "test4"),
4351 (Domain::APP, 1, "test5"),
4352 (Domain::APP, 1, "test6"),
4353 (Domain::APP, 1, "test7"),
4354 (Domain::APP, 2, "test1"),
4355 (Domain::APP, 2, "test2"),
4356 (Domain::APP, 2, "test3"),
4357 (Domain::APP, 2, "test4"),
4358 (Domain::APP, 2, "test5"),
4359 (Domain::APP, 2, "test6"),
4360 (Domain::APP, 2, "test8"),
4361 (Domain::SELINUX, 100, "test1"),
4362 (Domain::SELINUX, 100, "test2"),
4363 (Domain::SELINUX, 100, "test3"),
4364 (Domain::SELINUX, 100, "test4"),
4365 (Domain::SELINUX, 100, "test5"),
4366 (Domain::SELINUX, 100, "test6"),
4367 (Domain::SELINUX, 100, "test9"),
4368 ];
4369
4370 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4371 .iter()
4372 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004373 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4374 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004375 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4376 });
4377 (entry.id(), *ns)
4378 })
4379 .collect();
4380
4381 for (domain, namespace) in
4382 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4383 {
4384 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4385 .iter()
4386 .filter_map(|(domain, ns, alias)| match ns {
4387 ns if *ns == *namespace => Some(KeyDescriptor {
4388 domain: *domain,
4389 nspace: *ns,
4390 alias: Some(alias.to_string()),
4391 blob: None,
4392 }),
4393 _ => None,
4394 })
4395 .collect();
4396 list_o_descriptors.sort();
4397 let mut list_result = db.list(*domain, *namespace)?;
4398 list_result.sort();
4399 assert_eq!(list_o_descriptors, list_result);
4400
4401 let mut list_o_ids: Vec<i64> = list_o_descriptors
4402 .into_iter()
4403 .map(|d| {
4404 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004405 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004406 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004407 KeyType::Client,
4408 KeyEntryLoadBits::NONE,
4409 *namespace as u32,
4410 |_, _| Ok(()),
4411 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004412 .unwrap();
4413 entry.id()
4414 })
4415 .collect();
4416 list_o_ids.sort_unstable();
4417 let mut loaded_entries: Vec<i64> = list_o_keys
4418 .iter()
4419 .filter_map(|(id, ns)| match ns {
4420 ns if *ns == *namespace => Some(*id),
4421 _ => None,
4422 })
4423 .collect();
4424 loaded_entries.sort_unstable();
4425 assert_eq!(list_o_ids, loaded_entries);
4426 }
4427 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4428
4429 Ok(())
4430 }
4431
Joel Galenson0891bc12020-07-20 10:37:03 -07004432 // Helpers
4433
4434 // Checks that the given result is an error containing the given string.
4435 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4436 let error_str = format!(
4437 "{:#?}",
4438 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4439 );
4440 assert!(
4441 error_str.contains(target),
4442 "The string \"{}\" should contain \"{}\"",
4443 error_str,
4444 target
4445 );
4446 }
4447
Joel Galenson2aab4432020-07-22 15:27:57 -07004448 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004449 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004450 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004451 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004452 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004453 namespace: Option<i64>,
4454 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004455 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004456 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004457 }
4458
4459 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4460 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004461 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004462 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004463 Ok(KeyEntryRow {
4464 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004465 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004466 domain: match row.get(2)? {
4467 Some(i) => Some(Domain(i)),
4468 None => None,
4469 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004470 namespace: row.get(3)?,
4471 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004472 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004473 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004474 })
4475 })?
4476 .map(|r| r.context("Could not read keyentry row."))
4477 .collect::<Result<Vec<_>>>()
4478 }
4479
Max Biresb2e1d032021-02-08 21:35:05 -08004480 struct RemoteProvValues {
4481 cert_chain: Vec<u8>,
4482 priv_key: Vec<u8>,
4483 batch_cert: Vec<u8>,
4484 }
4485
Max Bires2b2e6562020-09-22 11:22:36 -07004486 fn load_attestation_key_pool(
4487 db: &mut KeystoreDB,
4488 expiration_date: i64,
4489 namespace: i64,
4490 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004491 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004492 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4493 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4494 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4495 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004496 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004497 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4498 db.store_signed_attestation_certificate_chain(
4499 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004500 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004501 &cert_chain,
4502 expiration_date,
4503 &KEYSTORE_UUID,
4504 )?;
4505 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004506 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004507 }
4508
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004509 // Note: The parameters and SecurityLevel associations are nonsensical. This
4510 // collection is only used to check if the parameters are preserved as expected by the
4511 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004512 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4513 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004514 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4515 KeyParameter::new(
4516 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4517 SecurityLevel::TRUSTED_ENVIRONMENT,
4518 ),
4519 KeyParameter::new(
4520 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4521 SecurityLevel::TRUSTED_ENVIRONMENT,
4522 ),
4523 KeyParameter::new(
4524 KeyParameterValue::Algorithm(Algorithm::RSA),
4525 SecurityLevel::TRUSTED_ENVIRONMENT,
4526 ),
4527 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4528 KeyParameter::new(
4529 KeyParameterValue::BlockMode(BlockMode::ECB),
4530 SecurityLevel::TRUSTED_ENVIRONMENT,
4531 ),
4532 KeyParameter::new(
4533 KeyParameterValue::BlockMode(BlockMode::GCM),
4534 SecurityLevel::TRUSTED_ENVIRONMENT,
4535 ),
4536 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4537 KeyParameter::new(
4538 KeyParameterValue::Digest(Digest::MD5),
4539 SecurityLevel::TRUSTED_ENVIRONMENT,
4540 ),
4541 KeyParameter::new(
4542 KeyParameterValue::Digest(Digest::SHA_2_224),
4543 SecurityLevel::TRUSTED_ENVIRONMENT,
4544 ),
4545 KeyParameter::new(
4546 KeyParameterValue::Digest(Digest::SHA_2_256),
4547 SecurityLevel::STRONGBOX,
4548 ),
4549 KeyParameter::new(
4550 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4551 SecurityLevel::TRUSTED_ENVIRONMENT,
4552 ),
4553 KeyParameter::new(
4554 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4555 SecurityLevel::TRUSTED_ENVIRONMENT,
4556 ),
4557 KeyParameter::new(
4558 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4559 SecurityLevel::STRONGBOX,
4560 ),
4561 KeyParameter::new(
4562 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4563 SecurityLevel::TRUSTED_ENVIRONMENT,
4564 ),
4565 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4566 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4567 KeyParameter::new(
4568 KeyParameterValue::EcCurve(EcCurve::P_224),
4569 SecurityLevel::TRUSTED_ENVIRONMENT,
4570 ),
4571 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4572 KeyParameter::new(
4573 KeyParameterValue::EcCurve(EcCurve::P_384),
4574 SecurityLevel::TRUSTED_ENVIRONMENT,
4575 ),
4576 KeyParameter::new(
4577 KeyParameterValue::EcCurve(EcCurve::P_521),
4578 SecurityLevel::TRUSTED_ENVIRONMENT,
4579 ),
4580 KeyParameter::new(
4581 KeyParameterValue::RSAPublicExponent(3),
4582 SecurityLevel::TRUSTED_ENVIRONMENT,
4583 ),
4584 KeyParameter::new(
4585 KeyParameterValue::IncludeUniqueID,
4586 SecurityLevel::TRUSTED_ENVIRONMENT,
4587 ),
4588 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4589 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4590 KeyParameter::new(
4591 KeyParameterValue::ActiveDateTime(1234567890),
4592 SecurityLevel::STRONGBOX,
4593 ),
4594 KeyParameter::new(
4595 KeyParameterValue::OriginationExpireDateTime(1234567890),
4596 SecurityLevel::TRUSTED_ENVIRONMENT,
4597 ),
4598 KeyParameter::new(
4599 KeyParameterValue::UsageExpireDateTime(1234567890),
4600 SecurityLevel::TRUSTED_ENVIRONMENT,
4601 ),
4602 KeyParameter::new(
4603 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4604 SecurityLevel::TRUSTED_ENVIRONMENT,
4605 ),
4606 KeyParameter::new(
4607 KeyParameterValue::MaxUsesPerBoot(1234567890),
4608 SecurityLevel::TRUSTED_ENVIRONMENT,
4609 ),
4610 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4611 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4612 KeyParameter::new(
4613 KeyParameterValue::NoAuthRequired,
4614 SecurityLevel::TRUSTED_ENVIRONMENT,
4615 ),
4616 KeyParameter::new(
4617 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4618 SecurityLevel::TRUSTED_ENVIRONMENT,
4619 ),
4620 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4621 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4622 KeyParameter::new(
4623 KeyParameterValue::TrustedUserPresenceRequired,
4624 SecurityLevel::TRUSTED_ENVIRONMENT,
4625 ),
4626 KeyParameter::new(
4627 KeyParameterValue::TrustedConfirmationRequired,
4628 SecurityLevel::TRUSTED_ENVIRONMENT,
4629 ),
4630 KeyParameter::new(
4631 KeyParameterValue::UnlockedDeviceRequired,
4632 SecurityLevel::TRUSTED_ENVIRONMENT,
4633 ),
4634 KeyParameter::new(
4635 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4636 SecurityLevel::SOFTWARE,
4637 ),
4638 KeyParameter::new(
4639 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4640 SecurityLevel::SOFTWARE,
4641 ),
4642 KeyParameter::new(
4643 KeyParameterValue::CreationDateTime(12345677890),
4644 SecurityLevel::SOFTWARE,
4645 ),
4646 KeyParameter::new(
4647 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4648 SecurityLevel::TRUSTED_ENVIRONMENT,
4649 ),
4650 KeyParameter::new(
4651 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4652 SecurityLevel::TRUSTED_ENVIRONMENT,
4653 ),
4654 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4655 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4656 KeyParameter::new(
4657 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4658 SecurityLevel::SOFTWARE,
4659 ),
4660 KeyParameter::new(
4661 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4662 SecurityLevel::TRUSTED_ENVIRONMENT,
4663 ),
4664 KeyParameter::new(
4665 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4666 SecurityLevel::TRUSTED_ENVIRONMENT,
4667 ),
4668 KeyParameter::new(
4669 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4670 SecurityLevel::TRUSTED_ENVIRONMENT,
4671 ),
4672 KeyParameter::new(
4673 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4674 SecurityLevel::TRUSTED_ENVIRONMENT,
4675 ),
4676 KeyParameter::new(
4677 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4678 SecurityLevel::TRUSTED_ENVIRONMENT,
4679 ),
4680 KeyParameter::new(
4681 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4682 SecurityLevel::TRUSTED_ENVIRONMENT,
4683 ),
4684 KeyParameter::new(
4685 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4686 SecurityLevel::TRUSTED_ENVIRONMENT,
4687 ),
4688 KeyParameter::new(
4689 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4690 SecurityLevel::TRUSTED_ENVIRONMENT,
4691 ),
4692 KeyParameter::new(
4693 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4694 SecurityLevel::TRUSTED_ENVIRONMENT,
4695 ),
4696 KeyParameter::new(
4697 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4698 SecurityLevel::TRUSTED_ENVIRONMENT,
4699 ),
4700 KeyParameter::new(
4701 KeyParameterValue::VendorPatchLevel(3),
4702 SecurityLevel::TRUSTED_ENVIRONMENT,
4703 ),
4704 KeyParameter::new(
4705 KeyParameterValue::BootPatchLevel(4),
4706 SecurityLevel::TRUSTED_ENVIRONMENT,
4707 ),
4708 KeyParameter::new(
4709 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4710 SecurityLevel::TRUSTED_ENVIRONMENT,
4711 ),
4712 KeyParameter::new(
4713 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4714 SecurityLevel::TRUSTED_ENVIRONMENT,
4715 ),
4716 KeyParameter::new(
4717 KeyParameterValue::MacLength(256),
4718 SecurityLevel::TRUSTED_ENVIRONMENT,
4719 ),
4720 KeyParameter::new(
4721 KeyParameterValue::ResetSinceIdRotation,
4722 SecurityLevel::TRUSTED_ENVIRONMENT,
4723 ),
4724 KeyParameter::new(
4725 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4726 SecurityLevel::TRUSTED_ENVIRONMENT,
4727 ),
Qi Wub9433b52020-12-01 14:52:46 +08004728 ];
4729 if let Some(value) = max_usage_count {
4730 params.push(KeyParameter::new(
4731 KeyParameterValue::UsageCountLimit(value),
4732 SecurityLevel::SOFTWARE,
4733 ));
4734 }
4735 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004736 }
4737
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004738 fn make_test_key_entry(
4739 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004740 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004741 namespace: i64,
4742 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004743 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004744 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004745 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004746 let mut blob_metadata = BlobMetaData::new();
4747 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4748 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4749 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4750 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4751 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4752
4753 db.set_blob(
4754 &key_id,
4755 SubComponentType::KEY_BLOB,
4756 Some(TEST_KEY_BLOB),
4757 Some(&blob_metadata),
4758 )?;
4759 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4760 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004761
4762 let params = make_test_params(max_usage_count);
4763 db.insert_keyparameter(&key_id, &params)?;
4764
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004765 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004766 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004767 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004768 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004769 Ok(key_id)
4770 }
4771
Qi Wub9433b52020-12-01 14:52:46 +08004772 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4773 let params = make_test_params(max_usage_count);
4774
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004775 let mut blob_metadata = BlobMetaData::new();
4776 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4777 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4778 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4779 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4780 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4781
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004782 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004783 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004784
4785 KeyEntry {
4786 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004787 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004788 cert: Some(TEST_CERT_BLOB.to_vec()),
4789 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004790 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004791 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004792 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004793 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004794 }
4795 }
4796
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004797 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004798 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004799 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004800 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004801 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004802 NO_PARAMS,
4803 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004804 Ok((
4805 row.get(0)?,
4806 row.get(1)?,
4807 row.get(2)?,
4808 row.get(3)?,
4809 row.get(4)?,
4810 row.get(5)?,
4811 row.get(6)?,
4812 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004813 },
4814 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004815
4816 println!("Key entry table rows:");
4817 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004818 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004819 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004820 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4821 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004822 );
4823 }
4824 Ok(())
4825 }
4826
4827 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004828 let mut stmt = db
4829 .conn
4830 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004831 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
4832 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4833 })?;
4834
4835 println!("Grant table rows:");
4836 for r in rows {
4837 let (id, gt, ki, av) = r.unwrap();
4838 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4839 }
4840 Ok(())
4841 }
4842
Joel Galenson0891bc12020-07-20 10:37:03 -07004843 // Use a custom random number generator that repeats each number once.
4844 // This allows us to test repeated elements.
4845
4846 thread_local! {
4847 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4848 }
4849
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004850 fn reset_random() {
4851 RANDOM_COUNTER.with(|counter| {
4852 *counter.borrow_mut() = 0;
4853 })
4854 }
4855
Joel Galenson0891bc12020-07-20 10:37:03 -07004856 pub fn random() -> i64 {
4857 RANDOM_COUNTER.with(|counter| {
4858 let result = *counter.borrow() / 2;
4859 *counter.borrow_mut() += 1;
4860 result
4861 })
4862 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004863
4864 #[test]
4865 fn test_last_off_body() -> Result<()> {
4866 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08004867 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004868 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4869 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
4870 tx.commit()?;
4871 let one_second = Duration::from_secs(1);
4872 thread::sleep(one_second);
4873 db.update_last_off_body(MonotonicRawTime::now())?;
4874 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4875 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
4876 tx2.commit()?;
4877 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
4878 Ok(())
4879 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00004880
4881 #[test]
4882 fn test_unbind_keys_for_user() -> Result<()> {
4883 let mut db = new_test_db()?;
4884 db.unbind_keys_for_user(1, false)?;
4885
4886 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4887 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4888 db.unbind_keys_for_user(2, false)?;
4889
4890 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
4891 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
4892
4893 db.unbind_keys_for_user(1, true)?;
4894 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
4895
4896 Ok(())
4897 }
4898
4899 #[test]
4900 fn test_store_super_key() -> Result<()> {
4901 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07004902 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00004903 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07004904 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00004905 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07004906 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004907
4908 let (encrypted_super_key, metadata) =
4909 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07004910 db.store_super_key(
4911 1,
4912 &USER_SUPER_KEY,
4913 &encrypted_super_key,
4914 &metadata,
4915 &KeyMetaData::new(),
4916 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004917
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00004918 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07004919 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00004920
Paul Crowley7a658392021-03-18 17:08:20 -07004921 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07004922 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
4923 USER_SUPER_KEY.algorithm,
4924 key_entry,
4925 &pw,
4926 None,
4927 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004928
Paul Crowley7a658392021-03-18 17:08:20 -07004929 let decrypted_secret_bytes =
4930 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
4931 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00004932 Ok(())
4933 }
Joel Galenson26f4d012020-07-17 14:57:21 -07004934}