blob: ce760eb696c048781488ada961ef2aad635938d2 [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
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002034 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2035 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2036 pub fn migrate_key_namespace(
2037 &mut self,
2038 key_id_guard: KeyIdGuard,
2039 destination: &KeyDescriptor,
2040 caller_uid: u32,
2041 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2042 ) -> Result<()> {
2043 let destination = match destination.domain {
2044 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2045 Domain::SELINUX => (*destination).clone(),
2046 domain => {
2047 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2048 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2049 }
2050 };
2051
2052 // Security critical: Must return immediately on failure. Do not remove the '?';
2053 check_permission(&destination)
2054 .context("In migrate_key_namespace: Trying to check permission.")?;
2055
2056 let alias = destination
2057 .alias
2058 .as_ref()
2059 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2060 .context("In migrate_key_namespace: Alias must be specified.")?;
2061
2062 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2063 // Query the destination location. If there is a key, the migration request fails.
2064 if tx
2065 .query_row(
2066 "SELECT id FROM persistent.keyentry
2067 WHERE alias = ? AND domain = ? AND namespace = ?;",
2068 params![alias, destination.domain.0, destination.nspace],
2069 |_| Ok(()),
2070 )
2071 .optional()
2072 .context("Failed to query destination.")?
2073 .is_some()
2074 {
2075 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2076 .context("Target already exists.");
2077 }
2078
2079 let updated = tx
2080 .execute(
2081 "UPDATE persistent.keyentry
2082 SET alias = ?, domain = ?, namespace = ?
2083 WHERE id = ?;",
2084 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2085 )
2086 .context("Failed to update key entry.")?;
2087
2088 if updated != 1 {
2089 return Err(KsError::sys())
2090 .context(format!("Update succeeded, but {} rows were updated.", updated));
2091 }
2092 Ok(()).no_gc()
2093 })
2094 .context("In migrate_key_namespace:")
2095 }
2096
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002097 /// Store a new key in a single transaction.
2098 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2099 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002100 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2101 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002102 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002103 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002104 key: &KeyDescriptor,
2105 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002106 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002107 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002108 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002109 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002110 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002111 let (alias, domain, namespace) = match key {
2112 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2113 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2114 (alias, key.domain, nspace)
2115 }
2116 _ => {
2117 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2118 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2119 }
2120 };
2121 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002122 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002123 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002124 let (blob, blob_metadata) = *blob_info;
2125 Self::set_blob_internal(
2126 tx,
2127 key_id.id(),
2128 SubComponentType::KEY_BLOB,
2129 Some(blob),
2130 Some(&blob_metadata),
2131 )
2132 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002133 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002134 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002135 .context("Trying to insert the certificate.")?;
2136 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002137 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002138 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002139 tx,
2140 key_id.id(),
2141 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002142 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002143 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002144 )
2145 .context("Trying to insert the certificate chain.")?;
2146 }
2147 Self::insert_keyparameter_internal(tx, &key_id, params)
2148 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002149 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002150 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002151 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002152 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002153 })
2154 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002155 }
2156
Janis Danisevskis377d1002021-01-27 19:07:48 -08002157 /// Store a new certificate
2158 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2159 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002160 pub fn store_new_certificate(
2161 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002162 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002163 cert: &[u8],
2164 km_uuid: &Uuid,
2165 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002166 let (alias, domain, namespace) = match key {
2167 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2168 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2169 (alias, key.domain, nspace)
2170 }
2171 _ => {
2172 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2173 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2174 )
2175 }
2176 };
2177 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002178 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002179 .context("Trying to create new key entry.")?;
2180
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002181 Self::set_blob_internal(
2182 tx,
2183 key_id.id(),
2184 SubComponentType::CERT_CHAIN,
2185 Some(cert),
2186 None,
2187 )
2188 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002189
2190 let mut metadata = KeyMetaData::new();
2191 metadata.add(KeyMetaEntry::CreationDate(
2192 DateTime::now().context("Trying to make creation time.")?,
2193 ));
2194
2195 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2196
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002197 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002198 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002199 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002200 })
2201 .context("In store_new_certificate.")
2202 }
2203
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002204 // Helper function loading the key_id given the key descriptor
2205 // tuple comprising domain, namespace, and alias.
2206 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002207 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002208 let alias = key
2209 .alias
2210 .as_ref()
2211 .map_or_else(|| Err(KsError::sys()), Ok)
2212 .context("In load_key_entry_id: Alias must be specified.")?;
2213 let mut stmt = tx
2214 .prepare(
2215 "SELECT id FROM persistent.keyentry
2216 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002217 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002218 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002219 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002220 AND alias = ?
2221 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002222 )
2223 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2224 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002225 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002226 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002227 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002228 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002229 .get(0)
2230 .context("Failed to unpack id.")
2231 })
2232 .context("In load_key_entry_id.")
2233 }
2234
2235 /// This helper function completes the access tuple of a key, which is required
2236 /// to perform access control. The strategy depends on the `domain` field in the
2237 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002238 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002239 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002240 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002241 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002242 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002243 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002244 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002245 /// `namespace`.
2246 /// In each case the information returned is sufficient to perform the access
2247 /// check and the key id can be used to load further key artifacts.
2248 fn load_access_tuple(
2249 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002250 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002251 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002252 caller_uid: u32,
2253 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2254 match key.domain {
2255 // Domain App or SELinux. In this case we load the key_id from
2256 // the keyentry database for further loading of key components.
2257 // We already have the full access tuple to perform access control.
2258 // The only distinction is that we use the caller_uid instead
2259 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002260 // Domain::APP.
2261 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002262 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002263 if access_key.domain == Domain::APP {
2264 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002265 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002266 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002267 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002268
2269 Ok((key_id, access_key, None))
2270 }
2271
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002272 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002273 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002274 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002275 let mut stmt = tx
2276 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002277 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002278 WHERE grantee = ? AND id = ?;",
2279 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002280 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002281 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002282 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002283 .context("Domain:Grant: query failed.")?;
2284 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002285 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002286 let r =
2287 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002288 Ok((
2289 r.get(0).context("Failed to unpack key_id.")?,
2290 r.get(1).context("Failed to unpack access_vector.")?,
2291 ))
2292 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002293 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002294 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002295 }
2296
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002297 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002298 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002299 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002300 let (domain, namespace): (Domain, i64) = {
2301 let mut stmt = tx
2302 .prepare(
2303 "SELECT domain, namespace FROM persistent.keyentry
2304 WHERE
2305 id = ?
2306 AND state = ?;",
2307 )
2308 .context("Domain::KEY_ID: prepare statement failed")?;
2309 let mut rows = stmt
2310 .query(params![key.nspace, KeyLifeCycle::Live])
2311 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002312 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002313 let r =
2314 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002315 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002316 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002317 r.get(1).context("Failed to unpack namespace.")?,
2318 ))
2319 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002320 .context("Domain::KEY_ID.")?
2321 };
2322
2323 // We may use a key by id after loading it by grant.
2324 // In this case we have to check if the caller has a grant for this particular
2325 // key. We can skip this if we already know that the caller is the owner.
2326 // But we cannot know this if domain is anything but App. E.g. in the case
2327 // of Domain::SELINUX we have to speculatively check for grants because we have to
2328 // consult the SEPolicy before we know if the caller is the owner.
2329 let access_vector: Option<KeyPermSet> =
2330 if domain != Domain::APP || namespace != caller_uid as i64 {
2331 let access_vector: Option<i32> = tx
2332 .query_row(
2333 "SELECT access_vector FROM persistent.grant
2334 WHERE grantee = ? AND keyentryid = ?;",
2335 params![caller_uid as i64, key.nspace],
2336 |row| row.get(0),
2337 )
2338 .optional()
2339 .context("Domain::KEY_ID: query grant failed.")?;
2340 access_vector.map(|p| p.into())
2341 } else {
2342 None
2343 };
2344
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002345 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002346 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002347 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002348 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002349
Janis Danisevskis45760022021-01-19 16:34:10 -08002350 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002351 }
2352 _ => Err(anyhow!(KsError::sys())),
2353 }
2354 }
2355
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002356 fn load_blob_components(
2357 key_id: i64,
2358 load_bits: KeyEntryLoadBits,
2359 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002360 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002361 let mut stmt = tx
2362 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002363 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002364 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2365 )
2366 .context("In load_blob_components: prepare statement failed.")?;
2367
2368 let mut rows =
2369 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2370
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002371 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002372 let mut cert_blob: Option<Vec<u8>> = None;
2373 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002374 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002375 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002376 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002377 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002378 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002379 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2380 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002381 key_blob = Some((
2382 row.get(0).context("Failed to extract key blob id.")?,
2383 row.get(2).context("Failed to extract key blob.")?,
2384 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002385 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002386 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002387 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002388 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002389 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002390 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002391 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002392 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002393 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002394 (SubComponentType::CERT, _, _)
2395 | (SubComponentType::CERT_CHAIN, _, _)
2396 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002397 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2398 }
2399 Ok(())
2400 })
2401 .context("In load_blob_components.")?;
2402
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002403 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2404 Ok(Some((
2405 blob,
2406 BlobMetaData::load_from_db(blob_id, tx)
2407 .context("In load_blob_components: Trying to load blob_metadata.")?,
2408 )))
2409 })?;
2410
2411 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002412 }
2413
2414 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2415 let mut stmt = tx
2416 .prepare(
2417 "SELECT tag, data, security_level from persistent.keyparameter
2418 WHERE keyentryid = ?;",
2419 )
2420 .context("In load_key_parameters: prepare statement failed.")?;
2421
2422 let mut parameters: Vec<KeyParameter> = Vec::new();
2423
2424 let mut rows =
2425 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002426 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002427 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2428 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002429 parameters.push(
2430 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2431 .context("Failed to read KeyParameter.")?,
2432 );
2433 Ok(())
2434 })
2435 .context("In load_key_parameters.")?;
2436
2437 Ok(parameters)
2438 }
2439
Qi Wub9433b52020-12-01 14:52:46 +08002440 /// Decrements the usage count of a limited use key. This function first checks whether the
2441 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2442 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2443 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002444 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002445 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2446 let limit: Option<i32> = tx
2447 .query_row(
2448 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2449 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2450 |row| row.get(0),
2451 )
2452 .optional()
2453 .context("Trying to load usage count")?;
2454
2455 let limit = limit
2456 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2457 .context("The Key no longer exists. Key is exhausted.")?;
2458
2459 tx.execute(
2460 "UPDATE persistent.keyparameter
2461 SET data = data - 1
2462 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2463 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2464 )
2465 .context("Failed to update key usage count.")?;
2466
2467 match limit {
2468 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002469 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002470 .context("Trying to mark limited use key for deletion."),
2471 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002472 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002473 }
2474 })
2475 .context("In check_and_update_key_usage_count.")
2476 }
2477
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002478 /// Load a key entry by the given key descriptor.
2479 /// It uses the `check_permission` callback to verify if the access is allowed
2480 /// given the key access tuple read from the database using `load_access_tuple`.
2481 /// With `load_bits` the caller may specify which blobs shall be loaded from
2482 /// the blob database.
2483 pub fn load_key_entry(
2484 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002485 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002486 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002487 load_bits: KeyEntryLoadBits,
2488 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002489 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2490 ) -> Result<(KeyIdGuard, KeyEntry)> {
2491 loop {
2492 match self.load_key_entry_internal(
2493 key,
2494 key_type,
2495 load_bits,
2496 caller_uid,
2497 &check_permission,
2498 ) {
2499 Ok(result) => break Ok(result),
2500 Err(e) => {
2501 if Self::is_locked_error(&e) {
2502 std::thread::sleep(std::time::Duration::from_micros(500));
2503 continue;
2504 } else {
2505 return Err(e).context("In load_key_entry.");
2506 }
2507 }
2508 }
2509 }
2510 }
2511
2512 fn load_key_entry_internal(
2513 &mut self,
2514 key: &KeyDescriptor,
2515 key_type: KeyType,
2516 load_bits: KeyEntryLoadBits,
2517 caller_uid: u32,
2518 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002519 ) -> Result<(KeyIdGuard, KeyEntry)> {
2520 // KEY ID LOCK 1/2
2521 // If we got a key descriptor with a key id we can get the lock right away.
2522 // Otherwise we have to defer it until we know the key id.
2523 let key_id_guard = match key.domain {
2524 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2525 _ => None,
2526 };
2527
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002528 let tx = self
2529 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002530 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002531 .context("In load_key_entry: Failed to initialize transaction.")?;
2532
2533 // Load the key_id and complete the access control tuple.
2534 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002535 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2536 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002537
2538 // Perform access control. It is vital that we return here if the permission is denied.
2539 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002540 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002541
Janis Danisevskisaec14592020-11-12 09:41:49 -08002542 // KEY ID LOCK 2/2
2543 // If we did not get a key id lock by now, it was because we got a key descriptor
2544 // without a key id. At this point we got the key id, so we can try and get a lock.
2545 // However, we cannot block here, because we are in the middle of the transaction.
2546 // So first we try to get the lock non blocking. If that fails, we roll back the
2547 // transaction and block until we get the lock. After we successfully got the lock,
2548 // we start a new transaction and load the access tuple again.
2549 //
2550 // We don't need to perform access control again, because we already established
2551 // that the caller had access to the given key. But we need to make sure that the
2552 // key id still exists. So we have to load the key entry by key id this time.
2553 let (key_id_guard, tx) = match key_id_guard {
2554 None => match KEY_ID_LOCK.try_get(key_id) {
2555 None => {
2556 // Roll back the transaction.
2557 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002558
Janis Danisevskisaec14592020-11-12 09:41:49 -08002559 // Block until we have a key id lock.
2560 let key_id_guard = KEY_ID_LOCK.get(key_id);
2561
2562 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002563 let tx = self
2564 .conn
2565 .unchecked_transaction()
2566 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002567
2568 Self::load_access_tuple(
2569 &tx,
2570 // This time we have to load the key by the retrieved key id, because the
2571 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002572 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002573 domain: Domain::KEY_ID,
2574 nspace: key_id,
2575 ..Default::default()
2576 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002577 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002578 caller_uid,
2579 )
2580 .context("In load_key_entry. (deferred key lock)")?;
2581 (key_id_guard, tx)
2582 }
2583 Some(l) => (l, tx),
2584 },
2585 Some(key_id_guard) => (key_id_guard, tx),
2586 };
2587
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002588 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2589 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002590
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002591 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2592
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002593 Ok((key_id_guard, key_entry))
2594 }
2595
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002596 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002597 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002598 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2599 .context("Trying to delete keyentry.")?;
2600 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2601 .context("Trying to delete keymetadata.")?;
2602 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2603 .context("Trying to delete keyparameters.")?;
2604 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2605 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002606 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002607 }
2608
2609 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002610 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002611 pub fn unbind_key(
2612 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002613 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002614 key_type: KeyType,
2615 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002616 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002617 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002618 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2619 let (key_id, access_key_descriptor, access_vector) =
2620 Self::load_access_tuple(tx, key, key_type, caller_uid)
2621 .context("Trying to get access tuple.")?;
2622
2623 // Perform access control. It is vital that we return here if the permission is denied.
2624 // So do not touch that '?' at the end.
2625 check_permission(&access_key_descriptor, access_vector)
2626 .context("While checking permission.")?;
2627
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002628 Self::mark_unreferenced(tx, key_id)
2629 .map(|need_gc| (need_gc, ()))
2630 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002631 })
2632 .context("In unbind_key.")
2633 }
2634
Max Bires8e93d2b2021-01-14 13:17:59 -08002635 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2636 tx.query_row(
2637 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2638 params![key_id],
2639 |row| row.get(0),
2640 )
2641 .context("In get_key_km_uuid.")
2642 }
2643
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002644 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2645 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2646 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
2647 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2648 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2649 .context("In unbind_keys_for_namespace.");
2650 }
2651 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2652 tx.execute(
2653 "DELETE FROM persistent.keymetadata
2654 WHERE keyentryid IN (
2655 SELECT id FROM persistent.keyentry
2656 WHERE domain = ? AND namespace = ?
2657 );",
2658 params![domain.0, namespace],
2659 )
2660 .context("Trying to delete keymetadata.")?;
2661 tx.execute(
2662 "DELETE FROM persistent.keyparameter
2663 WHERE keyentryid IN (
2664 SELECT id FROM persistent.keyentry
2665 WHERE domain = ? AND namespace = ?
2666 );",
2667 params![domain.0, namespace],
2668 )
2669 .context("Trying to delete keyparameters.")?;
2670 tx.execute(
2671 "DELETE FROM persistent.grant
2672 WHERE keyentryid IN (
2673 SELECT id FROM persistent.keyentry
2674 WHERE domain = ? AND namespace = ?
2675 );",
2676 params![domain.0, namespace],
2677 )
2678 .context("Trying to delete grants.")?;
2679 tx.execute(
2680 "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;",
2681 params![domain.0, namespace],
2682 )
2683 .context("Trying to delete keyentry.")?;
2684 Ok(()).need_gc()
2685 })
2686 .context("In unbind_keys_for_namespace")
2687 }
2688
Hasini Gunasingheda895552021-01-27 19:34:37 +00002689 /// Delete the keys created on behalf of the user, denoted by the user id.
2690 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2691 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2692 /// The caller of this function should notify the gc if the returned value is true.
2693 pub fn unbind_keys_for_user(
2694 &mut self,
2695 user_id: u32,
2696 keep_non_super_encrypted_keys: bool,
2697 ) -> Result<()> {
2698 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2699 let mut stmt = tx
2700 .prepare(&format!(
2701 "SELECT id from persistent.keyentry
2702 WHERE (
2703 key_type = ?
2704 AND domain = ?
2705 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2706 AND state = ?
2707 ) OR (
2708 key_type = ?
2709 AND namespace = ?
2710 AND alias = ?
2711 AND state = ?
2712 );",
2713 aid_user_offset = AID_USER_OFFSET
2714 ))
2715 .context(concat!(
2716 "In unbind_keys_for_user. ",
2717 "Failed to prepare the query to find the keys created by apps."
2718 ))?;
2719
2720 let mut rows = stmt
2721 .query(params![
2722 // WHERE client key:
2723 KeyType::Client,
2724 Domain::APP.0 as u32,
2725 user_id,
2726 KeyLifeCycle::Live,
2727 // OR super key:
2728 KeyType::Super,
2729 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002730 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002731 KeyLifeCycle::Live
2732 ])
2733 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2734
2735 let mut key_ids: Vec<i64> = Vec::new();
2736 db_utils::with_rows_extract_all(&mut rows, |row| {
2737 key_ids
2738 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2739 Ok(())
2740 })
2741 .context("In unbind_keys_for_user.")?;
2742
2743 let mut notify_gc = false;
2744 for key_id in key_ids {
2745 if keep_non_super_encrypted_keys {
2746 // Load metadata and filter out non-super-encrypted keys.
2747 if let (_, Some((_, blob_metadata)), _, _) =
2748 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2749 .context("In unbind_keys_for_user: Trying to load blob info.")?
2750 {
2751 if blob_metadata.encrypted_by().is_none() {
2752 continue;
2753 }
2754 }
2755 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002756 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002757 .context("In unbind_keys_for_user.")?
2758 || notify_gc;
2759 }
2760 Ok(()).do_gc(notify_gc)
2761 })
2762 .context("In unbind_keys_for_user.")
2763 }
2764
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002765 fn load_key_components(
2766 tx: &Transaction,
2767 load_bits: KeyEntryLoadBits,
2768 key_id: i64,
2769 ) -> Result<KeyEntry> {
2770 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2771
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002772 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002773 Self::load_blob_components(key_id, load_bits, &tx)
2774 .context("In load_key_components.")?;
2775
Max Bires8e93d2b2021-01-14 13:17:59 -08002776 let parameters = Self::load_key_parameters(key_id, &tx)
2777 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002778
Max Bires8e93d2b2021-01-14 13:17:59 -08002779 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2780 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002781
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002782 Ok(KeyEntry {
2783 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002784 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002785 cert: cert_blob,
2786 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002787 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002788 parameters,
2789 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002790 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002791 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002792 }
2793
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002794 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2795 /// The key descriptors will have the domain, nspace, and alias field set.
2796 /// Domain must be APP or SELINUX, the caller must make sure of that.
2797 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002798 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2799 let mut stmt = tx
2800 .prepare(
2801 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002802 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002803 )
2804 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002805
Janis Danisevskis66784c42021-01-27 08:40:25 -08002806 let mut rows = stmt
2807 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2808 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002809
Janis Danisevskis66784c42021-01-27 08:40:25 -08002810 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2811 db_utils::with_rows_extract_all(&mut rows, |row| {
2812 descriptors.push(KeyDescriptor {
2813 domain,
2814 nspace: namespace,
2815 alias: Some(row.get(0).context("Trying to extract alias.")?),
2816 blob: None,
2817 });
2818 Ok(())
2819 })
2820 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002821 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002822 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002823 }
2824
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002825 /// Adds a grant to the grant table.
2826 /// Like `load_key_entry` this function loads the access tuple before
2827 /// it uses the callback for a permission check. Upon success,
2828 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2829 /// grant table. The new row will have a randomized id, which is used as
2830 /// grant id in the namespace field of the resulting KeyDescriptor.
2831 pub fn grant(
2832 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002833 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002834 caller_uid: u32,
2835 grantee_uid: u32,
2836 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002837 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002838 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002839 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2840 // Load the key_id and complete the access control tuple.
2841 // We ignore the access vector here because grants cannot be granted.
2842 // The access vector returned here expresses the permissions the
2843 // grantee has if key.domain == Domain::GRANT. But this vector
2844 // cannot include the grant permission by design, so there is no way the
2845 // subsequent permission check can pass.
2846 // We could check key.domain == Domain::GRANT and fail early.
2847 // But even if we load the access tuple by grant here, the permission
2848 // check denies the attempt to create a grant by grant descriptor.
2849 let (key_id, access_key_descriptor, _) =
2850 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2851 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002852
Janis Danisevskis66784c42021-01-27 08:40:25 -08002853 // Perform access control. It is vital that we return here if the permission
2854 // was denied. So do not touch that '?' at the end of the line.
2855 // This permission check checks if the caller has the grant permission
2856 // for the given key and in addition to all of the permissions
2857 // expressed in `access_vector`.
2858 check_permission(&access_key_descriptor, &access_vector)
2859 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002860
Janis Danisevskis66784c42021-01-27 08:40:25 -08002861 let grant_id = if let Some(grant_id) = tx
2862 .query_row(
2863 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002864 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002865 params![key_id, grantee_uid],
2866 |row| row.get(0),
2867 )
2868 .optional()
2869 .context("In grant: Failed get optional existing grant id.")?
2870 {
2871 tx.execute(
2872 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002873 SET access_vector = ?
2874 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002875 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002876 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002877 .context("In grant: Failed to update existing grant.")?;
2878 grant_id
2879 } else {
2880 Self::insert_with_retry(|id| {
2881 tx.execute(
2882 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2883 VALUES (?, ?, ?, ?);",
2884 params![id, grantee_uid, key_id, i32::from(access_vector)],
2885 )
2886 })
2887 .context("In grant")?
2888 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002889
Janis Danisevskis66784c42021-01-27 08:40:25 -08002890 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002891 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002892 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002893 }
2894
2895 /// This function checks permissions like `grant` and `load_key_entry`
2896 /// before removing a grant from the grant table.
2897 pub fn ungrant(
2898 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002899 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002900 caller_uid: u32,
2901 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002902 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002903 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002904 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2905 // Load the key_id and complete the access control tuple.
2906 // We ignore the access vector here because grants cannot be granted.
2907 let (key_id, access_key_descriptor, _) =
2908 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2909 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002910
Janis Danisevskis66784c42021-01-27 08:40:25 -08002911 // Perform access control. We must return here if the permission
2912 // was denied. So do not touch the '?' at the end of this line.
2913 check_permission(&access_key_descriptor)
2914 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002915
Janis Danisevskis66784c42021-01-27 08:40:25 -08002916 tx.execute(
2917 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002918 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002919 params![key_id, grantee_uid],
2920 )
2921 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002922
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002923 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002924 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002925 }
2926
Joel Galenson845f74b2020-09-09 14:11:55 -07002927 // Generates a random id and passes it to the given function, which will
2928 // try to insert it into a database. If that insertion fails, retry;
2929 // otherwise return the id.
2930 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2931 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002932 let newid: i64 = match random() {
2933 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2934 i => i,
2935 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002936 match inserter(newid) {
2937 // If the id already existed, try again.
2938 Err(rusqlite::Error::SqliteFailure(
2939 libsqlite3_sys::Error {
2940 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2941 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2942 },
2943 _,
2944 )) => (),
2945 Err(e) => {
2946 return Err(e).context("In insert_with_retry: failed to insert into database.")
2947 }
2948 _ => return Ok(newid),
2949 }
2950 }
2951 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002952
2953 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
2954 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002955 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2956 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002957 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
2958 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
2959 params![
2960 auth_token.challenge,
2961 auth_token.userId,
2962 auth_token.authenticatorId,
2963 auth_token.authenticatorType.0 as i32,
2964 auth_token.timestamp.milliSeconds as i64,
2965 auth_token.mac,
2966 MonotonicRawTime::now(),
2967 ],
2968 )
2969 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002970 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002971 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002972 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002973
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002974 /// Find the newest auth token matching the given predicate.
2975 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002976 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002977 p: F,
2978 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
2979 where
2980 F: Fn(&AuthTokenEntry) -> bool,
2981 {
2982 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2983 let mut stmt = tx
2984 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
2985 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002986
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002987 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002988
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002989 while let Some(row) = rows.next().context("Failed to get next row.")? {
2990 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002991 HardwareAuthToken {
2992 challenge: row.get(1)?,
2993 userId: row.get(2)?,
2994 authenticatorId: row.get(3)?,
2995 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2996 timestamp: Timestamp { milliSeconds: row.get(5)? },
2997 mac: row.get(6)?,
2998 },
2999 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003000 );
3001 if p(&entry) {
3002 return Ok(Some((
3003 entry,
3004 Self::get_last_off_body(tx)
3005 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003006 )))
3007 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003008 }
3009 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003010 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003011 })
3012 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003013 }
3014
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003015 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003016 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
3017 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3018 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003019 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3020 params!["last_off_body", last_off_body],
3021 )
3022 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003023 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003024 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003025 }
3026
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003027 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003028 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
3029 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3030 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003031 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3032 params![last_off_body, "last_off_body"],
3033 )
3034 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003035 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003036 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003037 }
3038
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003039 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003040 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003041 tx.query_row(
3042 "SELECT value from perboot.metadata WHERE key = ?;",
3043 params!["last_off_body"],
3044 |row| Ok(row.get(0)?),
3045 )
3046 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003047 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003048}
3049
3050#[cfg(test)]
3051mod tests {
3052
3053 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003054 use crate::key_parameter::{
3055 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3056 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3057 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003058 use crate::key_perm_set;
3059 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003060 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003061 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003062 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3063 HardwareAuthToken::HardwareAuthToken,
3064 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003065 };
3066 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003067 Timestamp::Timestamp,
3068 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003069 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003070 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003071 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003072 use std::sync::atomic::{AtomicU8, Ordering};
3073 use std::sync::Arc;
3074 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003075 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003076 #[cfg(disabled)]
3077 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003078
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003079 fn new_test_db() -> Result<KeystoreDB> {
3080 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3081
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003082 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003084 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003085 })?;
3086 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003087 }
3088
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003089 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3090 where
3091 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3092 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003093 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003094
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003095 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003096 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003097
3098 KeystoreDB::new(path, Some(gc))
3099 }
3100
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003101 fn rebind_alias(
3102 db: &mut KeystoreDB,
3103 newid: &KeyIdGuard,
3104 alias: &str,
3105 domain: Domain,
3106 namespace: i64,
3107 ) -> Result<bool> {
3108 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003109 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003110 })
3111 .context("In rebind_alias.")
3112 }
3113
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003114 #[test]
3115 fn datetime() -> Result<()> {
3116 let conn = Connection::open_in_memory()?;
3117 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3118 let now = SystemTime::now();
3119 let duration = Duration::from_secs(1000);
3120 let then = now.checked_sub(duration).unwrap();
3121 let soon = now.checked_add(duration).unwrap();
3122 conn.execute(
3123 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3124 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3125 )?;
3126 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3127 let mut rows = stmt.query(NO_PARAMS)?;
3128 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3129 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3130 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3131 assert!(rows.next()?.is_none());
3132 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3133 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3134 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3135 Ok(())
3136 }
3137
Joel Galenson0891bc12020-07-20 10:37:03 -07003138 // Ensure that we're using the "injected" random function, not the real one.
3139 #[test]
3140 fn test_mocked_random() {
3141 let rand1 = random();
3142 let rand2 = random();
3143 let rand3 = random();
3144 if rand1 == rand2 {
3145 assert_eq!(rand2 + 1, rand3);
3146 } else {
3147 assert_eq!(rand1 + 1, rand2);
3148 assert_eq!(rand2, rand3);
3149 }
3150 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003151
Joel Galenson26f4d012020-07-17 14:57:21 -07003152 // Test that we have the correct tables.
3153 #[test]
3154 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003155 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003156 let tables = db
3157 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003158 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003159 .query_map(params![], |row| row.get(0))?
3160 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003161 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003162 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003163 assert_eq!(tables[1], "blobmetadata");
3164 assert_eq!(tables[2], "grant");
3165 assert_eq!(tables[3], "keyentry");
3166 assert_eq!(tables[4], "keymetadata");
3167 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003168 let tables = db
3169 .conn
3170 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3171 .query_map(params![], |row| row.get(0))?
3172 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003173
3174 assert_eq!(tables.len(), 2);
3175 assert_eq!(tables[0], "authtoken");
3176 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003177 Ok(())
3178 }
3179
3180 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003181 fn test_auth_token_table_invariant() -> Result<()> {
3182 let mut db = new_test_db()?;
3183 let auth_token1 = HardwareAuthToken {
3184 challenge: i64::MAX,
3185 userId: 200,
3186 authenticatorId: 200,
3187 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3188 timestamp: Timestamp { milliSeconds: 500 },
3189 mac: String::from("mac").into_bytes(),
3190 };
3191 db.insert_auth_token(&auth_token1)?;
3192 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3193 assert_eq!(auth_tokens_returned.len(), 1);
3194
3195 // insert another auth token with the same values for the columns in the UNIQUE constraint
3196 // of the auth token table and different value for timestamp
3197 let auth_token2 = HardwareAuthToken {
3198 challenge: i64::MAX,
3199 userId: 200,
3200 authenticatorId: 200,
3201 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3202 timestamp: Timestamp { milliSeconds: 600 },
3203 mac: String::from("mac").into_bytes(),
3204 };
3205
3206 db.insert_auth_token(&auth_token2)?;
3207 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3208 assert_eq!(auth_tokens_returned.len(), 1);
3209
3210 if let Some(auth_token) = auth_tokens_returned.pop() {
3211 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3212 }
3213
3214 // insert another auth token with the different values for the columns in the UNIQUE
3215 // constraint of the auth token table
3216 let auth_token3 = HardwareAuthToken {
3217 challenge: i64::MAX,
3218 userId: 201,
3219 authenticatorId: 200,
3220 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3221 timestamp: Timestamp { milliSeconds: 600 },
3222 mac: String::from("mac").into_bytes(),
3223 };
3224
3225 db.insert_auth_token(&auth_token3)?;
3226 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3227 assert_eq!(auth_tokens_returned.len(), 2);
3228
3229 Ok(())
3230 }
3231
3232 // utility function for test_auth_token_table_invariant()
3233 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3234 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3235
3236 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3237 .query_map(NO_PARAMS, |row| {
3238 Ok(AuthTokenEntry::new(
3239 HardwareAuthToken {
3240 challenge: row.get(1)?,
3241 userId: row.get(2)?,
3242 authenticatorId: row.get(3)?,
3243 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3244 timestamp: Timestamp { milliSeconds: row.get(5)? },
3245 mac: row.get(6)?,
3246 },
3247 row.get(7)?,
3248 ))
3249 })?
3250 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3251 Ok(auth_token_entries)
3252 }
3253
3254 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003255 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003256 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003257 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003258
Janis Danisevskis66784c42021-01-27 08:40:25 -08003259 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003260 let entries = get_keyentry(&db)?;
3261 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003262
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003263 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003264
3265 let entries_new = get_keyentry(&db)?;
3266 assert_eq!(entries, entries_new);
3267 Ok(())
3268 }
3269
3270 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003271 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003272 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3273 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003274 }
3275
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003276 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003277
Janis Danisevskis66784c42021-01-27 08:40:25 -08003278 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3279 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003280
3281 let entries = get_keyentry(&db)?;
3282 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003283 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3284 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003285
3286 // Test that we must pass in a valid Domain.
3287 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003288 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003289 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003290 );
3291 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003292 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003293 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003294 );
3295 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003296 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003297 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003298 );
3299
3300 Ok(())
3301 }
3302
Joel Galenson33c04ad2020-08-03 11:04:38 -07003303 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003304 fn test_add_unsigned_key() -> Result<()> {
3305 let mut db = new_test_db()?;
3306 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3307 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3308 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3309 db.create_attestation_key_entry(
3310 &public_key,
3311 &raw_public_key,
3312 &private_key,
3313 &KEYSTORE_UUID,
3314 )?;
3315 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3316 assert_eq!(keys.len(), 1);
3317 assert_eq!(keys[0], public_key);
3318 Ok(())
3319 }
3320
3321 #[test]
3322 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3323 let mut db = new_test_db()?;
3324 let expiration_date: i64 = 20;
3325 let namespace: i64 = 30;
3326 let base_byte: u8 = 1;
3327 let loaded_values =
3328 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3329 let chain =
3330 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3331 assert_eq!(true, chain.is_some());
3332 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003333 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003334 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3335 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003336 Ok(())
3337 }
3338
3339 #[test]
3340 fn test_get_attestation_pool_status() -> Result<()> {
3341 let mut db = new_test_db()?;
3342 let namespace: i64 = 30;
3343 load_attestation_key_pool(
3344 &mut db, 10, /* expiration */
3345 namespace, 0x01, /* base_byte */
3346 )?;
3347 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3348 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3349 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3350 assert_eq!(status.expiring, 0);
3351 assert_eq!(status.attested, 3);
3352 assert_eq!(status.unassigned, 0);
3353 assert_eq!(status.total, 3);
3354 assert_eq!(
3355 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3356 1
3357 );
3358 assert_eq!(
3359 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3360 2
3361 );
3362 assert_eq!(
3363 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3364 3
3365 );
3366 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3367 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3368 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3369 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003370 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003371 db.create_attestation_key_entry(
3372 &public_key,
3373 &raw_public_key,
3374 &private_key,
3375 &KEYSTORE_UUID,
3376 )?;
3377 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3378 assert_eq!(status.attested, 3);
3379 assert_eq!(status.unassigned, 0);
3380 assert_eq!(status.total, 4);
3381 db.store_signed_attestation_certificate_chain(
3382 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003383 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003384 &cert_chain,
3385 20,
3386 &KEYSTORE_UUID,
3387 )?;
3388 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3389 assert_eq!(status.attested, 4);
3390 assert_eq!(status.unassigned, 1);
3391 assert_eq!(status.total, 4);
3392 Ok(())
3393 }
3394
3395 #[test]
3396 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003397 let temp_dir =
3398 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3399 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003400 let expiration_date: i64 =
3401 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3402 let namespace: i64 = 30;
3403 let namespace_del1: i64 = 45;
3404 let namespace_del2: i64 = 60;
3405 let entry_values = load_attestation_key_pool(
3406 &mut db,
3407 expiration_date,
3408 namespace,
3409 0x01, /* base_byte */
3410 )?;
3411 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3412 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003413
3414 let blob_entry_row_count: u32 = db
3415 .conn
3416 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3417 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003418 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3419 // one key, one certificate chain, and one certificate.
3420 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003421
Max Bires2b2e6562020-09-22 11:22:36 -07003422 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3423
3424 let mut cert_chain =
3425 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003426 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003427 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003428 assert_eq!(entry_values.batch_cert, value.batch_cert);
3429 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003430 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003431
3432 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3433 Domain::APP,
3434 namespace_del1,
3435 &KEYSTORE_UUID,
3436 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003437 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003438 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3439 Domain::APP,
3440 namespace_del2,
3441 &KEYSTORE_UUID,
3442 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003443 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003444
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003445 // Give the garbage collector half a second to catch up.
3446 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003447
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003448 let blob_entry_row_count: u32 = db
3449 .conn
3450 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3451 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003452 // There shound be 3 blob entries left, because we deleted two of the attestation
3453 // key entries with three blobs each.
3454 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003455
Max Bires2b2e6562020-09-22 11:22:36 -07003456 Ok(())
3457 }
3458
3459 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003460 fn test_delete_all_attestation_keys() -> Result<()> {
3461 let mut db = new_test_db()?;
3462 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3463 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3464 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3465 let result = db.delete_all_attestation_keys()?;
3466
3467 // Give the garbage collector half a second to catch up.
3468 std::thread::sleep(Duration::from_millis(500));
3469
3470 // Attestation keys should be deleted, and the regular key should remain.
3471 assert_eq!(result, 2);
3472
3473 Ok(())
3474 }
3475
3476 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003477 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003478 fn extractor(
3479 ke: &KeyEntryRow,
3480 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3481 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003482 }
3483
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003484 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003485 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3486 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003487 let entries = get_keyentry(&db)?;
3488 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003489 assert_eq!(
3490 extractor(&entries[0]),
3491 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3492 );
3493 assert_eq!(
3494 extractor(&entries[1]),
3495 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3496 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003497
3498 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003499 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003500 let entries = get_keyentry(&db)?;
3501 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003502 assert_eq!(
3503 extractor(&entries[0]),
3504 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3505 );
3506 assert_eq!(
3507 extractor(&entries[1]),
3508 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3509 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003510
3511 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003512 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003513 let entries = get_keyentry(&db)?;
3514 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003515 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3516 assert_eq!(
3517 extractor(&entries[1]),
3518 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3519 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003520
3521 // Test that we must pass in a valid Domain.
3522 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003523 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003524 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003525 );
3526 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003527 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003528 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003529 );
3530 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003531 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003532 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003533 );
3534
3535 // Test that we correctly handle setting an alias for something that does not exist.
3536 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003537 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003538 "Expected to update a single entry but instead updated 0",
3539 );
3540 // Test that we correctly abort the transaction in this case.
3541 let entries = get_keyentry(&db)?;
3542 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003543 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3544 assert_eq!(
3545 extractor(&entries[1]),
3546 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3547 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003548
3549 Ok(())
3550 }
3551
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003552 #[test]
3553 fn test_grant_ungrant() -> Result<()> {
3554 const CALLER_UID: u32 = 15;
3555 const GRANTEE_UID: u32 = 12;
3556 const SELINUX_NAMESPACE: i64 = 7;
3557
3558 let mut db = new_test_db()?;
3559 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003560 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3561 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3562 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003563 )?;
3564 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003565 domain: super::Domain::APP,
3566 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003567 alias: Some("key".to_string()),
3568 blob: None,
3569 };
3570 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3571 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3572
3573 // Reset totally predictable random number generator in case we
3574 // are not the first test running on this thread.
3575 reset_random();
3576 let next_random = 0i64;
3577
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003578 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003579 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003580 assert_eq!(*a, PVEC1);
3581 assert_eq!(
3582 *k,
3583 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003584 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003585 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003586 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003587 alias: Some("key".to_string()),
3588 blob: None,
3589 }
3590 );
3591 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003592 })
3593 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003594
3595 assert_eq!(
3596 app_granted_key,
3597 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003598 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003599 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003600 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003601 alias: None,
3602 blob: None,
3603 }
3604 );
3605
3606 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003607 domain: super::Domain::SELINUX,
3608 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003609 alias: Some("yek".to_string()),
3610 blob: None,
3611 };
3612
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003613 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003614 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003615 assert_eq!(*a, PVEC1);
3616 assert_eq!(
3617 *k,
3618 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003619 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003620 // namespace must be the supplied SELinux
3621 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003622 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003623 alias: Some("yek".to_string()),
3624 blob: None,
3625 }
3626 );
3627 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003628 })
3629 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003630
3631 assert_eq!(
3632 selinux_granted_key,
3633 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003634 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003635 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003636 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003637 alias: None,
3638 blob: None,
3639 }
3640 );
3641
3642 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003643 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003644 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003645 assert_eq!(*a, PVEC2);
3646 assert_eq!(
3647 *k,
3648 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003649 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003650 // namespace must be the supplied SELinux
3651 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003652 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003653 alias: Some("yek".to_string()),
3654 blob: None,
3655 }
3656 );
3657 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003658 })
3659 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003660
3661 assert_eq!(
3662 selinux_granted_key,
3663 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003664 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003665 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003666 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003667 alias: None,
3668 blob: None,
3669 }
3670 );
3671
3672 {
3673 // Limiting scope of stmt, because it borrows db.
3674 let mut stmt = db
3675 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003676 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003677 let mut rows =
3678 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3679 Ok((
3680 row.get(0)?,
3681 row.get(1)?,
3682 row.get(2)?,
3683 KeyPermSet::from(row.get::<_, i32>(3)?),
3684 ))
3685 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003686
3687 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003688 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003689 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003690 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003691 assert!(rows.next().is_none());
3692 }
3693
3694 debug_dump_keyentry_table(&mut db)?;
3695 println!("app_key {:?}", app_key);
3696 println!("selinux_key {:?}", selinux_key);
3697
Janis Danisevskis66784c42021-01-27 08:40:25 -08003698 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3699 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003700
3701 Ok(())
3702 }
3703
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003704 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003705 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3706 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3707
3708 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003709 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003710 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003711 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003712 let mut blob_metadata = BlobMetaData::new();
3713 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3714 db.set_blob(
3715 &key_id,
3716 SubComponentType::KEY_BLOB,
3717 Some(TEST_KEY_BLOB),
3718 Some(&blob_metadata),
3719 )?;
3720 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3721 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003722 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003723
3724 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003725 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003726 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003727 )?;
3728 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003729 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3730 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003731 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003732 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003733 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003734 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003735 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003736 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003737 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003738
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003739 drop(rows);
3740 drop(stmt);
3741
3742 assert_eq!(
3743 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3744 BlobMetaData::load_from_db(id, tx).no_gc()
3745 })
3746 .expect("Should find blob metadata."),
3747 blob_metadata
3748 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003749 Ok(())
3750 }
3751
3752 static TEST_ALIAS: &str = "my super duper key";
3753
3754 #[test]
3755 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3756 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003757 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003758 .context("test_insert_and_load_full_keyentry_domain_app")?
3759 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003760 let (_key_guard, key_entry) = db
3761 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003762 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003763 domain: Domain::APP,
3764 nspace: 0,
3765 alias: Some(TEST_ALIAS.to_string()),
3766 blob: None,
3767 },
3768 KeyType::Client,
3769 KeyEntryLoadBits::BOTH,
3770 1,
3771 |_k, _av| Ok(()),
3772 )
3773 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003774 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003775
3776 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003777 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003778 domain: Domain::APP,
3779 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003780 alias: Some(TEST_ALIAS.to_string()),
3781 blob: None,
3782 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003783 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003784 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003785 |_, _| Ok(()),
3786 )
3787 .unwrap();
3788
3789 assert_eq!(
3790 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3791 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003792 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003793 domain: Domain::APP,
3794 nspace: 0,
3795 alias: Some(TEST_ALIAS.to_string()),
3796 blob: None,
3797 },
3798 KeyType::Client,
3799 KeyEntryLoadBits::NONE,
3800 1,
3801 |_k, _av| Ok(()),
3802 )
3803 .unwrap_err()
3804 .root_cause()
3805 .downcast_ref::<KsError>()
3806 );
3807
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003808 Ok(())
3809 }
3810
3811 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003812 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3813 let mut db = new_test_db()?;
3814
3815 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003816 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003817 domain: Domain::APP,
3818 nspace: 1,
3819 alias: Some(TEST_ALIAS.to_string()),
3820 blob: None,
3821 },
3822 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003823 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003824 )
3825 .expect("Trying to insert cert.");
3826
3827 let (_key_guard, mut key_entry) = db
3828 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003829 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003830 domain: Domain::APP,
3831 nspace: 1,
3832 alias: Some(TEST_ALIAS.to_string()),
3833 blob: None,
3834 },
3835 KeyType::Client,
3836 KeyEntryLoadBits::PUBLIC,
3837 1,
3838 |_k, _av| Ok(()),
3839 )
3840 .expect("Trying to read certificate entry.");
3841
3842 assert!(key_entry.pure_cert());
3843 assert!(key_entry.cert().is_none());
3844 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3845
3846 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003847 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003848 domain: Domain::APP,
3849 nspace: 1,
3850 alias: Some(TEST_ALIAS.to_string()),
3851 blob: None,
3852 },
3853 KeyType::Client,
3854 1,
3855 |_, _| Ok(()),
3856 )
3857 .unwrap();
3858
3859 assert_eq!(
3860 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3861 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003862 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003863 domain: Domain::APP,
3864 nspace: 1,
3865 alias: Some(TEST_ALIAS.to_string()),
3866 blob: None,
3867 },
3868 KeyType::Client,
3869 KeyEntryLoadBits::NONE,
3870 1,
3871 |_k, _av| Ok(()),
3872 )
3873 .unwrap_err()
3874 .root_cause()
3875 .downcast_ref::<KsError>()
3876 );
3877
3878 Ok(())
3879 }
3880
3881 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003882 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3883 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003884 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003885 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3886 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003887 let (_key_guard, key_entry) = db
3888 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003889 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003890 domain: Domain::SELINUX,
3891 nspace: 1,
3892 alias: Some(TEST_ALIAS.to_string()),
3893 blob: None,
3894 },
3895 KeyType::Client,
3896 KeyEntryLoadBits::BOTH,
3897 1,
3898 |_k, _av| Ok(()),
3899 )
3900 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003901 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003902
3903 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003904 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003905 domain: Domain::SELINUX,
3906 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003907 alias: Some(TEST_ALIAS.to_string()),
3908 blob: None,
3909 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003910 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003911 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003912 |_, _| Ok(()),
3913 )
3914 .unwrap();
3915
3916 assert_eq!(
3917 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3918 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003919 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003920 domain: Domain::SELINUX,
3921 nspace: 1,
3922 alias: Some(TEST_ALIAS.to_string()),
3923 blob: None,
3924 },
3925 KeyType::Client,
3926 KeyEntryLoadBits::NONE,
3927 1,
3928 |_k, _av| Ok(()),
3929 )
3930 .unwrap_err()
3931 .root_cause()
3932 .downcast_ref::<KsError>()
3933 );
3934
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003935 Ok(())
3936 }
3937
3938 #[test]
3939 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3940 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003941 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003942 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3943 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003944 let (_, key_entry) = db
3945 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003946 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003947 KeyType::Client,
3948 KeyEntryLoadBits::BOTH,
3949 1,
3950 |_k, _av| Ok(()),
3951 )
3952 .unwrap();
3953
Qi Wub9433b52020-12-01 14:52:46 +08003954 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003955
3956 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003957 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003958 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003959 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003960 |_, _| Ok(()),
3961 )
3962 .unwrap();
3963
3964 assert_eq!(
3965 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3966 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003967 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003968 KeyType::Client,
3969 KeyEntryLoadBits::NONE,
3970 1,
3971 |_k, _av| Ok(()),
3972 )
3973 .unwrap_err()
3974 .root_cause()
3975 .downcast_ref::<KsError>()
3976 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003977
3978 Ok(())
3979 }
3980
3981 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003982 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3983 let mut db = new_test_db()?;
3984 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3985 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3986 .0;
3987 // Update the usage count of the limited use key.
3988 db.check_and_update_key_usage_count(key_id)?;
3989
3990 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003991 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003992 KeyType::Client,
3993 KeyEntryLoadBits::BOTH,
3994 1,
3995 |_k, _av| Ok(()),
3996 )?;
3997
3998 // The usage count is decremented now.
3999 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4000
4001 Ok(())
4002 }
4003
4004 #[test]
4005 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4006 let mut db = new_test_db()?;
4007 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4008 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4009 .0;
4010 // Update the usage count of the limited use key.
4011 db.check_and_update_key_usage_count(key_id).expect(concat!(
4012 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4013 "This should succeed."
4014 ));
4015
4016 // Try to update the exhausted limited use key.
4017 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4018 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4019 "This should fail."
4020 ));
4021 assert_eq!(
4022 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4023 e.root_cause().downcast_ref::<KsError>().unwrap()
4024 );
4025
4026 Ok(())
4027 }
4028
4029 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004030 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4031 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004032 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004033 .context("test_insert_and_load_full_keyentry_from_grant")?
4034 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004035
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004036 let granted_key = db
4037 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004038 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004039 domain: Domain::APP,
4040 nspace: 0,
4041 alias: Some(TEST_ALIAS.to_string()),
4042 blob: None,
4043 },
4044 1,
4045 2,
4046 key_perm_set![KeyPerm::use_()],
4047 |_k, _av| Ok(()),
4048 )
4049 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004050
4051 debug_dump_grant_table(&mut db)?;
4052
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004053 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004054 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4055 assert_eq!(Domain::GRANT, k.domain);
4056 assert!(av.unwrap().includes(KeyPerm::use_()));
4057 Ok(())
4058 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004059 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004060
Qi Wub9433b52020-12-01 14:52:46 +08004061 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004062
Janis Danisevskis66784c42021-01-27 08:40:25 -08004063 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004064
4065 assert_eq!(
4066 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4067 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004068 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004069 KeyType::Client,
4070 KeyEntryLoadBits::NONE,
4071 2,
4072 |_k, _av| Ok(()),
4073 )
4074 .unwrap_err()
4075 .root_cause()
4076 .downcast_ref::<KsError>()
4077 );
4078
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004079 Ok(())
4080 }
4081
Janis Danisevskis45760022021-01-19 16:34:10 -08004082 // This test attempts to load a key by key id while the caller is not the owner
4083 // but a grant exists for the given key and the caller.
4084 #[test]
4085 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4086 let mut db = new_test_db()?;
4087 const OWNER_UID: u32 = 1u32;
4088 const GRANTEE_UID: u32 = 2u32;
4089 const SOMEONE_ELSE_UID: u32 = 3u32;
4090 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4091 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4092 .0;
4093
4094 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004095 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004096 domain: Domain::APP,
4097 nspace: 0,
4098 alias: Some(TEST_ALIAS.to_string()),
4099 blob: None,
4100 },
4101 OWNER_UID,
4102 GRANTEE_UID,
4103 key_perm_set![KeyPerm::use_()],
4104 |_k, _av| Ok(()),
4105 )
4106 .unwrap();
4107
4108 debug_dump_grant_table(&mut db)?;
4109
4110 let id_descriptor =
4111 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4112
4113 let (_, key_entry) = db
4114 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004115 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004116 KeyType::Client,
4117 KeyEntryLoadBits::BOTH,
4118 GRANTEE_UID,
4119 |k, av| {
4120 assert_eq!(Domain::APP, k.domain);
4121 assert_eq!(OWNER_UID as i64, k.nspace);
4122 assert!(av.unwrap().includes(KeyPerm::use_()));
4123 Ok(())
4124 },
4125 )
4126 .unwrap();
4127
4128 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4129
4130 let (_, key_entry) = db
4131 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004132 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004133 KeyType::Client,
4134 KeyEntryLoadBits::BOTH,
4135 SOMEONE_ELSE_UID,
4136 |k, av| {
4137 assert_eq!(Domain::APP, k.domain);
4138 assert_eq!(OWNER_UID as i64, k.nspace);
4139 assert!(av.is_none());
4140 Ok(())
4141 },
4142 )
4143 .unwrap();
4144
4145 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4146
Janis Danisevskis66784c42021-01-27 08:40:25 -08004147 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004148
4149 assert_eq!(
4150 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4151 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004152 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004153 KeyType::Client,
4154 KeyEntryLoadBits::NONE,
4155 GRANTEE_UID,
4156 |_k, _av| Ok(()),
4157 )
4158 .unwrap_err()
4159 .root_cause()
4160 .downcast_ref::<KsError>()
4161 );
4162
4163 Ok(())
4164 }
4165
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004166 // Creates a key migrates it to a different location and then tries to access it by the old
4167 // and new location.
4168 #[test]
4169 fn test_migrate_key_app_to_app() -> Result<()> {
4170 let mut db = new_test_db()?;
4171 const SOURCE_UID: u32 = 1u32;
4172 const DESTINATION_UID: u32 = 2u32;
4173 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4174 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4175 let key_id_guard =
4176 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4177 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4178
4179 let source_descriptor: KeyDescriptor = KeyDescriptor {
4180 domain: Domain::APP,
4181 nspace: -1,
4182 alias: Some(SOURCE_ALIAS.to_string()),
4183 blob: None,
4184 };
4185
4186 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4187 domain: Domain::APP,
4188 nspace: -1,
4189 alias: Some(DESTINATION_ALIAS.to_string()),
4190 blob: None,
4191 };
4192
4193 let key_id = key_id_guard.id();
4194
4195 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4196 Ok(())
4197 })
4198 .unwrap();
4199
4200 let (_, key_entry) = db
4201 .load_key_entry(
4202 &destination_descriptor,
4203 KeyType::Client,
4204 KeyEntryLoadBits::BOTH,
4205 DESTINATION_UID,
4206 |k, av| {
4207 assert_eq!(Domain::APP, k.domain);
4208 assert_eq!(DESTINATION_UID as i64, k.nspace);
4209 assert!(av.is_none());
4210 Ok(())
4211 },
4212 )
4213 .unwrap();
4214
4215 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4216
4217 assert_eq!(
4218 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4219 db.load_key_entry(
4220 &source_descriptor,
4221 KeyType::Client,
4222 KeyEntryLoadBits::NONE,
4223 SOURCE_UID,
4224 |_k, _av| Ok(()),
4225 )
4226 .unwrap_err()
4227 .root_cause()
4228 .downcast_ref::<KsError>()
4229 );
4230
4231 Ok(())
4232 }
4233
4234 // Creates a key migrates it to a different location and then tries to access it by the old
4235 // and new location.
4236 #[test]
4237 fn test_migrate_key_app_to_selinux() -> Result<()> {
4238 let mut db = new_test_db()?;
4239 const SOURCE_UID: u32 = 1u32;
4240 const DESTINATION_UID: u32 = 2u32;
4241 const DESTINATION_NAMESPACE: i64 = 1000i64;
4242 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4243 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4244 let key_id_guard =
4245 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4246 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4247
4248 let source_descriptor: KeyDescriptor = KeyDescriptor {
4249 domain: Domain::APP,
4250 nspace: -1,
4251 alias: Some(SOURCE_ALIAS.to_string()),
4252 blob: None,
4253 };
4254
4255 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4256 domain: Domain::SELINUX,
4257 nspace: DESTINATION_NAMESPACE,
4258 alias: Some(DESTINATION_ALIAS.to_string()),
4259 blob: None,
4260 };
4261
4262 let key_id = key_id_guard.id();
4263
4264 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4265 Ok(())
4266 })
4267 .unwrap();
4268
4269 let (_, key_entry) = db
4270 .load_key_entry(
4271 &destination_descriptor,
4272 KeyType::Client,
4273 KeyEntryLoadBits::BOTH,
4274 DESTINATION_UID,
4275 |k, av| {
4276 assert_eq!(Domain::SELINUX, k.domain);
4277 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4278 assert!(av.is_none());
4279 Ok(())
4280 },
4281 )
4282 .unwrap();
4283
4284 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4285
4286 assert_eq!(
4287 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4288 db.load_key_entry(
4289 &source_descriptor,
4290 KeyType::Client,
4291 KeyEntryLoadBits::NONE,
4292 SOURCE_UID,
4293 |_k, _av| Ok(()),
4294 )
4295 .unwrap_err()
4296 .root_cause()
4297 .downcast_ref::<KsError>()
4298 );
4299
4300 Ok(())
4301 }
4302
4303 // Creates two keys and tries to migrate the first to the location of the second which
4304 // is expected to fail.
4305 #[test]
4306 fn test_migrate_key_destination_occupied() -> Result<()> {
4307 let mut db = new_test_db()?;
4308 const SOURCE_UID: u32 = 1u32;
4309 const DESTINATION_UID: u32 = 2u32;
4310 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4311 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4312 let key_id_guard =
4313 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4314 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4315 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4316 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4317
4318 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4319 domain: Domain::APP,
4320 nspace: -1,
4321 alias: Some(DESTINATION_ALIAS.to_string()),
4322 blob: None,
4323 };
4324
4325 assert_eq!(
4326 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4327 db.migrate_key_namespace(
4328 key_id_guard,
4329 &destination_descriptor,
4330 DESTINATION_UID,
4331 |_k| Ok(())
4332 )
4333 .unwrap_err()
4334 .root_cause()
4335 .downcast_ref::<KsError>()
4336 );
4337
4338 Ok(())
4339 }
4340
Janis Danisevskisaec14592020-11-12 09:41:49 -08004341 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4342
Janis Danisevskisaec14592020-11-12 09:41:49 -08004343 #[test]
4344 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4345 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004346 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4347 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004348 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004349 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004350 .context("test_insert_and_load_full_keyentry_domain_app")?
4351 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004352 let (_key_guard, key_entry) = db
4353 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004354 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004355 domain: Domain::APP,
4356 nspace: 0,
4357 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4358 blob: None,
4359 },
4360 KeyType::Client,
4361 KeyEntryLoadBits::BOTH,
4362 33,
4363 |_k, _av| Ok(()),
4364 )
4365 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004366 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004367 let state = Arc::new(AtomicU8::new(1));
4368 let state2 = state.clone();
4369
4370 // Spawning a second thread that attempts to acquire the key id lock
4371 // for the same key as the primary thread. The primary thread then
4372 // waits, thereby forcing the secondary thread into the second stage
4373 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4374 // The test succeeds if the secondary thread observes the transition
4375 // of `state` from 1 to 2, despite having a whole second to overtake
4376 // the primary thread.
4377 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004378 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004379 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004380 assert!(db
4381 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004382 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004383 domain: Domain::APP,
4384 nspace: 0,
4385 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4386 blob: None,
4387 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004388 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004389 KeyEntryLoadBits::BOTH,
4390 33,
4391 |_k, _av| Ok(()),
4392 )
4393 .is_ok());
4394 // We should only see a 2 here because we can only return
4395 // from load_key_entry when the `_key_guard` expires,
4396 // which happens at the end of the scope.
4397 assert_eq!(2, state2.load(Ordering::Relaxed));
4398 });
4399
4400 thread::sleep(std::time::Duration::from_millis(1000));
4401
4402 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4403
4404 // Return the handle from this scope so we can join with the
4405 // secondary thread after the key id lock has expired.
4406 handle
4407 // This is where the `_key_guard` goes out of scope,
4408 // which is the reason for concurrent load_key_entry on the same key
4409 // to unblock.
4410 };
4411 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4412 // main test thread. We will not see failing asserts in secondary threads otherwise.
4413 handle.join().unwrap();
4414 Ok(())
4415 }
4416
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004417 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004418 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004419 let temp_dir =
4420 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4421
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004422 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4423 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004424
4425 let _tx1 = db1
4426 .conn
4427 .transaction_with_behavior(TransactionBehavior::Immediate)
4428 .expect("Failed to create first transaction.");
4429
4430 let error = db2
4431 .conn
4432 .transaction_with_behavior(TransactionBehavior::Immediate)
4433 .context("Transaction begin failed.")
4434 .expect_err("This should fail.");
4435 let root_cause = error.root_cause();
4436 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4437 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4438 {
4439 return;
4440 }
4441 panic!(
4442 "Unexpected error {:?} \n{:?} \n{:?}",
4443 error,
4444 root_cause,
4445 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4446 )
4447 }
4448
4449 #[cfg(disabled)]
4450 #[test]
4451 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4452 let temp_dir = Arc::new(
4453 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4454 .expect("Failed to create temp dir."),
4455 );
4456
4457 let test_begin = Instant::now();
4458
4459 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4460 const KEY_COUNT: u32 = 500u32;
4461 const OPEN_DB_COUNT: u32 = 50u32;
4462
4463 let mut actual_key_count = KEY_COUNT;
4464 // First insert KEY_COUNT keys.
4465 for count in 0..KEY_COUNT {
4466 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4467 actual_key_count = count;
4468 break;
4469 }
4470 let alias = format!("test_alias_{}", count);
4471 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4472 .expect("Failed to make key entry.");
4473 }
4474
4475 // Insert more keys from a different thread and into a different namespace.
4476 let temp_dir1 = temp_dir.clone();
4477 let handle1 = thread::spawn(move || {
4478 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4479
4480 for count in 0..actual_key_count {
4481 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4482 return;
4483 }
4484 let alias = format!("test_alias_{}", count);
4485 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4486 .expect("Failed to make key entry.");
4487 }
4488
4489 // then unbind them again.
4490 for count in 0..actual_key_count {
4491 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4492 return;
4493 }
4494 let key = KeyDescriptor {
4495 domain: Domain::APP,
4496 nspace: -1,
4497 alias: Some(format!("test_alias_{}", count)),
4498 blob: None,
4499 };
4500 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4501 }
4502 });
4503
4504 // And start unbinding the first set of keys.
4505 let temp_dir2 = temp_dir.clone();
4506 let handle2 = thread::spawn(move || {
4507 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4508
4509 for count in 0..actual_key_count {
4510 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4511 return;
4512 }
4513 let key = KeyDescriptor {
4514 domain: Domain::APP,
4515 nspace: -1,
4516 alias: Some(format!("test_alias_{}", count)),
4517 blob: None,
4518 };
4519 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4520 }
4521 });
4522
4523 let stop_deleting = Arc::new(AtomicU8::new(0));
4524 let stop_deleting2 = stop_deleting.clone();
4525
4526 // And delete anything that is unreferenced keys.
4527 let temp_dir3 = temp_dir.clone();
4528 let handle3 = thread::spawn(move || {
4529 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4530
4531 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4532 while let Some((key_guard, _key)) =
4533 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4534 {
4535 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4536 return;
4537 }
4538 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4539 }
4540 std::thread::sleep(std::time::Duration::from_millis(100));
4541 }
4542 });
4543
4544 // While a lot of inserting and deleting is going on we have to open database connections
4545 // successfully and use them.
4546 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4547 // out of scope.
4548 #[allow(clippy::redundant_clone)]
4549 let temp_dir4 = temp_dir.clone();
4550 let handle4 = thread::spawn(move || {
4551 for count in 0..OPEN_DB_COUNT {
4552 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4553 return;
4554 }
4555 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4556
4557 let alias = format!("test_alias_{}", count);
4558 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4559 .expect("Failed to make key entry.");
4560 let key = KeyDescriptor {
4561 domain: Domain::APP,
4562 nspace: -1,
4563 alias: Some(alias),
4564 blob: None,
4565 };
4566 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4567 }
4568 });
4569
4570 handle1.join().expect("Thread 1 panicked.");
4571 handle2.join().expect("Thread 2 panicked.");
4572 handle4.join().expect("Thread 4 panicked.");
4573
4574 stop_deleting.store(1, Ordering::Relaxed);
4575 handle3.join().expect("Thread 3 panicked.");
4576
4577 Ok(())
4578 }
4579
4580 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004581 fn list() -> Result<()> {
4582 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004583 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004584 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4585 (Domain::APP, 1, "test1"),
4586 (Domain::APP, 1, "test2"),
4587 (Domain::APP, 1, "test3"),
4588 (Domain::APP, 1, "test4"),
4589 (Domain::APP, 1, "test5"),
4590 (Domain::APP, 1, "test6"),
4591 (Domain::APP, 1, "test7"),
4592 (Domain::APP, 2, "test1"),
4593 (Domain::APP, 2, "test2"),
4594 (Domain::APP, 2, "test3"),
4595 (Domain::APP, 2, "test4"),
4596 (Domain::APP, 2, "test5"),
4597 (Domain::APP, 2, "test6"),
4598 (Domain::APP, 2, "test8"),
4599 (Domain::SELINUX, 100, "test1"),
4600 (Domain::SELINUX, 100, "test2"),
4601 (Domain::SELINUX, 100, "test3"),
4602 (Domain::SELINUX, 100, "test4"),
4603 (Domain::SELINUX, 100, "test5"),
4604 (Domain::SELINUX, 100, "test6"),
4605 (Domain::SELINUX, 100, "test9"),
4606 ];
4607
4608 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4609 .iter()
4610 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004611 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4612 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004613 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4614 });
4615 (entry.id(), *ns)
4616 })
4617 .collect();
4618
4619 for (domain, namespace) in
4620 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4621 {
4622 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4623 .iter()
4624 .filter_map(|(domain, ns, alias)| match ns {
4625 ns if *ns == *namespace => Some(KeyDescriptor {
4626 domain: *domain,
4627 nspace: *ns,
4628 alias: Some(alias.to_string()),
4629 blob: None,
4630 }),
4631 _ => None,
4632 })
4633 .collect();
4634 list_o_descriptors.sort();
4635 let mut list_result = db.list(*domain, *namespace)?;
4636 list_result.sort();
4637 assert_eq!(list_o_descriptors, list_result);
4638
4639 let mut list_o_ids: Vec<i64> = list_o_descriptors
4640 .into_iter()
4641 .map(|d| {
4642 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004643 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004644 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004645 KeyType::Client,
4646 KeyEntryLoadBits::NONE,
4647 *namespace as u32,
4648 |_, _| Ok(()),
4649 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004650 .unwrap();
4651 entry.id()
4652 })
4653 .collect();
4654 list_o_ids.sort_unstable();
4655 let mut loaded_entries: Vec<i64> = list_o_keys
4656 .iter()
4657 .filter_map(|(id, ns)| match ns {
4658 ns if *ns == *namespace => Some(*id),
4659 _ => None,
4660 })
4661 .collect();
4662 loaded_entries.sort_unstable();
4663 assert_eq!(list_o_ids, loaded_entries);
4664 }
4665 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4666
4667 Ok(())
4668 }
4669
Joel Galenson0891bc12020-07-20 10:37:03 -07004670 // Helpers
4671
4672 // Checks that the given result is an error containing the given string.
4673 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4674 let error_str = format!(
4675 "{:#?}",
4676 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4677 );
4678 assert!(
4679 error_str.contains(target),
4680 "The string \"{}\" should contain \"{}\"",
4681 error_str,
4682 target
4683 );
4684 }
4685
Joel Galenson2aab4432020-07-22 15:27:57 -07004686 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004687 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004688 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004689 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004690 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004691 namespace: Option<i64>,
4692 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004693 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004694 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004695 }
4696
4697 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4698 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004699 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004700 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004701 Ok(KeyEntryRow {
4702 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004703 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004704 domain: match row.get(2)? {
4705 Some(i) => Some(Domain(i)),
4706 None => None,
4707 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004708 namespace: row.get(3)?,
4709 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004710 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004711 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004712 })
4713 })?
4714 .map(|r| r.context("Could not read keyentry row."))
4715 .collect::<Result<Vec<_>>>()
4716 }
4717
Max Biresb2e1d032021-02-08 21:35:05 -08004718 struct RemoteProvValues {
4719 cert_chain: Vec<u8>,
4720 priv_key: Vec<u8>,
4721 batch_cert: Vec<u8>,
4722 }
4723
Max Bires2b2e6562020-09-22 11:22:36 -07004724 fn load_attestation_key_pool(
4725 db: &mut KeystoreDB,
4726 expiration_date: i64,
4727 namespace: i64,
4728 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004729 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004730 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4731 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4732 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4733 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004734 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004735 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4736 db.store_signed_attestation_certificate_chain(
4737 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004738 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004739 &cert_chain,
4740 expiration_date,
4741 &KEYSTORE_UUID,
4742 )?;
4743 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004744 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004745 }
4746
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004747 // Note: The parameters and SecurityLevel associations are nonsensical. This
4748 // collection is only used to check if the parameters are preserved as expected by the
4749 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004750 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4751 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004752 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4753 KeyParameter::new(
4754 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4755 SecurityLevel::TRUSTED_ENVIRONMENT,
4756 ),
4757 KeyParameter::new(
4758 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4759 SecurityLevel::TRUSTED_ENVIRONMENT,
4760 ),
4761 KeyParameter::new(
4762 KeyParameterValue::Algorithm(Algorithm::RSA),
4763 SecurityLevel::TRUSTED_ENVIRONMENT,
4764 ),
4765 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4766 KeyParameter::new(
4767 KeyParameterValue::BlockMode(BlockMode::ECB),
4768 SecurityLevel::TRUSTED_ENVIRONMENT,
4769 ),
4770 KeyParameter::new(
4771 KeyParameterValue::BlockMode(BlockMode::GCM),
4772 SecurityLevel::TRUSTED_ENVIRONMENT,
4773 ),
4774 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4775 KeyParameter::new(
4776 KeyParameterValue::Digest(Digest::MD5),
4777 SecurityLevel::TRUSTED_ENVIRONMENT,
4778 ),
4779 KeyParameter::new(
4780 KeyParameterValue::Digest(Digest::SHA_2_224),
4781 SecurityLevel::TRUSTED_ENVIRONMENT,
4782 ),
4783 KeyParameter::new(
4784 KeyParameterValue::Digest(Digest::SHA_2_256),
4785 SecurityLevel::STRONGBOX,
4786 ),
4787 KeyParameter::new(
4788 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4789 SecurityLevel::TRUSTED_ENVIRONMENT,
4790 ),
4791 KeyParameter::new(
4792 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4793 SecurityLevel::TRUSTED_ENVIRONMENT,
4794 ),
4795 KeyParameter::new(
4796 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4797 SecurityLevel::STRONGBOX,
4798 ),
4799 KeyParameter::new(
4800 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4801 SecurityLevel::TRUSTED_ENVIRONMENT,
4802 ),
4803 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4804 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4805 KeyParameter::new(
4806 KeyParameterValue::EcCurve(EcCurve::P_224),
4807 SecurityLevel::TRUSTED_ENVIRONMENT,
4808 ),
4809 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4810 KeyParameter::new(
4811 KeyParameterValue::EcCurve(EcCurve::P_384),
4812 SecurityLevel::TRUSTED_ENVIRONMENT,
4813 ),
4814 KeyParameter::new(
4815 KeyParameterValue::EcCurve(EcCurve::P_521),
4816 SecurityLevel::TRUSTED_ENVIRONMENT,
4817 ),
4818 KeyParameter::new(
4819 KeyParameterValue::RSAPublicExponent(3),
4820 SecurityLevel::TRUSTED_ENVIRONMENT,
4821 ),
4822 KeyParameter::new(
4823 KeyParameterValue::IncludeUniqueID,
4824 SecurityLevel::TRUSTED_ENVIRONMENT,
4825 ),
4826 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4827 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4828 KeyParameter::new(
4829 KeyParameterValue::ActiveDateTime(1234567890),
4830 SecurityLevel::STRONGBOX,
4831 ),
4832 KeyParameter::new(
4833 KeyParameterValue::OriginationExpireDateTime(1234567890),
4834 SecurityLevel::TRUSTED_ENVIRONMENT,
4835 ),
4836 KeyParameter::new(
4837 KeyParameterValue::UsageExpireDateTime(1234567890),
4838 SecurityLevel::TRUSTED_ENVIRONMENT,
4839 ),
4840 KeyParameter::new(
4841 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4842 SecurityLevel::TRUSTED_ENVIRONMENT,
4843 ),
4844 KeyParameter::new(
4845 KeyParameterValue::MaxUsesPerBoot(1234567890),
4846 SecurityLevel::TRUSTED_ENVIRONMENT,
4847 ),
4848 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4849 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4850 KeyParameter::new(
4851 KeyParameterValue::NoAuthRequired,
4852 SecurityLevel::TRUSTED_ENVIRONMENT,
4853 ),
4854 KeyParameter::new(
4855 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4856 SecurityLevel::TRUSTED_ENVIRONMENT,
4857 ),
4858 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4859 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4860 KeyParameter::new(
4861 KeyParameterValue::TrustedUserPresenceRequired,
4862 SecurityLevel::TRUSTED_ENVIRONMENT,
4863 ),
4864 KeyParameter::new(
4865 KeyParameterValue::TrustedConfirmationRequired,
4866 SecurityLevel::TRUSTED_ENVIRONMENT,
4867 ),
4868 KeyParameter::new(
4869 KeyParameterValue::UnlockedDeviceRequired,
4870 SecurityLevel::TRUSTED_ENVIRONMENT,
4871 ),
4872 KeyParameter::new(
4873 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4874 SecurityLevel::SOFTWARE,
4875 ),
4876 KeyParameter::new(
4877 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4878 SecurityLevel::SOFTWARE,
4879 ),
4880 KeyParameter::new(
4881 KeyParameterValue::CreationDateTime(12345677890),
4882 SecurityLevel::SOFTWARE,
4883 ),
4884 KeyParameter::new(
4885 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4886 SecurityLevel::TRUSTED_ENVIRONMENT,
4887 ),
4888 KeyParameter::new(
4889 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4890 SecurityLevel::TRUSTED_ENVIRONMENT,
4891 ),
4892 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4893 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4894 KeyParameter::new(
4895 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4896 SecurityLevel::SOFTWARE,
4897 ),
4898 KeyParameter::new(
4899 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4900 SecurityLevel::TRUSTED_ENVIRONMENT,
4901 ),
4902 KeyParameter::new(
4903 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4904 SecurityLevel::TRUSTED_ENVIRONMENT,
4905 ),
4906 KeyParameter::new(
4907 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4908 SecurityLevel::TRUSTED_ENVIRONMENT,
4909 ),
4910 KeyParameter::new(
4911 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4912 SecurityLevel::TRUSTED_ENVIRONMENT,
4913 ),
4914 KeyParameter::new(
4915 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4916 SecurityLevel::TRUSTED_ENVIRONMENT,
4917 ),
4918 KeyParameter::new(
4919 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4920 SecurityLevel::TRUSTED_ENVIRONMENT,
4921 ),
4922 KeyParameter::new(
4923 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4924 SecurityLevel::TRUSTED_ENVIRONMENT,
4925 ),
4926 KeyParameter::new(
4927 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4928 SecurityLevel::TRUSTED_ENVIRONMENT,
4929 ),
4930 KeyParameter::new(
4931 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4932 SecurityLevel::TRUSTED_ENVIRONMENT,
4933 ),
4934 KeyParameter::new(
4935 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4936 SecurityLevel::TRUSTED_ENVIRONMENT,
4937 ),
4938 KeyParameter::new(
4939 KeyParameterValue::VendorPatchLevel(3),
4940 SecurityLevel::TRUSTED_ENVIRONMENT,
4941 ),
4942 KeyParameter::new(
4943 KeyParameterValue::BootPatchLevel(4),
4944 SecurityLevel::TRUSTED_ENVIRONMENT,
4945 ),
4946 KeyParameter::new(
4947 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4948 SecurityLevel::TRUSTED_ENVIRONMENT,
4949 ),
4950 KeyParameter::new(
4951 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4952 SecurityLevel::TRUSTED_ENVIRONMENT,
4953 ),
4954 KeyParameter::new(
4955 KeyParameterValue::MacLength(256),
4956 SecurityLevel::TRUSTED_ENVIRONMENT,
4957 ),
4958 KeyParameter::new(
4959 KeyParameterValue::ResetSinceIdRotation,
4960 SecurityLevel::TRUSTED_ENVIRONMENT,
4961 ),
4962 KeyParameter::new(
4963 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4964 SecurityLevel::TRUSTED_ENVIRONMENT,
4965 ),
Qi Wub9433b52020-12-01 14:52:46 +08004966 ];
4967 if let Some(value) = max_usage_count {
4968 params.push(KeyParameter::new(
4969 KeyParameterValue::UsageCountLimit(value),
4970 SecurityLevel::SOFTWARE,
4971 ));
4972 }
4973 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004974 }
4975
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004976 fn make_test_key_entry(
4977 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004978 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004979 namespace: i64,
4980 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004981 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004982 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004983 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004984 let mut blob_metadata = BlobMetaData::new();
4985 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4986 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4987 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4988 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4989 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4990
4991 db.set_blob(
4992 &key_id,
4993 SubComponentType::KEY_BLOB,
4994 Some(TEST_KEY_BLOB),
4995 Some(&blob_metadata),
4996 )?;
4997 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4998 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004999
5000 let params = make_test_params(max_usage_count);
5001 db.insert_keyparameter(&key_id, &params)?;
5002
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005003 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005004 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005005 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005006 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005007 Ok(key_id)
5008 }
5009
Qi Wub9433b52020-12-01 14:52:46 +08005010 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5011 let params = make_test_params(max_usage_count);
5012
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005013 let mut blob_metadata = BlobMetaData::new();
5014 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5015 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5016 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5017 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5018 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5019
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005020 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005021 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005022
5023 KeyEntry {
5024 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005025 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005026 cert: Some(TEST_CERT_BLOB.to_vec()),
5027 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005028 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005029 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005030 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005031 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005032 }
5033 }
5034
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005035 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005036 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005037 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005038 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005039 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005040 NO_PARAMS,
5041 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005042 Ok((
5043 row.get(0)?,
5044 row.get(1)?,
5045 row.get(2)?,
5046 row.get(3)?,
5047 row.get(4)?,
5048 row.get(5)?,
5049 row.get(6)?,
5050 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005051 },
5052 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005053
5054 println!("Key entry table rows:");
5055 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005056 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005057 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005058 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5059 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005060 );
5061 }
5062 Ok(())
5063 }
5064
5065 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005066 let mut stmt = db
5067 .conn
5068 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005069 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5070 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5071 })?;
5072
5073 println!("Grant table rows:");
5074 for r in rows {
5075 let (id, gt, ki, av) = r.unwrap();
5076 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5077 }
5078 Ok(())
5079 }
5080
Joel Galenson0891bc12020-07-20 10:37:03 -07005081 // Use a custom random number generator that repeats each number once.
5082 // This allows us to test repeated elements.
5083
5084 thread_local! {
5085 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5086 }
5087
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005088 fn reset_random() {
5089 RANDOM_COUNTER.with(|counter| {
5090 *counter.borrow_mut() = 0;
5091 })
5092 }
5093
Joel Galenson0891bc12020-07-20 10:37:03 -07005094 pub fn random() -> i64 {
5095 RANDOM_COUNTER.with(|counter| {
5096 let result = *counter.borrow() / 2;
5097 *counter.borrow_mut() += 1;
5098 result
5099 })
5100 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005101
5102 #[test]
5103 fn test_last_off_body() -> Result<()> {
5104 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005105 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005106 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5107 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5108 tx.commit()?;
5109 let one_second = Duration::from_secs(1);
5110 thread::sleep(one_second);
5111 db.update_last_off_body(MonotonicRawTime::now())?;
5112 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5113 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5114 tx2.commit()?;
5115 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5116 Ok(())
5117 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005118
5119 #[test]
5120 fn test_unbind_keys_for_user() -> Result<()> {
5121 let mut db = new_test_db()?;
5122 db.unbind_keys_for_user(1, false)?;
5123
5124 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5125 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5126 db.unbind_keys_for_user(2, false)?;
5127
5128 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5129 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5130
5131 db.unbind_keys_for_user(1, true)?;
5132 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5133
5134 Ok(())
5135 }
5136
5137 #[test]
5138 fn test_store_super_key() -> Result<()> {
5139 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005140 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005141 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005142 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005143 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005144 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005145
5146 let (encrypted_super_key, metadata) =
5147 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005148 db.store_super_key(
5149 1,
5150 &USER_SUPER_KEY,
5151 &encrypted_super_key,
5152 &metadata,
5153 &KeyMetaData::new(),
5154 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005155
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005156 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005157 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005158
Paul Crowley7a658392021-03-18 17:08:20 -07005159 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005160 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5161 USER_SUPER_KEY.algorithm,
5162 key_entry,
5163 &pw,
5164 None,
5165 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005166
Paul Crowley7a658392021-03-18 17:08:20 -07005167 let decrypted_secret_bytes =
5168 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5169 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005170 Ok(())
5171 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005172}