blob: dc6d7a04a35f8ea02f01b64604d7972bb34b920a [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
Qi Wub9433b52020-12-01 14:52:46 +080044use crate::error::{Error as KsError, ErrorCode, ResponseCode};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080045use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080046use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070047use crate::permission::KeyPermSet;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +000048use crate::utils::get_current_time_in_seconds;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080049use crate::{
50 db_utils::{self, SqlField},
51 gc::Gc,
52};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080053use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080054use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070055
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000056use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080057 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000058 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080059};
60use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000061 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070063use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070064 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070065};
Max Bires2b2e6562020-09-22 11:22:36 -070066use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
67 AttestationPoolStatus::AttestationPoolStatus,
68};
69
70use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080071use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000072use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070073#[cfg(not(test))]
74use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070075use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080076 params,
77 types::FromSql,
78 types::FromSqlResult,
79 types::ToSqlOutput,
80 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080081 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070082};
Max Bires2b2e6562020-09-22 11:22:36 -070083
Janis Danisevskisaec14592020-11-12 09:41:49 -080084use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080085 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080086 path::Path,
87 sync::{Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080088 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080089};
Max Bires2b2e6562020-09-22 11:22:36 -070090
Joel Galenson0891bc12020-07-20 10:37:03 -070091#[cfg(test)]
92use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070093
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094impl_metadata!(
95 /// A set of metadata for key entries.
96 #[derive(Debug, Default, Eq, PartialEq)]
97 pub struct KeyMetaData;
98 /// A metadata entry for key entries.
99 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
100 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800101 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800102 CreationDate(DateTime) with accessor creation_date,
103 /// Expiration date for attestation keys.
104 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700105 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
106 /// provisioning
107 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
108 /// Vector representing the raw public key so results from the server can be matched
109 /// to the right entry
110 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800111 // --- ADD NEW META DATA FIELDS HERE ---
112 // For backwards compatibility add new entries only to
113 // end of this list and above this comment.
114 };
115);
116
117impl KeyMetaData {
118 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
119 let mut stmt = tx
120 .prepare(
121 "SELECT tag, data from persistent.keymetadata
122 WHERE keyentryid = ?;",
123 )
124 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
125
126 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
127
128 let mut rows =
129 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
130 db_utils::with_rows_extract_all(&mut rows, |row| {
131 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
132 metadata.insert(
133 db_tag,
134 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
135 .context("Failed to read KeyMetaEntry.")?,
136 );
137 Ok(())
138 })
139 .context("In KeyMetaData::load_from_db.")?;
140
141 Ok(Self { data: metadata })
142 }
143
144 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
145 let mut stmt = tx
146 .prepare(
147 "INSERT into persistent.keymetadata (keyentryid, tag, data)
148 VALUES (?, ?, ?);",
149 )
150 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
151
152 let iter = self.data.iter();
153 for (tag, entry) in iter {
154 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
155 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
156 })?;
157 }
158 Ok(())
159 }
160}
161
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800162impl_metadata!(
163 /// A set of metadata for key blobs.
164 #[derive(Debug, Default, Eq, PartialEq)]
165 pub struct BlobMetaData;
166 /// A metadata entry for key blobs.
167 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
168 pub enum BlobMetaEntry {
169 /// If present, indicates that the blob is encrypted with another key or a key derived
170 /// from a password.
171 EncryptedBy(EncryptedBy) with accessor encrypted_by,
172 /// If the blob is password encrypted this field is set to the
173 /// salt used for the key derivation.
174 Salt(Vec<u8>) with accessor salt,
175 /// If the blob is encrypted, this field is set to the initialization vector.
176 Iv(Vec<u8>) with accessor iv,
177 /// If the blob is encrypted, this field holds the AEAD TAG.
178 AeadTag(Vec<u8>) with accessor aead_tag,
179 /// The uuid of the owning KeyMint instance.
180 KmUuid(Uuid) with accessor km_uuid,
181 // --- ADD NEW META DATA FIELDS HERE ---
182 // For backwards compatibility add new entries only to
183 // end of this list and above this comment.
184 };
185);
186
187impl BlobMetaData {
188 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
189 let mut stmt = tx
190 .prepare(
191 "SELECT tag, data from persistent.blobmetadata
192 WHERE blobentryid = ?;",
193 )
194 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
195
196 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
197
198 let mut rows =
199 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
200 db_utils::with_rows_extract_all(&mut rows, |row| {
201 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
202 metadata.insert(
203 db_tag,
204 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
205 .context("Failed to read BlobMetaEntry.")?,
206 );
207 Ok(())
208 })
209 .context("In BlobMetaData::load_from_db.")?;
210
211 Ok(Self { data: metadata })
212 }
213
214 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
215 let mut stmt = tx
216 .prepare(
217 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
218 VALUES (?, ?, ?);",
219 )
220 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
221
222 let iter = self.data.iter();
223 for (tag, entry) in iter {
224 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
225 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
226 })?;
227 }
228 Ok(())
229 }
230}
231
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800232/// Indicates the type of the keyentry.
233#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
234pub enum KeyType {
235 /// This is a client key type. These keys are created or imported through the Keystore 2.0
236 /// AIDL interface android.system.keystore2.
237 Client,
238 /// This is a super key type. These keys are created by keystore itself and used to encrypt
239 /// other key blobs to provide LSKF binding.
240 Super,
241 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
242 Attestation,
243}
244
245impl ToSql for KeyType {
246 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
247 Ok(ToSqlOutput::Owned(Value::Integer(match self {
248 KeyType::Client => 0,
249 KeyType::Super => 1,
250 KeyType::Attestation => 2,
251 })))
252 }
253}
254
255impl FromSql for KeyType {
256 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
257 match i64::column_result(value)? {
258 0 => Ok(KeyType::Client),
259 1 => Ok(KeyType::Super),
260 2 => Ok(KeyType::Attestation),
261 v => Err(FromSqlError::OutOfRange(v)),
262 }
263 }
264}
265
Max Bires8e93d2b2021-01-14 13:17:59 -0800266/// Uuid representation that can be stored in the database.
267/// Right now it can only be initialized from SecurityLevel.
268/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
269#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
270pub struct Uuid([u8; 16]);
271
272impl Deref for Uuid {
273 type Target = [u8; 16];
274
275 fn deref(&self) -> &Self::Target {
276 &self.0
277 }
278}
279
280impl From<SecurityLevel> for Uuid {
281 fn from(sec_level: SecurityLevel) -> Self {
282 Self((sec_level.0 as u128).to_be_bytes())
283 }
284}
285
286impl ToSql for Uuid {
287 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
288 self.0.to_sql()
289 }
290}
291
292impl FromSql for Uuid {
293 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
294 let blob = Vec::<u8>::column_result(value)?;
295 if blob.len() != 16 {
296 return Err(FromSqlError::OutOfRange(blob.len() as i64));
297 }
298 let mut arr = [0u8; 16];
299 arr.copy_from_slice(&blob);
300 Ok(Self(arr))
301 }
302}
303
304/// Key entries that are not associated with any KeyMint instance, such as pure certificate
305/// entries are associated with this UUID.
306pub static KEYSTORE_UUID: Uuid = Uuid([
307 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
308]);
309
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800310/// Indicates how the sensitive part of this key blob is encrypted.
311#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
312pub enum EncryptedBy {
313 /// The keyblob is encrypted by a user password.
314 /// In the database this variant is represented as NULL.
315 Password,
316 /// The keyblob is encrypted by another key with wrapped key id.
317 /// In the database this variant is represented as non NULL value
318 /// that is convertible to i64, typically NUMERIC.
319 KeyId(i64),
320}
321
322impl ToSql for EncryptedBy {
323 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
324 match self {
325 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
326 Self::KeyId(id) => id.to_sql(),
327 }
328 }
329}
330
331impl FromSql for EncryptedBy {
332 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
333 match value {
334 ValueRef::Null => Ok(Self::Password),
335 _ => Ok(Self::KeyId(i64::column_result(value)?)),
336 }
337 }
338}
339
340/// A database representation of wall clock time. DateTime stores unix epoch time as
341/// i64 in milliseconds.
342#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
343pub struct DateTime(i64);
344
345/// Error type returned when creating DateTime or converting it from and to
346/// SystemTime.
347#[derive(thiserror::Error, Debug)]
348pub enum DateTimeError {
349 /// This is returned when SystemTime and Duration computations fail.
350 #[error(transparent)]
351 SystemTimeError(#[from] SystemTimeError),
352
353 /// This is returned when type conversions fail.
354 #[error(transparent)]
355 TypeConversion(#[from] std::num::TryFromIntError),
356
357 /// This is returned when checked time arithmetic failed.
358 #[error("Time arithmetic failed.")]
359 TimeArithmetic,
360}
361
362impl DateTime {
363 /// Constructs a new DateTime object denoting the current time. This may fail during
364 /// conversion to unix epoch time and during conversion to the internal i64 representation.
365 pub fn now() -> Result<Self, DateTimeError> {
366 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
367 }
368
369 /// Constructs a new DateTime object from milliseconds.
370 pub fn from_millis_epoch(millis: i64) -> Self {
371 Self(millis)
372 }
373
374 /// Returns unix epoch time in milliseconds.
375 pub fn to_millis_epoch(&self) -> i64 {
376 self.0
377 }
378
379 /// Returns unix epoch time in seconds.
380 pub fn to_secs_epoch(&self) -> i64 {
381 self.0 / 1000
382 }
383}
384
385impl ToSql for DateTime {
386 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
387 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
388 }
389}
390
391impl FromSql for DateTime {
392 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
393 Ok(Self(i64::column_result(value)?))
394 }
395}
396
397impl TryInto<SystemTime> for DateTime {
398 type Error = DateTimeError;
399
400 fn try_into(self) -> Result<SystemTime, Self::Error> {
401 // We want to construct a SystemTime representation equivalent to self, denoting
402 // a point in time THEN, but we cannot set the time directly. We can only construct
403 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
404 // and between EPOCH and THEN. With this common reference we can construct the
405 // duration between NOW and THEN which we can add to our SystemTime representation
406 // of NOW to get a SystemTime representation of THEN.
407 // Durations can only be positive, thus the if statement below.
408 let now = SystemTime::now();
409 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
410 let then_epoch = Duration::from_millis(self.0.try_into()?);
411 Ok(if now_epoch > then_epoch {
412 // then = now - (now_epoch - then_epoch)
413 now_epoch
414 .checked_sub(then_epoch)
415 .and_then(|d| now.checked_sub(d))
416 .ok_or(DateTimeError::TimeArithmetic)?
417 } else {
418 // then = now + (then_epoch - now_epoch)
419 then_epoch
420 .checked_sub(now_epoch)
421 .and_then(|d| now.checked_add(d))
422 .ok_or(DateTimeError::TimeArithmetic)?
423 })
424 }
425}
426
427impl TryFrom<SystemTime> for DateTime {
428 type Error = DateTimeError;
429
430 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
431 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
432 }
433}
434
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800435#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
436enum KeyLifeCycle {
437 /// Existing keys have a key ID but are not fully populated yet.
438 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
439 /// them to Unreferenced for garbage collection.
440 Existing,
441 /// A live key is fully populated and usable by clients.
442 Live,
443 /// An unreferenced key is scheduled for garbage collection.
444 Unreferenced,
445}
446
447impl ToSql for KeyLifeCycle {
448 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
449 match self {
450 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
451 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
452 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
453 }
454 }
455}
456
457impl FromSql for KeyLifeCycle {
458 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
459 match i64::column_result(value)? {
460 0 => Ok(KeyLifeCycle::Existing),
461 1 => Ok(KeyLifeCycle::Live),
462 2 => Ok(KeyLifeCycle::Unreferenced),
463 v => Err(FromSqlError::OutOfRange(v)),
464 }
465 }
466}
467
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700468/// Keys have a KeyMint blob component and optional public certificate and
469/// certificate chain components.
470/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
471/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800472#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700473pub struct KeyEntryLoadBits(u32);
474
475impl KeyEntryLoadBits {
476 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
477 pub const NONE: KeyEntryLoadBits = Self(0);
478 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
479 pub const KM: KeyEntryLoadBits = Self(1);
480 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
481 pub const PUBLIC: KeyEntryLoadBits = Self(2);
482 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
483 pub const BOTH: KeyEntryLoadBits = Self(3);
484
485 /// Returns true if this object indicates that the public components shall be loaded.
486 pub const fn load_public(&self) -> bool {
487 self.0 & Self::PUBLIC.0 != 0
488 }
489
490 /// Returns true if the object indicates that the KeyMint component shall be loaded.
491 pub const fn load_km(&self) -> bool {
492 self.0 & Self::KM.0 != 0
493 }
494}
495
Janis Danisevskisaec14592020-11-12 09:41:49 -0800496lazy_static! {
497 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
498}
499
500struct KeyIdLockDb {
501 locked_keys: Mutex<HashSet<i64>>,
502 cond_var: Condvar,
503}
504
505/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
506/// from the database a second time. Most functions manipulating the key blob database
507/// require a KeyIdGuard.
508#[derive(Debug)]
509pub struct KeyIdGuard(i64);
510
511impl KeyIdLockDb {
512 fn new() -> Self {
513 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
514 }
515
516 /// This function blocks until an exclusive lock for the given key entry id can
517 /// be acquired. It returns a guard object, that represents the lifecycle of the
518 /// acquired lock.
519 pub fn get(&self, key_id: i64) -> KeyIdGuard {
520 let mut locked_keys = self.locked_keys.lock().unwrap();
521 while locked_keys.contains(&key_id) {
522 locked_keys = self.cond_var.wait(locked_keys).unwrap();
523 }
524 locked_keys.insert(key_id);
525 KeyIdGuard(key_id)
526 }
527
528 /// This function attempts to acquire an exclusive lock on a given key id. If the
529 /// given key id is already taken the function returns None immediately. If a lock
530 /// can be acquired this function returns a guard object, that represents the
531 /// lifecycle of the acquired lock.
532 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 if locked_keys.insert(key_id) {
535 Some(KeyIdGuard(key_id))
536 } else {
537 None
538 }
539 }
540}
541
542impl KeyIdGuard {
543 /// Get the numeric key id of the locked key.
544 pub fn id(&self) -> i64 {
545 self.0
546 }
547}
548
549impl Drop for KeyIdGuard {
550 fn drop(&mut self) {
551 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
552 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800553 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800554 KEY_ID_LOCK.cond_var.notify_all();
555 }
556}
557
Max Bires8e93d2b2021-01-14 13:17:59 -0800558/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700559#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800560pub struct CertificateInfo {
561 cert: Option<Vec<u8>>,
562 cert_chain: Option<Vec<u8>>,
563}
564
565impl CertificateInfo {
566 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
567 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
568 Self { cert, cert_chain }
569 }
570
571 /// Take the cert
572 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
573 self.cert.take()
574 }
575
576 /// Take the cert chain
577 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
578 self.cert_chain.take()
579 }
580}
581
Max Bires2b2e6562020-09-22 11:22:36 -0700582/// This type represents a certificate chain with a private key corresponding to the leaf
583/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
584#[allow(dead_code)]
585pub struct CertificateChain {
586 private_key: ZVec,
587 cert_chain: ZVec,
588}
589
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700590/// This type represents a Keystore 2.0 key entry.
591/// An entry has a unique `id` by which it can be found in the database.
592/// It has a security level field, key parameters, and three optional fields
593/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800594#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700595pub struct KeyEntry {
596 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800597 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700598 cert: Option<Vec<u8>>,
599 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800600 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700601 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800602 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800603 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700604}
605
606impl KeyEntry {
607 /// Returns the unique id of the Key entry.
608 pub fn id(&self) -> i64 {
609 self.id
610 }
611 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800612 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
613 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700614 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800615 /// Extracts the Optional KeyMint blob including its metadata.
616 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
617 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700618 }
619 /// Exposes the optional public certificate.
620 pub fn cert(&self) -> &Option<Vec<u8>> {
621 &self.cert
622 }
623 /// Extracts the optional public certificate.
624 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
625 self.cert.take()
626 }
627 /// Exposes the optional public certificate chain.
628 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
629 &self.cert_chain
630 }
631 /// Extracts the optional public certificate_chain.
632 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
633 self.cert_chain.take()
634 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800635 /// Returns the uuid of the owning KeyMint instance.
636 pub fn km_uuid(&self) -> &Uuid {
637 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700638 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700639 /// Exposes the key parameters of this key entry.
640 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
641 &self.parameters
642 }
643 /// Consumes this key entry and extracts the keyparameters from it.
644 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
645 self.parameters
646 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800647 /// Exposes the key metadata of this key entry.
648 pub fn metadata(&self) -> &KeyMetaData {
649 &self.metadata
650 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800651 /// This returns true if the entry is a pure certificate entry with no
652 /// private key component.
653 pub fn pure_cert(&self) -> bool {
654 self.pure_cert
655 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700656}
657
658/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800659#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700660pub struct SubComponentType(u32);
661impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800662 /// Persistent identifier for a key blob.
663 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700664 /// Persistent identifier for a certificate blob.
665 pub const CERT: SubComponentType = Self(1);
666 /// Persistent identifier for a certificate chain blob.
667 pub const CERT_CHAIN: SubComponentType = Self(2);
668}
669
670impl ToSql for SubComponentType {
671 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
672 self.0.to_sql()
673 }
674}
675
676impl FromSql for SubComponentType {
677 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
678 Ok(Self(u32::column_result(value)?))
679 }
680}
681
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800682/// This trait is private to the database module. It is used to convey whether or not the garbage
683/// collector shall be invoked after a database access. All closures passed to
684/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
685/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
686/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
687/// `.need_gc()`.
688trait DoGc<T> {
689 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
690
691 fn no_gc(self) -> Result<(bool, T)>;
692
693 fn need_gc(self) -> Result<(bool, T)>;
694}
695
696impl<T> DoGc<T> for Result<T> {
697 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
698 self.map(|r| (need_gc, r))
699 }
700
701 fn no_gc(self) -> Result<(bool, T)> {
702 self.do_gc(false)
703 }
704
705 fn need_gc(self) -> Result<(bool, T)> {
706 self.do_gc(true)
707 }
708}
709
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700710/// KeystoreDB wraps a connection to an SQLite database and tracks its
711/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700712pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700713 conn: Connection,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800714 gc: Option<Gc>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700715}
716
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000717/// Database representation of the monotonic time retrieved from the system call clock_gettime with
718/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
719#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
720pub struct MonotonicRawTime(i64);
721
722impl MonotonicRawTime {
723 /// Constructs a new MonotonicRawTime
724 pub fn now() -> Self {
725 Self(get_current_time_in_seconds())
726 }
727
728 /// Returns the integer value of MonotonicRawTime as i64
729 pub fn seconds(&self) -> i64 {
730 self.0
731 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800732
733 /// Like i64::checked_sub.
734 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
735 self.0.checked_sub(other.0).map(Self)
736 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000737}
738
739impl ToSql for MonotonicRawTime {
740 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
741 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
742 }
743}
744
745impl FromSql for MonotonicRawTime {
746 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
747 Ok(Self(i64::column_result(value)?))
748 }
749}
750
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000751/// This struct encapsulates the information to be stored in the database about the auth tokens
752/// received by keystore.
753pub struct AuthTokenEntry {
754 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000756}
757
758impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000759 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000760 AuthTokenEntry { auth_token, time_received }
761 }
762
763 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800764 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000765 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800766 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
767 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000768 })
769 }
770
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000771 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800772 pub fn auth_token(&self) -> &HardwareAuthToken {
773 &self.auth_token
774 }
775
776 /// Returns the auth token wrapped by the AuthTokenEntry
777 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000778 self.auth_token
779 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800780
781 /// Returns the time that this auth token was received.
782 pub fn time_received(&self) -> MonotonicRawTime {
783 self.time_received
784 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000785}
786
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800787/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
788/// This object does not allow access to the database connection. But it keeps a database
789/// connection alive in order to keep the in memory per boot database alive.
790pub struct PerBootDbKeepAlive(Connection);
791
Joel Galenson26f4d012020-07-17 14:57:21 -0700792impl KeystoreDB {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800793 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
794
795 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
796 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
797 let conn = Connection::open_in_memory()
798 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
799
800 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
801 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
802 Ok(PerBootDbKeepAlive(conn))
803 }
804
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700805 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800806 /// files persistent.sqlite and perboot.sqlite in the given directory.
807 /// It also attempts to initialize all of the tables.
808 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700809 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800810 pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800811 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800812 let mut persistent_path = db_root.to_path_buf();
813 persistent_path.push("persistent.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700814
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800815 // Now convert them to strings prefixed with "file:"
816 let mut persistent_path_str = "file:".to_owned();
817 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800818
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800819 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800820
Janis Danisevskis66784c42021-01-27 08:40:25 -0800821 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
822 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
823
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800824 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800825 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800826 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800827 })?;
828 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700829 }
830
Janis Danisevskis66784c42021-01-27 08:40:25 -0800831 fn init_tables(tx: &Transaction) -> Result<()> {
832 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700833 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700834 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800835 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700836 domain INTEGER,
837 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800838 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800839 state INTEGER,
840 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700841 NO_PARAMS,
842 )
843 .context("Failed to initialize \"keyentry\" table.")?;
844
Janis Danisevskis66784c42021-01-27 08:40:25 -0800845 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800846 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
847 ON keyentry(id);",
848 NO_PARAMS,
849 )
850 .context("Failed to create index keyentry_id_index.")?;
851
852 tx.execute(
853 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
854 ON keyentry(domain, namespace, alias);",
855 NO_PARAMS,
856 )
857 .context("Failed to create index keyentry_domain_namespace_index.")?;
858
859 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700860 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
861 id INTEGER PRIMARY KEY,
862 subcomponent_type INTEGER,
863 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800864 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700865 NO_PARAMS,
866 )
867 .context("Failed to initialize \"blobentry\" table.")?;
868
Janis Danisevskis66784c42021-01-27 08:40:25 -0800869 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800870 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
871 ON blobentry(keyentryid);",
872 NO_PARAMS,
873 )
874 .context("Failed to create index blobentry_keyentryid_index.")?;
875
876 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800877 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
878 id INTEGER PRIMARY KEY,
879 blobentryid INTEGER,
880 tag INTEGER,
881 data ANY,
882 UNIQUE (blobentryid, tag));",
883 NO_PARAMS,
884 )
885 .context("Failed to initialize \"blobmetadata\" table.")?;
886
887 tx.execute(
888 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
889 ON blobmetadata(blobentryid);",
890 NO_PARAMS,
891 )
892 .context("Failed to create index blobmetadata_blobentryid_index.")?;
893
894 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700895 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000896 keyentryid INTEGER,
897 tag INTEGER,
898 data ANY,
899 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700900 NO_PARAMS,
901 )
902 .context("Failed to initialize \"keyparameter\" table.")?;
903
Janis Danisevskis66784c42021-01-27 08:40:25 -0800904 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800905 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
906 ON keyparameter(keyentryid);",
907 NO_PARAMS,
908 )
909 .context("Failed to create index keyparameter_keyentryid_index.")?;
910
911 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800912 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
913 keyentryid INTEGER,
914 tag INTEGER,
915 data ANY);",
916 NO_PARAMS,
917 )
918 .context("Failed to initialize \"keymetadata\" table.")?;
919
Janis Danisevskis66784c42021-01-27 08:40:25 -0800920 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800921 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
922 ON keymetadata(keyentryid);",
923 NO_PARAMS,
924 )
925 .context("Failed to create index keymetadata_keyentryid_index.")?;
926
927 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800928 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700929 id INTEGER UNIQUE,
930 grantee INTEGER,
931 keyentryid INTEGER,
932 access_vector INTEGER);",
933 NO_PARAMS,
934 )
935 .context("Failed to initialize \"grant\" table.")?;
936
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000937 //TODO: only drop the following two perboot tables if this is the first start up
938 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800939 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000940 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800941 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000942 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
943 id INTEGER PRIMARY KEY,
944 challenge INTEGER,
945 user_id INTEGER,
946 auth_id INTEGER,
947 authenticator_type INTEGER,
948 timestamp INTEGER,
949 mac BLOB,
950 time_received INTEGER,
951 UNIQUE(user_id, auth_id, authenticator_type));",
952 NO_PARAMS,
953 )
954 .context("Failed to initialize \"authtoken\" table.")?;
955
Janis Danisevskis66784c42021-01-27 08:40:25 -0800956 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000957 // .context("Failed to drop perboot.metadata table")?;
958 // metadata table stores certain miscellaneous information required for keystore functioning
959 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800960 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000961 "CREATE TABLE IF NOT EXISTS perboot.metadata (
962 key TEXT,
963 value BLOB,
964 UNIQUE(key));",
965 NO_PARAMS,
966 )
967 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -0700968 Ok(())
969 }
970
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700971 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
972 let conn =
973 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
974
Janis Danisevskis66784c42021-01-27 08:40:25 -0800975 loop {
976 if let Err(e) = conn
977 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
978 .context("Failed to attach database persistent.")
979 {
980 if Self::is_locked_error(&e) {
981 std::thread::sleep(std::time::Duration::from_micros(500));
982 continue;
983 } else {
984 return Err(e);
985 }
986 }
987 break;
988 }
989 loop {
990 if let Err(e) = conn
991 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
992 .context("Failed to attach database perboot.")
993 {
994 if Self::is_locked_error(&e) {
995 std::thread::sleep(std::time::Duration::from_micros(500));
996 continue;
997 } else {
998 return Err(e);
999 }
1000 }
1001 break;
1002 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001003
1004 Ok(conn)
1005 }
1006
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001007 /// This function is intended to be used by the garbage collector.
1008 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1009 /// key blob that might need special handling by the garbage collector.
1010 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1011 /// need special handling and returns None.
1012 pub fn handle_next_superseded_blob(
1013 &mut self,
1014 blob_id_to_delete: Option<i64>,
1015 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001016 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001017 // Delete the given blob if one was given.
1018 if let Some(blob_id_to_delete) = blob_id_to_delete {
1019 tx.execute(
1020 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1021 params![blob_id_to_delete],
1022 )
1023 .context("Trying to delete blob metadata.")?;
1024 tx.execute(
1025 "DELETE FROM persistent.blobentry WHERE id = ?;",
1026 params![blob_id_to_delete],
1027 )
1028 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001029 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001030
1031 // Find another superseded keyblob load its metadata and return it.
1032 if let Some((blob_id, blob)) = tx
1033 .query_row(
1034 "SELECT id, blob FROM persistent.blobentry
1035 WHERE subcomponent_type = ?
1036 AND (
1037 id NOT IN (
1038 SELECT MAX(id) FROM persistent.blobentry
1039 WHERE subcomponent_type = ?
1040 GROUP BY keyentryid, subcomponent_type
1041 )
1042 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1043 );",
1044 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1045 |row| Ok((row.get(0)?, row.get(1)?)),
1046 )
1047 .optional()
1048 .context("Trying to query superseded blob.")?
1049 {
1050 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1051 .context("Trying to load blob metadata.")?;
1052 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1053 }
1054
1055 // We did not find any superseded key blob, so let's remove other superseded blob in
1056 // one transaction.
1057 tx.execute(
1058 "DELETE FROM persistent.blobentry
1059 WHERE NOT subcomponent_type = ?
1060 AND (
1061 id NOT IN (
1062 SELECT MAX(id) FROM persistent.blobentry
1063 WHERE NOT subcomponent_type = ?
1064 GROUP BY keyentryid, subcomponent_type
1065 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1066 );",
1067 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1068 )
1069 .context("Trying to purge superseded blobs.")?;
1070
1071 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001072 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001073 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001074 }
1075
1076 /// This maintenance function should be called only once before the database is used for the
1077 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1078 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1079 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1080 /// Keystore crashed at some point during key generation. Callers may want to log such
1081 /// occurrences.
1082 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1083 /// it to `KeyLifeCycle::Live` may have grants.
1084 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001085 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1086 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001087 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1088 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1089 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001090 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001091 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001092 })
1093 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001094 }
1095
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001096 /// Atomically loads a key entry and associated metadata or creates it using the
1097 /// callback create_new_key callback. The callback is called during a database
1098 /// transaction. This means that implementers should be mindful about using
1099 /// blocking operations such as IPC or grabbing mutexes.
1100 pub fn get_or_create_key_with<F>(
1101 &mut self,
1102 domain: Domain,
1103 namespace: i64,
1104 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001105 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001106 create_new_key: F,
1107 ) -> Result<(KeyIdGuard, KeyEntry)>
1108 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001109 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001110 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001111 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1112 let id = {
1113 let mut stmt = tx
1114 .prepare(
1115 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001116 WHERE
1117 key_type = ?
1118 AND domain = ?
1119 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001120 AND alias = ?
1121 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001122 )
1123 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1124 let mut rows = stmt
1125 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1126 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001127
Janis Danisevskis66784c42021-01-27 08:40:25 -08001128 db_utils::with_rows_extract_one(&mut rows, |row| {
1129 Ok(match row {
1130 Some(r) => r.get(0).context("Failed to unpack id.")?,
1131 None => None,
1132 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001133 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001134 .context("In get_or_create_key_with.")?
1135 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001136
Janis Danisevskis66784c42021-01-27 08:40:25 -08001137 let (id, entry) = match id {
1138 Some(id) => (
1139 id,
1140 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1141 .context("In get_or_create_key_with.")?,
1142 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001143
Janis Danisevskis66784c42021-01-27 08:40:25 -08001144 None => {
1145 let id = Self::insert_with_retry(|id| {
1146 tx.execute(
1147 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001148 (id, key_type, domain, namespace, alias, state, km_uuid)
1149 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001150 params![
1151 id,
1152 KeyType::Super,
1153 domain.0,
1154 namespace,
1155 alias,
1156 KeyLifeCycle::Live,
1157 km_uuid,
1158 ],
1159 )
1160 })
1161 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001162
Janis Danisevskis66784c42021-01-27 08:40:25 -08001163 let (blob, metadata) =
1164 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001165 Self::set_blob_internal(
1166 &tx,
1167 id,
1168 SubComponentType::KEY_BLOB,
1169 Some(&blob),
1170 Some(&metadata),
1171 )
1172 .context("In get_of_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001173 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001174 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001175 KeyEntry {
1176 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001177 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001178 pure_cert: false,
1179 ..Default::default()
1180 },
1181 )
1182 }
1183 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001184 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001185 })
1186 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001187 }
1188
Janis Danisevskis66784c42021-01-27 08:40:25 -08001189 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1190 /// waiting for the database file to become available. This makes it
1191 /// impossible to successfully recover from a locked database when the
1192 /// transaction holding the device busy is in the same process on a
1193 /// different connection. As a result the busy handler has to time out and
1194 /// fail in order to make progress.
1195 ///
1196 /// Instead, we set the busy handler to None (return immediately). And catch
1197 /// Busy and Locked errors (the latter occur on in memory databases with
1198 /// shared cache, e.g., the per-boot database.) and restart the transaction
1199 /// after a grace period of half a millisecond.
1200 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001201 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001202 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1203 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001204 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1205 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001206 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001207 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001208 loop {
1209 match self
1210 .conn
1211 .transaction_with_behavior(behavior)
1212 .context("In with_transaction.")
1213 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1214 .and_then(|(result, tx)| {
1215 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1216 Ok(result)
1217 }) {
1218 Ok(result) => break Ok(result),
1219 Err(e) => {
1220 if Self::is_locked_error(&e) {
1221 std::thread::sleep(std::time::Duration::from_micros(500));
1222 continue;
1223 } else {
1224 return Err(e).context("In with_transaction.");
1225 }
1226 }
1227 }
1228 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001229 .map(|(need_gc, result)| {
1230 if need_gc {
1231 if let Some(ref gc) = self.gc {
1232 gc.notify_gc();
1233 }
1234 }
1235 result
1236 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001237 }
1238
1239 fn is_locked_error(e: &anyhow::Error) -> bool {
1240 matches!(e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1241 Some(rusqlite::ffi::Error {
1242 code: rusqlite::ErrorCode::DatabaseBusy,
1243 ..
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001244 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001245 | Some(rusqlite::ffi::Error {
1246 code: rusqlite::ErrorCode::DatabaseLocked,
1247 ..
1248 }))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001249 }
1250
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001251 /// Creates a new key entry and allocates a new randomized id for the new key.
1252 /// The key id gets associated with a domain and namespace but not with an alias.
1253 /// To complete key generation `rebind_alias` should be called after all of the
1254 /// key artifacts, i.e., blobs and parameters have been associated with the new
1255 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1256 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001257 pub fn create_key_entry(
1258 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001259 domain: &Domain,
1260 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001261 km_uuid: &Uuid,
1262 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001263 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001264 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001265 })
1266 .context("In create_key_entry.")
1267 }
1268
1269 fn create_key_entry_internal(
1270 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001271 domain: &Domain,
1272 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001273 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001274 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001275 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001276 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001277 _ => {
1278 return Err(KsError::sys())
1279 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1280 }
1281 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001282 Ok(KEY_ID_LOCK.get(
1283 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001284 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001285 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001286 (id, key_type, domain, namespace, alias, state, km_uuid)
1287 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001288 params![
1289 id,
1290 KeyType::Client,
1291 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001292 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001293 KeyLifeCycle::Existing,
1294 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001295 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001296 )
1297 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001298 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001299 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001300 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001301
Max Bires2b2e6562020-09-22 11:22:36 -07001302 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1303 /// The key id gets associated with a domain and namespace later but not with an alias. The
1304 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1305 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1306 /// a key.
1307 pub fn create_attestation_key_entry(
1308 &mut self,
1309 maced_public_key: &[u8],
1310 raw_public_key: &[u8],
1311 private_key: &[u8],
1312 km_uuid: &Uuid,
1313 ) -> Result<()> {
1314 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1315 let key_id = KEY_ID_LOCK.get(
1316 Self::insert_with_retry(|id| {
1317 tx.execute(
1318 "INSERT into persistent.keyentry
1319 (id, key_type, domain, namespace, alias, state, km_uuid)
1320 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1321 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1322 )
1323 })
1324 .context("In create_key_entry")?,
1325 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001326 Self::set_blob_internal(
1327 &tx,
1328 key_id.0,
1329 SubComponentType::KEY_BLOB,
1330 Some(private_key),
1331 None,
1332 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001333 let mut metadata = KeyMetaData::new();
1334 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1335 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1336 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001337 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001338 })
1339 .context("In create_attestation_key_entry")
1340 }
1341
Janis Danisevskis377d1002021-01-27 19:07:48 -08001342 /// Set a new blob and associates it with the given key id. Each blob
1343 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001344 /// Each key can have one of each sub component type associated. If more
1345 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001346 /// will get garbage collected.
1347 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1348 /// removed by setting blob to None.
1349 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001350 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001351 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001352 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001353 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001354 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001355 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001356 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001357 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001358 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001359 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001360 }
1361
Janis Danisevskis377d1002021-01-27 19:07:48 -08001362 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001363 tx: &Transaction,
1364 key_id: i64,
1365 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001366 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001367 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001368 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001369 match (blob, sc_type) {
1370 (Some(blob), _) => {
1371 tx.execute(
1372 "INSERT INTO persistent.blobentry
1373 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1374 params![sc_type, key_id, blob],
1375 )
1376 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001377 if let Some(blob_metadata) = blob_metadata {
1378 let blob_id = tx
1379 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1380 row.get(0)
1381 })
1382 .context("In set_blob_internal: Failed to get new blob id.")?;
1383 blob_metadata
1384 .store_in_db(blob_id, tx)
1385 .context("In set_blob_internal: Trying to store blob metadata.")?;
1386 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001387 }
1388 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1389 tx.execute(
1390 "DELETE FROM persistent.blobentry
1391 WHERE subcomponent_type = ? AND keyentryid = ?;",
1392 params![sc_type, key_id],
1393 )
1394 .context("In set_blob_internal: Failed to delete blob.")?;
1395 }
1396 (None, _) => {
1397 return Err(KsError::sys())
1398 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1399 }
1400 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001401 Ok(())
1402 }
1403
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001404 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1405 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001406 #[cfg(test)]
1407 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001408 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001409 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001410 })
1411 .context("In insert_keyparameter.")
1412 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001413
Janis Danisevskis66784c42021-01-27 08:40:25 -08001414 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001415 tx: &Transaction,
1416 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001418 ) -> Result<()> {
1419 let mut stmt = tx
1420 .prepare(
1421 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1422 VALUES (?, ?, ?, ?);",
1423 )
1424 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1425
Janis Danisevskis66784c42021-01-27 08:40:25 -08001426 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001427 stmt.insert(params![
1428 key_id.0,
1429 p.get_tag().0,
1430 p.key_parameter_value(),
1431 p.security_level().0
1432 ])
1433 .with_context(|| {
1434 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1435 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001436 }
1437 Ok(())
1438 }
1439
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001440 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001441 #[cfg(test)]
1442 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001443 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001444 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001445 })
1446 .context("In insert_key_metadata.")
1447 }
1448
Max Bires2b2e6562020-09-22 11:22:36 -07001449 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1450 /// on the public key.
1451 pub fn store_signed_attestation_certificate_chain(
1452 &mut self,
1453 raw_public_key: &[u8],
1454 cert_chain: &[u8],
1455 expiration_date: i64,
1456 km_uuid: &Uuid,
1457 ) -> Result<()> {
1458 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1459 let mut stmt = tx
1460 .prepare(
1461 "SELECT keyentryid
1462 FROM persistent.keymetadata
1463 WHERE tag = ? AND data = ? AND keyentryid IN
1464 (SELECT id
1465 FROM persistent.keyentry
1466 WHERE
1467 alias IS NULL AND
1468 domain IS NULL AND
1469 namespace IS NULL AND
1470 key_type = ? AND
1471 km_uuid = ?);",
1472 )
1473 .context("Failed to store attestation certificate chain.")?;
1474 let mut rows = stmt
1475 .query(params![
1476 KeyMetaData::AttestationRawPubKey,
1477 raw_public_key,
1478 KeyType::Attestation,
1479 km_uuid
1480 ])
1481 .context("Failed to fetch keyid")?;
1482 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1483 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1484 .get(0)
1485 .context("Failed to unpack id.")
1486 })
1487 .context("Failed to get key_id.")?;
1488 let num_updated = tx
1489 .execute(
1490 "UPDATE persistent.keyentry
1491 SET alias = ?
1492 WHERE id = ?;",
1493 params!["signed", key_id],
1494 )
1495 .context("Failed to update alias.")?;
1496 if num_updated != 1 {
1497 return Err(KsError::sys()).context("Alias not updated for the key.");
1498 }
1499 let mut metadata = KeyMetaData::new();
1500 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1501 expiration_date,
1502 )));
1503 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001504 Self::set_blob_internal(
1505 &tx,
1506 key_id,
1507 SubComponentType::CERT_CHAIN,
1508 Some(cert_chain),
1509 None,
1510 )
1511 .context("Failed to insert cert chain")?;
1512 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001513 })
1514 .context("In store_signed_attestation_certificate_chain: ")
1515 }
1516
1517 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1518 /// currently have a key assigned to it.
1519 pub fn assign_attestation_key(
1520 &mut self,
1521 domain: Domain,
1522 namespace: i64,
1523 km_uuid: &Uuid,
1524 ) -> Result<()> {
1525 match domain {
1526 Domain::APP | Domain::SELINUX => {}
1527 _ => {
1528 return Err(KsError::sys()).context(format!(
1529 concat!(
1530 "In assign_attestation_key: Domain {:?} ",
1531 "must be either App or SELinux.",
1532 ),
1533 domain
1534 ));
1535 }
1536 }
1537 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1538 let result = tx
1539 .execute(
1540 "UPDATE persistent.keyentry
1541 SET domain=?1, namespace=?2
1542 WHERE
1543 id =
1544 (SELECT MIN(id)
1545 FROM persistent.keyentry
1546 WHERE ALIAS IS NOT NULL
1547 AND domain IS NULL
1548 AND key_type IS ?3
1549 AND state IS ?4
1550 AND km_uuid IS ?5)
1551 AND
1552 (SELECT COUNT(*)
1553 FROM persistent.keyentry
1554 WHERE domain=?1
1555 AND namespace=?2
1556 AND key_type IS ?3
1557 AND state IS ?4
1558 AND km_uuid IS ?5) = 0;",
1559 params![
1560 domain.0 as u32,
1561 namespace,
1562 KeyType::Attestation,
1563 KeyLifeCycle::Live,
1564 km_uuid,
1565 ],
1566 )
1567 .context("Failed to assign attestation key")?;
1568 if result != 1 {
1569 return Err(KsError::sys()).context(format!(
1570 "Expected to update a single entry but instead updated {}.",
1571 result
1572 ));
1573 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001574 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001575 })
1576 .context("In assign_attestation_key: ")
1577 }
1578
1579 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1580 /// provisioning server, or the maximum number available if there are not num_keys number of
1581 /// entries in the table.
1582 pub fn fetch_unsigned_attestation_keys(
1583 &mut self,
1584 num_keys: i32,
1585 km_uuid: &Uuid,
1586 ) -> Result<Vec<Vec<u8>>> {
1587 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1588 let mut stmt = tx
1589 .prepare(
1590 "SELECT data
1591 FROM persistent.keymetadata
1592 WHERE tag = ? AND keyentryid IN
1593 (SELECT id
1594 FROM persistent.keyentry
1595 WHERE
1596 alias IS NULL AND
1597 domain IS NULL AND
1598 namespace IS NULL AND
1599 key_type = ? AND
1600 km_uuid = ?
1601 LIMIT ?);",
1602 )
1603 .context("Failed to prepare statement")?;
1604 let rows = stmt
1605 .query_map(
1606 params![
1607 KeyMetaData::AttestationMacedPublicKey,
1608 KeyType::Attestation,
1609 km_uuid,
1610 num_keys
1611 ],
1612 |row| Ok(row.get(0)?),
1613 )?
1614 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1615 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001616 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001617 })
1618 .context("In fetch_unsigned_attestation_keys")
1619 }
1620
1621 /// Removes any keys that have expired as of the current time. Returns the number of keys
1622 /// marked unreferenced that are bound to be garbage collected.
1623 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
1624 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1625 let mut stmt = tx
1626 .prepare(
1627 "SELECT keyentryid, data
1628 FROM persistent.keymetadata
1629 WHERE tag = ? AND keyentryid IN
1630 (SELECT id
1631 FROM persistent.keyentry
1632 WHERE key_type = ?);",
1633 )
1634 .context("Failed to prepare query")?;
1635 let key_ids_to_check = stmt
1636 .query_map(
1637 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1638 |row| Ok((row.get(0)?, row.get(1)?)),
1639 )?
1640 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1641 .context("Failed to get date metadata")?;
1642 let curr_time = DateTime::from_millis_epoch(
1643 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1644 );
1645 let mut num_deleted = 0;
1646 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1647 if Self::mark_unreferenced(&tx, id)? {
1648 num_deleted += 1;
1649 }
1650 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001651 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001652 })
1653 .context("In delete_expired_attestation_keys: ")
1654 }
1655
1656 /// Counts the number of keys that will expire by the provided epoch date and the number of
1657 /// keys not currently assigned to a domain.
1658 pub fn get_attestation_pool_status(
1659 &mut self,
1660 date: i64,
1661 km_uuid: &Uuid,
1662 ) -> Result<AttestationPoolStatus> {
1663 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1664 let mut stmt = tx.prepare(
1665 "SELECT data
1666 FROM persistent.keymetadata
1667 WHERE tag = ? AND keyentryid IN
1668 (SELECT id
1669 FROM persistent.keyentry
1670 WHERE alias IS NOT NULL
1671 AND key_type = ?
1672 AND km_uuid = ?
1673 AND state = ?);",
1674 )?;
1675 let times = stmt
1676 .query_map(
1677 params![
1678 KeyMetaData::AttestationExpirationDate,
1679 KeyType::Attestation,
1680 km_uuid,
1681 KeyLifeCycle::Live
1682 ],
1683 |row| Ok(row.get(0)?),
1684 )?
1685 .collect::<rusqlite::Result<Vec<DateTime>>>()
1686 .context("Failed to execute metadata statement")?;
1687 let expiring =
1688 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1689 as i32;
1690 stmt = tx.prepare(
1691 "SELECT alias, domain
1692 FROM persistent.keyentry
1693 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1694 )?;
1695 let rows = stmt
1696 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1697 Ok((row.get(0)?, row.get(1)?))
1698 })?
1699 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1700 .context("Failed to execute keyentry statement")?;
1701 let mut unassigned = 0i32;
1702 let mut attested = 0i32;
1703 let total = rows.len() as i32;
1704 for (alias, domain) in rows {
1705 match (alias, domain) {
1706 (Some(_alias), None) => {
1707 attested += 1;
1708 unassigned += 1;
1709 }
1710 (Some(_alias), Some(_domain)) => {
1711 attested += 1;
1712 }
1713 _ => {}
1714 }
1715 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001716 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001717 })
1718 .context("In get_attestation_pool_status: ")
1719 }
1720
1721 /// Fetches the private key and corresponding certificate chain assigned to a
1722 /// domain/namespace pair. Will either return nothing if the domain/namespace is
1723 /// not assigned, or one CertificateChain.
1724 pub fn retrieve_attestation_key_and_cert_chain(
1725 &mut self,
1726 domain: Domain,
1727 namespace: i64,
1728 km_uuid: &Uuid,
1729 ) -> Result<Option<CertificateChain>> {
1730 match domain {
1731 Domain::APP | Domain::SELINUX => {}
1732 _ => {
1733 return Err(KsError::sys())
1734 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1735 }
1736 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001737 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1738 let mut stmt = tx.prepare(
1739 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07001740 FROM persistent.blobentry
1741 WHERE keyentryid IN
1742 (SELECT id
1743 FROM persistent.keyentry
1744 WHERE key_type = ?
1745 AND domain = ?
1746 AND namespace = ?
1747 AND state = ?
1748 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001749 )?;
1750 let rows = stmt
1751 .query_map(
1752 params![
1753 KeyType::Attestation,
1754 domain.0 as u32,
1755 namespace,
1756 KeyLifeCycle::Live,
1757 km_uuid
1758 ],
1759 |row| Ok((row.get(0)?, row.get(1)?)),
1760 )?
1761 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
1762 .context("In retrieve_attestation_key_and_cert_chain: query failed.")?;
1763 if rows.is_empty() {
1764 return Ok(None).no_gc();
1765 } else if rows.len() != 2 {
1766 return Err(KsError::sys()).context(format!(
1767 concat!(
Max Bires2b2e6562020-09-22 11:22:36 -07001768 "In retrieve_attestation_key_and_cert_chain: Expected to get a single attestation",
1769 "key chain but instead got {}."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001770 rows.len()
1771 ));
Max Bires2b2e6562020-09-22 11:22:36 -07001772 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001773 let mut km_blob: Vec<u8> = Vec::new();
1774 let mut cert_chain_blob: Vec<u8> = Vec::new();
1775 for row in rows {
1776 let sub_type: SubComponentType = row.0;
1777 match sub_type {
1778 SubComponentType::KEY_BLOB => {
1779 km_blob = row.1;
1780 }
1781 SubComponentType::CERT_CHAIN => {
1782 cert_chain_blob = row.1;
1783 }
1784 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
1785 }
1786 }
1787 Ok(Some(CertificateChain {
1788 private_key: ZVec::try_from(km_blob)?,
1789 cert_chain: ZVec::try_from(cert_chain_blob)?,
1790 }))
1791 .no_gc()
1792 })
Max Bires2b2e6562020-09-22 11:22:36 -07001793 }
1794
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001795 /// Updates the alias column of the given key id `newid` with the given alias,
1796 /// and atomically, removes the alias, domain, and namespace from another row
1797 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001798 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1799 /// collector.
1800 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001801 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001802 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001803 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001804 domain: &Domain,
1805 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001806 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001807 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001808 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001809 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001810 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001811 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001812 domain
1813 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001814 }
1815 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001816 let updated = tx
1817 .execute(
1818 "UPDATE persistent.keyentry
1819 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07001820 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001821 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
1822 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001823 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001824 let result = tx
1825 .execute(
1826 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001827 SET alias = ?, state = ?
1828 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
1829 params![
1830 alias,
1831 KeyLifeCycle::Live,
1832 newid.0,
1833 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001834 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001835 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001836 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001837 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001838 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001839 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001840 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001841 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001842 result
1843 ));
1844 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001845 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001846 }
1847
1848 /// Store a new key in a single transaction.
1849 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1850 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001851 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1852 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001853 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001854 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001855 key: &KeyDescriptor,
1856 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001857 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08001858 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001859 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001860 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001861 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001862 let (alias, domain, namespace) = match key {
1863 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1864 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1865 (alias, key.domain, nspace)
1866 }
1867 _ => {
1868 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1869 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
1870 }
1871 };
1872 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001873 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001874 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001875 let (blob, blob_metadata) = *blob_info;
1876 Self::set_blob_internal(
1877 tx,
1878 key_id.id(),
1879 SubComponentType::KEY_BLOB,
1880 Some(blob),
1881 Some(&blob_metadata),
1882 )
1883 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001884 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001885 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001886 .context("Trying to insert the certificate.")?;
1887 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001888 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001889 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001890 tx,
1891 key_id.id(),
1892 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001893 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001894 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001895 )
1896 .context("Trying to insert the certificate chain.")?;
1897 }
1898 Self::insert_keyparameter_internal(tx, &key_id, params)
1899 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001900 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001901 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001902 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001903 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001904 })
1905 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001906 }
1907
Janis Danisevskis377d1002021-01-27 19:07:48 -08001908 /// Store a new certificate
1909 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1910 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001911 pub fn store_new_certificate(
1912 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001913 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08001914 cert: &[u8],
1915 km_uuid: &Uuid,
1916 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001917 let (alias, domain, namespace) = match key {
1918 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1919 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1920 (alias, key.domain, nspace)
1921 }
1922 _ => {
1923 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
1924 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
1925 )
1926 }
1927 };
1928 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001929 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001930 .context("Trying to create new key entry.")?;
1931
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001932 Self::set_blob_internal(
1933 tx,
1934 key_id.id(),
1935 SubComponentType::CERT_CHAIN,
1936 Some(cert),
1937 None,
1938 )
1939 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001940
1941 let mut metadata = KeyMetaData::new();
1942 metadata.add(KeyMetaEntry::CreationDate(
1943 DateTime::now().context("Trying to make creation time.")?,
1944 ));
1945
1946 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1947
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001948 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001949 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001950 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001951 })
1952 .context("In store_new_certificate.")
1953 }
1954
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001955 // Helper function loading the key_id given the key descriptor
1956 // tuple comprising domain, namespace, and alias.
1957 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001958 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001959 let alias = key
1960 .alias
1961 .as_ref()
1962 .map_or_else(|| Err(KsError::sys()), Ok)
1963 .context("In load_key_entry_id: Alias must be specified.")?;
1964 let mut stmt = tx
1965 .prepare(
1966 "SELECT id FROM persistent.keyentry
1967 WHERE
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001968 key_type = ?
1969 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001970 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001971 AND alias = ?
1972 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001973 )
1974 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1975 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001976 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001977 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001978 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001979 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001980 .get(0)
1981 .context("Failed to unpack id.")
1982 })
1983 .context("In load_key_entry_id.")
1984 }
1985
1986 /// This helper function completes the access tuple of a key, which is required
1987 /// to perform access control. The strategy depends on the `domain` field in the
1988 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001989 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001990 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001991 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001992 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001993 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001994 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001995 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001996 /// `namespace`.
1997 /// In each case the information returned is sufficient to perform the access
1998 /// check and the key id can be used to load further key artifacts.
1999 fn load_access_tuple(
2000 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002001 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002002 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002003 caller_uid: u32,
2004 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2005 match key.domain {
2006 // Domain App or SELinux. In this case we load the key_id from
2007 // the keyentry database for further loading of key components.
2008 // We already have the full access tuple to perform access control.
2009 // The only distinction is that we use the caller_uid instead
2010 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002011 // Domain::APP.
2012 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002013 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002014 if access_key.domain == Domain::APP {
2015 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002016 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002017 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002018 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002019
2020 Ok((key_id, access_key, None))
2021 }
2022
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002023 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002024 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002025 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002026 let mut stmt = tx
2027 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002028 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002029 WHERE grantee = ? AND id = ?;",
2030 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002031 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002032 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002033 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002034 .context("Domain:Grant: query failed.")?;
2035 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002036 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002037 let r =
2038 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002039 Ok((
2040 r.get(0).context("Failed to unpack key_id.")?,
2041 r.get(1).context("Failed to unpack access_vector.")?,
2042 ))
2043 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002044 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002045 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002046 }
2047
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002048 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002049 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002050 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002051 let (domain, namespace): (Domain, i64) = {
2052 let mut stmt = tx
2053 .prepare(
2054 "SELECT domain, namespace FROM persistent.keyentry
2055 WHERE
2056 id = ?
2057 AND state = ?;",
2058 )
2059 .context("Domain::KEY_ID: prepare statement failed")?;
2060 let mut rows = stmt
2061 .query(params![key.nspace, KeyLifeCycle::Live])
2062 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002063 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002064 let r =
2065 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002066 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002067 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002068 r.get(1).context("Failed to unpack namespace.")?,
2069 ))
2070 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002071 .context("Domain::KEY_ID.")?
2072 };
2073
2074 // We may use a key by id after loading it by grant.
2075 // In this case we have to check if the caller has a grant for this particular
2076 // key. We can skip this if we already know that the caller is the owner.
2077 // But we cannot know this if domain is anything but App. E.g. in the case
2078 // of Domain::SELINUX we have to speculatively check for grants because we have to
2079 // consult the SEPolicy before we know if the caller is the owner.
2080 let access_vector: Option<KeyPermSet> =
2081 if domain != Domain::APP || namespace != caller_uid as i64 {
2082 let access_vector: Option<i32> = tx
2083 .query_row(
2084 "SELECT access_vector FROM persistent.grant
2085 WHERE grantee = ? AND keyentryid = ?;",
2086 params![caller_uid as i64, key.nspace],
2087 |row| row.get(0),
2088 )
2089 .optional()
2090 .context("Domain::KEY_ID: query grant failed.")?;
2091 access_vector.map(|p| p.into())
2092 } else {
2093 None
2094 };
2095
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002096 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002097 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002098 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002099 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002100
Janis Danisevskis45760022021-01-19 16:34:10 -08002101 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002102 }
2103 _ => Err(anyhow!(KsError::sys())),
2104 }
2105 }
2106
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002107 fn load_blob_components(
2108 key_id: i64,
2109 load_bits: KeyEntryLoadBits,
2110 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002111 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002112 let mut stmt = tx
2113 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002114 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002115 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2116 )
2117 .context("In load_blob_components: prepare statement failed.")?;
2118
2119 let mut rows =
2120 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2121
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002122 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002123 let mut cert_blob: Option<Vec<u8>> = None;
2124 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002125 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002126 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002127 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002128 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002129 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002130 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2131 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002132 key_blob = Some((
2133 row.get(0).context("Failed to extract key blob id.")?,
2134 row.get(2).context("Failed to extract key blob.")?,
2135 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002136 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002137 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002138 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002139 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002140 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002141 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002142 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002143 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002144 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002145 (SubComponentType::CERT, _, _)
2146 | (SubComponentType::CERT_CHAIN, _, _)
2147 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002148 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2149 }
2150 Ok(())
2151 })
2152 .context("In load_blob_components.")?;
2153
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002154 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2155 Ok(Some((
2156 blob,
2157 BlobMetaData::load_from_db(blob_id, tx)
2158 .context("In load_blob_components: Trying to load blob_metadata.")?,
2159 )))
2160 })?;
2161
2162 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002163 }
2164
2165 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2166 let mut stmt = tx
2167 .prepare(
2168 "SELECT tag, data, security_level from persistent.keyparameter
2169 WHERE keyentryid = ?;",
2170 )
2171 .context("In load_key_parameters: prepare statement failed.")?;
2172
2173 let mut parameters: Vec<KeyParameter> = Vec::new();
2174
2175 let mut rows =
2176 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002177 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002178 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2179 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002180 parameters.push(
2181 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2182 .context("Failed to read KeyParameter.")?,
2183 );
2184 Ok(())
2185 })
2186 .context("In load_key_parameters.")?;
2187
2188 Ok(parameters)
2189 }
2190
Qi Wub9433b52020-12-01 14:52:46 +08002191 /// Decrements the usage count of a limited use key. This function first checks whether the
2192 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2193 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2194 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002195 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002196 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2197 let limit: Option<i32> = tx
2198 .query_row(
2199 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2200 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2201 |row| row.get(0),
2202 )
2203 .optional()
2204 .context("Trying to load usage count")?;
2205
2206 let limit = limit
2207 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2208 .context("The Key no longer exists. Key is exhausted.")?;
2209
2210 tx.execute(
2211 "UPDATE persistent.keyparameter
2212 SET data = data - 1
2213 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2214 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2215 )
2216 .context("Failed to update key usage count.")?;
2217
2218 match limit {
2219 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002220 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002221 .context("Trying to mark limited use key for deletion."),
2222 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002223 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002224 }
2225 })
2226 .context("In check_and_update_key_usage_count.")
2227 }
2228
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002229 /// Load a key entry by the given key descriptor.
2230 /// It uses the `check_permission` callback to verify if the access is allowed
2231 /// given the key access tuple read from the database using `load_access_tuple`.
2232 /// With `load_bits` the caller may specify which blobs shall be loaded from
2233 /// the blob database.
2234 pub fn load_key_entry(
2235 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002236 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002237 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002238 load_bits: KeyEntryLoadBits,
2239 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002240 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2241 ) -> Result<(KeyIdGuard, KeyEntry)> {
2242 loop {
2243 match self.load_key_entry_internal(
2244 key,
2245 key_type,
2246 load_bits,
2247 caller_uid,
2248 &check_permission,
2249 ) {
2250 Ok(result) => break Ok(result),
2251 Err(e) => {
2252 if Self::is_locked_error(&e) {
2253 std::thread::sleep(std::time::Duration::from_micros(500));
2254 continue;
2255 } else {
2256 return Err(e).context("In load_key_entry.");
2257 }
2258 }
2259 }
2260 }
2261 }
2262
2263 fn load_key_entry_internal(
2264 &mut self,
2265 key: &KeyDescriptor,
2266 key_type: KeyType,
2267 load_bits: KeyEntryLoadBits,
2268 caller_uid: u32,
2269 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002270 ) -> Result<(KeyIdGuard, KeyEntry)> {
2271 // KEY ID LOCK 1/2
2272 // If we got a key descriptor with a key id we can get the lock right away.
2273 // Otherwise we have to defer it until we know the key id.
2274 let key_id_guard = match key.domain {
2275 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2276 _ => None,
2277 };
2278
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002279 let tx = self
2280 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002281 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002282 .context("In load_key_entry: Failed to initialize transaction.")?;
2283
2284 // Load the key_id and complete the access control tuple.
2285 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002286 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2287 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002288
2289 // Perform access control. It is vital that we return here if the permission is denied.
2290 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002291 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002292
Janis Danisevskisaec14592020-11-12 09:41:49 -08002293 // KEY ID LOCK 2/2
2294 // If we did not get a key id lock by now, it was because we got a key descriptor
2295 // without a key id. At this point we got the key id, so we can try and get a lock.
2296 // However, we cannot block here, because we are in the middle of the transaction.
2297 // So first we try to get the lock non blocking. If that fails, we roll back the
2298 // transaction and block until we get the lock. After we successfully got the lock,
2299 // we start a new transaction and load the access tuple again.
2300 //
2301 // We don't need to perform access control again, because we already established
2302 // that the caller had access to the given key. But we need to make sure that the
2303 // key id still exists. So we have to load the key entry by key id this time.
2304 let (key_id_guard, tx) = match key_id_guard {
2305 None => match KEY_ID_LOCK.try_get(key_id) {
2306 None => {
2307 // Roll back the transaction.
2308 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002309
Janis Danisevskisaec14592020-11-12 09:41:49 -08002310 // Block until we have a key id lock.
2311 let key_id_guard = KEY_ID_LOCK.get(key_id);
2312
2313 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002314 let tx = self
2315 .conn
2316 .unchecked_transaction()
2317 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002318
2319 Self::load_access_tuple(
2320 &tx,
2321 // This time we have to load the key by the retrieved key id, because the
2322 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002323 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002324 domain: Domain::KEY_ID,
2325 nspace: key_id,
2326 ..Default::default()
2327 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002328 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002329 caller_uid,
2330 )
2331 .context("In load_key_entry. (deferred key lock)")?;
2332 (key_id_guard, tx)
2333 }
2334 Some(l) => (l, tx),
2335 },
2336 Some(key_id_guard) => (key_id_guard, tx),
2337 };
2338
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002339 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2340 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002341
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002342 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2343
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002344 Ok((key_id_guard, key_entry))
2345 }
2346
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002347 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002348 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002349 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2350 .context("Trying to delete keyentry.")?;
2351 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2352 .context("Trying to delete keymetadata.")?;
2353 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2354 .context("Trying to delete keyparameters.")?;
2355 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2356 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002357 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002358 }
2359
2360 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002361 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002362 pub fn unbind_key(
2363 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002364 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002365 key_type: KeyType,
2366 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002367 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002368 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002369 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2370 let (key_id, access_key_descriptor, access_vector) =
2371 Self::load_access_tuple(tx, key, key_type, caller_uid)
2372 .context("Trying to get access tuple.")?;
2373
2374 // Perform access control. It is vital that we return here if the permission is denied.
2375 // So do not touch that '?' at the end.
2376 check_permission(&access_key_descriptor, access_vector)
2377 .context("While checking permission.")?;
2378
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002379 Self::mark_unreferenced(tx, key_id)
2380 .map(|need_gc| (need_gc, ()))
2381 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002382 })
2383 .context("In unbind_key.")
2384 }
2385
Max Bires8e93d2b2021-01-14 13:17:59 -08002386 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2387 tx.query_row(
2388 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2389 params![key_id],
2390 |row| row.get(0),
2391 )
2392 .context("In get_key_km_uuid.")
2393 }
2394
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002395 fn load_key_components(
2396 tx: &Transaction,
2397 load_bits: KeyEntryLoadBits,
2398 key_id: i64,
2399 ) -> Result<KeyEntry> {
2400 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2401
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002402 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002403 Self::load_blob_components(key_id, load_bits, &tx)
2404 .context("In load_key_components.")?;
2405
Max Bires8e93d2b2021-01-14 13:17:59 -08002406 let parameters = Self::load_key_parameters(key_id, &tx)
2407 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002408
Max Bires8e93d2b2021-01-14 13:17:59 -08002409 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2410 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002411
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002412 Ok(KeyEntry {
2413 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002414 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002415 cert: cert_blob,
2416 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002417 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002418 parameters,
2419 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002420 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002421 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002422 }
2423
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002424 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2425 /// The key descriptors will have the domain, nspace, and alias field set.
2426 /// Domain must be APP or SELINUX, the caller must make sure of that.
2427 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002428 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2429 let mut stmt = tx
2430 .prepare(
2431 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002432 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002433 )
2434 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002435
Janis Danisevskis66784c42021-01-27 08:40:25 -08002436 let mut rows = stmt
2437 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2438 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002439
Janis Danisevskis66784c42021-01-27 08:40:25 -08002440 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2441 db_utils::with_rows_extract_all(&mut rows, |row| {
2442 descriptors.push(KeyDescriptor {
2443 domain,
2444 nspace: namespace,
2445 alias: Some(row.get(0).context("Trying to extract alias.")?),
2446 blob: None,
2447 });
2448 Ok(())
2449 })
2450 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002451 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002452 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002453 }
2454
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002455 /// Adds a grant to the grant table.
2456 /// Like `load_key_entry` this function loads the access tuple before
2457 /// it uses the callback for a permission check. Upon success,
2458 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2459 /// grant table. The new row will have a randomized id, which is used as
2460 /// grant id in the namespace field of the resulting KeyDescriptor.
2461 pub fn grant(
2462 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002463 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002464 caller_uid: u32,
2465 grantee_uid: u32,
2466 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002467 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002468 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002469 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2470 // Load the key_id and complete the access control tuple.
2471 // We ignore the access vector here because grants cannot be granted.
2472 // The access vector returned here expresses the permissions the
2473 // grantee has if key.domain == Domain::GRANT. But this vector
2474 // cannot include the grant permission by design, so there is no way the
2475 // subsequent permission check can pass.
2476 // We could check key.domain == Domain::GRANT and fail early.
2477 // But even if we load the access tuple by grant here, the permission
2478 // check denies the attempt to create a grant by grant descriptor.
2479 let (key_id, access_key_descriptor, _) =
2480 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2481 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002482
Janis Danisevskis66784c42021-01-27 08:40:25 -08002483 // Perform access control. It is vital that we return here if the permission
2484 // was denied. So do not touch that '?' at the end of the line.
2485 // This permission check checks if the caller has the grant permission
2486 // for the given key and in addition to all of the permissions
2487 // expressed in `access_vector`.
2488 check_permission(&access_key_descriptor, &access_vector)
2489 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002490
Janis Danisevskis66784c42021-01-27 08:40:25 -08002491 let grant_id = if let Some(grant_id) = tx
2492 .query_row(
2493 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002494 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002495 params![key_id, grantee_uid],
2496 |row| row.get(0),
2497 )
2498 .optional()
2499 .context("In grant: Failed get optional existing grant id.")?
2500 {
2501 tx.execute(
2502 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002503 SET access_vector = ?
2504 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002505 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002506 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002507 .context("In grant: Failed to update existing grant.")?;
2508 grant_id
2509 } else {
2510 Self::insert_with_retry(|id| {
2511 tx.execute(
2512 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2513 VALUES (?, ?, ?, ?);",
2514 params![id, grantee_uid, key_id, i32::from(access_vector)],
2515 )
2516 })
2517 .context("In grant")?
2518 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002519
Janis Danisevskis66784c42021-01-27 08:40:25 -08002520 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002521 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002522 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002523 }
2524
2525 /// This function checks permissions like `grant` and `load_key_entry`
2526 /// before removing a grant from the grant table.
2527 pub fn ungrant(
2528 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002529 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002530 caller_uid: u32,
2531 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002532 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002533 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002534 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2535 // Load the key_id and complete the access control tuple.
2536 // We ignore the access vector here because grants cannot be granted.
2537 let (key_id, access_key_descriptor, _) =
2538 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2539 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002540
Janis Danisevskis66784c42021-01-27 08:40:25 -08002541 // Perform access control. We must return here if the permission
2542 // was denied. So do not touch the '?' at the end of this line.
2543 check_permission(&access_key_descriptor)
2544 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002545
Janis Danisevskis66784c42021-01-27 08:40:25 -08002546 tx.execute(
2547 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002548 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002549 params![key_id, grantee_uid],
2550 )
2551 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002552
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002553 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002554 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002555 }
2556
Joel Galenson845f74b2020-09-09 14:11:55 -07002557 // Generates a random id and passes it to the given function, which will
2558 // try to insert it into a database. If that insertion fails, retry;
2559 // otherwise return the id.
2560 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2561 loop {
2562 let newid: i64 = random();
2563 match inserter(newid) {
2564 // If the id already existed, try again.
2565 Err(rusqlite::Error::SqliteFailure(
2566 libsqlite3_sys::Error {
2567 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2568 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2569 },
2570 _,
2571 )) => (),
2572 Err(e) => {
2573 return Err(e).context("In insert_with_retry: failed to insert into database.")
2574 }
2575 _ => return Ok(newid),
2576 }
2577 }
2578 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002579
2580 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
2581 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002582 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2583 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002584 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
2585 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
2586 params![
2587 auth_token.challenge,
2588 auth_token.userId,
2589 auth_token.authenticatorId,
2590 auth_token.authenticatorType.0 as i32,
2591 auth_token.timestamp.milliSeconds as i64,
2592 auth_token.mac,
2593 MonotonicRawTime::now(),
2594 ],
2595 )
2596 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002597 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002598 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002599 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002600
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002601 /// Find the newest auth token matching the given predicate.
2602 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002603 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002604 p: F,
2605 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
2606 where
2607 F: Fn(&AuthTokenEntry) -> bool,
2608 {
2609 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2610 let mut stmt = tx
2611 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
2612 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002613
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002614 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002615
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002616 while let Some(row) = rows.next().context("Failed to get next row.")? {
2617 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002618 HardwareAuthToken {
2619 challenge: row.get(1)?,
2620 userId: row.get(2)?,
2621 authenticatorId: row.get(3)?,
2622 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2623 timestamp: Timestamp { milliSeconds: row.get(5)? },
2624 mac: row.get(6)?,
2625 },
2626 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002627 );
2628 if p(&entry) {
2629 return Ok(Some((
2630 entry,
2631 Self::get_last_off_body(tx)
2632 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002633 )))
2634 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002635 }
2636 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002637 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002638 })
2639 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002640 }
2641
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002642 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08002643 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2644 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2645 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002646 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
2647 params!["last_off_body", last_off_body],
2648 )
2649 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002650 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002651 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002652 }
2653
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002654 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08002655 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2656 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2657 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002658 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
2659 params![last_off_body, "last_off_body"],
2660 )
2661 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002662 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002663 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002664 }
2665
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002666 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002667 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002668 tx.query_row(
2669 "SELECT value from perboot.metadata WHERE key = ?;",
2670 params!["last_off_body"],
2671 |row| Ok(row.get(0)?),
2672 )
2673 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002674 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002675}
2676
2677#[cfg(test)]
2678mod tests {
2679
2680 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002681 use crate::key_parameter::{
2682 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2683 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2684 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002685 use crate::key_perm_set;
2686 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002687 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002688 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2689 HardwareAuthToken::HardwareAuthToken,
2690 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002691 };
2692 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002693 Timestamp::Timestamp,
2694 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002695 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002696 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07002697 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002698 use std::sync::atomic::{AtomicU8, Ordering};
2699 use std::sync::Arc;
2700 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002701 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08002702 #[cfg(disabled)]
2703 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002704
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002705 fn new_test_db() -> Result<KeystoreDB> {
2706 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
2707
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002708 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002709 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002710 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002711 })?;
2712 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002713 }
2714
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002715 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
2716 where
2717 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
2718 {
2719 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
2720 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db));
2721
2722 KeystoreDB::new(path, Some(gc))
2723 }
2724
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002725 fn rebind_alias(
2726 db: &mut KeystoreDB,
2727 newid: &KeyIdGuard,
2728 alias: &str,
2729 domain: Domain,
2730 namespace: i64,
2731 ) -> Result<bool> {
2732 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002733 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002734 })
2735 .context("In rebind_alias.")
2736 }
2737
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002738 #[test]
2739 fn datetime() -> Result<()> {
2740 let conn = Connection::open_in_memory()?;
2741 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
2742 let now = SystemTime::now();
2743 let duration = Duration::from_secs(1000);
2744 let then = now.checked_sub(duration).unwrap();
2745 let soon = now.checked_add(duration).unwrap();
2746 conn.execute(
2747 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2748 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2749 )?;
2750 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
2751 let mut rows = stmt.query(NO_PARAMS)?;
2752 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2753 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2754 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2755 assert!(rows.next()?.is_none());
2756 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2757 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2758 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2759 Ok(())
2760 }
2761
Joel Galenson0891bc12020-07-20 10:37:03 -07002762 // Ensure that we're using the "injected" random function, not the real one.
2763 #[test]
2764 fn test_mocked_random() {
2765 let rand1 = random();
2766 let rand2 = random();
2767 let rand3 = random();
2768 if rand1 == rand2 {
2769 assert_eq!(rand2 + 1, rand3);
2770 } else {
2771 assert_eq!(rand1 + 1, rand2);
2772 assert_eq!(rand2, rand3);
2773 }
2774 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002775
Joel Galenson26f4d012020-07-17 14:57:21 -07002776 // Test that we have the correct tables.
2777 #[test]
2778 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002779 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002780 let tables = db
2781 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002782 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002783 .query_map(params![], |row| row.get(0))?
2784 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002785 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002786 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002787 assert_eq!(tables[1], "blobmetadata");
2788 assert_eq!(tables[2], "grant");
2789 assert_eq!(tables[3], "keyentry");
2790 assert_eq!(tables[4], "keymetadata");
2791 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002792 let tables = db
2793 .conn
2794 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
2795 .query_map(params![], |row| row.get(0))?
2796 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002797
2798 assert_eq!(tables.len(), 2);
2799 assert_eq!(tables[0], "authtoken");
2800 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07002801 Ok(())
2802 }
2803
2804 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002805 fn test_auth_token_table_invariant() -> Result<()> {
2806 let mut db = new_test_db()?;
2807 let auth_token1 = HardwareAuthToken {
2808 challenge: i64::MAX,
2809 userId: 200,
2810 authenticatorId: 200,
2811 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2812 timestamp: Timestamp { milliSeconds: 500 },
2813 mac: String::from("mac").into_bytes(),
2814 };
2815 db.insert_auth_token(&auth_token1)?;
2816 let auth_tokens_returned = get_auth_tokens(&mut db)?;
2817 assert_eq!(auth_tokens_returned.len(), 1);
2818
2819 // insert another auth token with the same values for the columns in the UNIQUE constraint
2820 // of the auth token table and different value for timestamp
2821 let auth_token2 = HardwareAuthToken {
2822 challenge: i64::MAX,
2823 userId: 200,
2824 authenticatorId: 200,
2825 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2826 timestamp: Timestamp { milliSeconds: 600 },
2827 mac: String::from("mac").into_bytes(),
2828 };
2829
2830 db.insert_auth_token(&auth_token2)?;
2831 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
2832 assert_eq!(auth_tokens_returned.len(), 1);
2833
2834 if let Some(auth_token) = auth_tokens_returned.pop() {
2835 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
2836 }
2837
2838 // insert another auth token with the different values for the columns in the UNIQUE
2839 // constraint of the auth token table
2840 let auth_token3 = HardwareAuthToken {
2841 challenge: i64::MAX,
2842 userId: 201,
2843 authenticatorId: 200,
2844 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2845 timestamp: Timestamp { milliSeconds: 600 },
2846 mac: String::from("mac").into_bytes(),
2847 };
2848
2849 db.insert_auth_token(&auth_token3)?;
2850 let auth_tokens_returned = get_auth_tokens(&mut db)?;
2851 assert_eq!(auth_tokens_returned.len(), 2);
2852
2853 Ok(())
2854 }
2855
2856 // utility function for test_auth_token_table_invariant()
2857 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
2858 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
2859
2860 let auth_token_entries: Vec<AuthTokenEntry> = stmt
2861 .query_map(NO_PARAMS, |row| {
2862 Ok(AuthTokenEntry::new(
2863 HardwareAuthToken {
2864 challenge: row.get(1)?,
2865 userId: row.get(2)?,
2866 authenticatorId: row.get(3)?,
2867 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2868 timestamp: Timestamp { milliSeconds: row.get(5)? },
2869 mac: row.get(6)?,
2870 },
2871 row.get(7)?,
2872 ))
2873 })?
2874 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
2875 Ok(auth_token_entries)
2876 }
2877
2878 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07002879 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002880 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002881 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07002882
Janis Danisevskis66784c42021-01-27 08:40:25 -08002883 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07002884 let entries = get_keyentry(&db)?;
2885 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002886
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002887 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07002888
2889 let entries_new = get_keyentry(&db)?;
2890 assert_eq!(entries, entries_new);
2891 Ok(())
2892 }
2893
2894 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07002895 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08002896 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
2897 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07002898 }
2899
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002900 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07002901
Janis Danisevskis66784c42021-01-27 08:40:25 -08002902 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
2903 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07002904
2905 let entries = get_keyentry(&db)?;
2906 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08002907 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
2908 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07002909
2910 // Test that we must pass in a valid Domain.
2911 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08002912 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002913 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002914 );
2915 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08002916 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002917 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002918 );
2919 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08002920 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002921 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07002922 );
2923
2924 Ok(())
2925 }
2926
Joel Galenson33c04ad2020-08-03 11:04:38 -07002927 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07002928 fn test_add_unsigned_key() -> Result<()> {
2929 let mut db = new_test_db()?;
2930 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
2931 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
2932 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
2933 db.create_attestation_key_entry(
2934 &public_key,
2935 &raw_public_key,
2936 &private_key,
2937 &KEYSTORE_UUID,
2938 )?;
2939 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
2940 assert_eq!(keys.len(), 1);
2941 assert_eq!(keys[0], public_key);
2942 Ok(())
2943 }
2944
2945 #[test]
2946 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
2947 let mut db = new_test_db()?;
2948 let expiration_date: i64 = 20;
2949 let namespace: i64 = 30;
2950 let base_byte: u8 = 1;
2951 let loaded_values =
2952 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
2953 let chain =
2954 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
2955 assert_eq!(true, chain.is_some());
2956 let cert_chain = chain.unwrap();
2957 assert_eq!(cert_chain.private_key.to_vec(), loaded_values[2]);
2958 assert_eq!(cert_chain.cert_chain.to_vec(), loaded_values[1]);
2959 Ok(())
2960 }
2961
2962 #[test]
2963 fn test_get_attestation_pool_status() -> Result<()> {
2964 let mut db = new_test_db()?;
2965 let namespace: i64 = 30;
2966 load_attestation_key_pool(
2967 &mut db, 10, /* expiration */
2968 namespace, 0x01, /* base_byte */
2969 )?;
2970 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
2971 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
2972 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
2973 assert_eq!(status.expiring, 0);
2974 assert_eq!(status.attested, 3);
2975 assert_eq!(status.unassigned, 0);
2976 assert_eq!(status.total, 3);
2977 assert_eq!(
2978 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
2979 1
2980 );
2981 assert_eq!(
2982 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
2983 2
2984 );
2985 assert_eq!(
2986 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
2987 3
2988 );
2989 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
2990 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
2991 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
2992 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
2993 db.create_attestation_key_entry(
2994 &public_key,
2995 &raw_public_key,
2996 &private_key,
2997 &KEYSTORE_UUID,
2998 )?;
2999 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3000 assert_eq!(status.attested, 3);
3001 assert_eq!(status.unassigned, 0);
3002 assert_eq!(status.total, 4);
3003 db.store_signed_attestation_certificate_chain(
3004 &raw_public_key,
3005 &cert_chain,
3006 20,
3007 &KEYSTORE_UUID,
3008 )?;
3009 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3010 assert_eq!(status.attested, 4);
3011 assert_eq!(status.unassigned, 1);
3012 assert_eq!(status.total, 4);
3013 Ok(())
3014 }
3015
3016 #[test]
3017 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003018 let temp_dir =
3019 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3020 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003021 let expiration_date: i64 =
3022 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3023 let namespace: i64 = 30;
3024 let namespace_del1: i64 = 45;
3025 let namespace_del2: i64 = 60;
3026 let entry_values = load_attestation_key_pool(
3027 &mut db,
3028 expiration_date,
3029 namespace,
3030 0x01, /* base_byte */
3031 )?;
3032 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3033 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003034
3035 let blob_entry_row_count: u32 = db
3036 .conn
3037 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3038 .expect("Failed to get blob entry row count.");
3039 // We expect 6 rows here because there are two blobs per attestation key, i.e.,
3040 // One key and one certificate.
3041 assert_eq!(blob_entry_row_count, 6);
3042
Max Bires2b2e6562020-09-22 11:22:36 -07003043 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3044
3045 let mut cert_chain =
3046 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003047 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003048 let value = cert_chain.unwrap();
3049 assert_eq!(entry_values[1], value.cert_chain.to_vec());
3050 assert_eq!(entry_values[2], value.private_key.to_vec());
3051
3052 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3053 Domain::APP,
3054 namespace_del1,
3055 &KEYSTORE_UUID,
3056 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003057 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003058 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3059 Domain::APP,
3060 namespace_del2,
3061 &KEYSTORE_UUID,
3062 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003063 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003064
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003065 // Give the garbage collector half a second to catch up.
3066 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003067
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003068 let blob_entry_row_count: u32 = db
3069 .conn
3070 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3071 .expect("Failed to get blob entry row count.");
3072 // There shound be 2 blob entries left, because we deleted two of the attestation
3073 // key entries with two blobs each.
3074 assert_eq!(blob_entry_row_count, 2);
Max Bires2b2e6562020-09-22 11:22:36 -07003075
Max Bires2b2e6562020-09-22 11:22:36 -07003076 Ok(())
3077 }
3078
3079 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003080 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003081 fn extractor(
3082 ke: &KeyEntryRow,
3083 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3084 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003085 }
3086
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003087 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003088 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3089 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003090 let entries = get_keyentry(&db)?;
3091 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003092 assert_eq!(
3093 extractor(&entries[0]),
3094 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3095 );
3096 assert_eq!(
3097 extractor(&entries[1]),
3098 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3099 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003100
3101 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003102 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003103 let entries = get_keyentry(&db)?;
3104 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003105 assert_eq!(
3106 extractor(&entries[0]),
3107 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3108 );
3109 assert_eq!(
3110 extractor(&entries[1]),
3111 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3112 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003113
3114 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003115 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003116 let entries = get_keyentry(&db)?;
3117 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003118 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3119 assert_eq!(
3120 extractor(&entries[1]),
3121 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3122 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003123
3124 // Test that we must pass in a valid Domain.
3125 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003126 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003127 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003128 );
3129 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003130 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003131 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003132 );
3133 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003134 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003135 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003136 );
3137
3138 // Test that we correctly handle setting an alias for something that does not exist.
3139 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003140 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003141 "Expected to update a single entry but instead updated 0",
3142 );
3143 // Test that we correctly abort the transaction in this case.
3144 let entries = get_keyentry(&db)?;
3145 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003146 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3147 assert_eq!(
3148 extractor(&entries[1]),
3149 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3150 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003151
3152 Ok(())
3153 }
3154
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003155 #[test]
3156 fn test_grant_ungrant() -> Result<()> {
3157 const CALLER_UID: u32 = 15;
3158 const GRANTEE_UID: u32 = 12;
3159 const SELINUX_NAMESPACE: i64 = 7;
3160
3161 let mut db = new_test_db()?;
3162 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003163 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3164 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3165 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003166 )?;
3167 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003168 domain: super::Domain::APP,
3169 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003170 alias: Some("key".to_string()),
3171 blob: None,
3172 };
3173 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3174 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3175
3176 // Reset totally predictable random number generator in case we
3177 // are not the first test running on this thread.
3178 reset_random();
3179 let next_random = 0i64;
3180
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003181 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003182 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003183 assert_eq!(*a, PVEC1);
3184 assert_eq!(
3185 *k,
3186 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003187 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003188 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003189 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003190 alias: Some("key".to_string()),
3191 blob: None,
3192 }
3193 );
3194 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003195 })
3196 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003197
3198 assert_eq!(
3199 app_granted_key,
3200 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003201 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003202 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003203 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003204 alias: None,
3205 blob: None,
3206 }
3207 );
3208
3209 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003210 domain: super::Domain::SELINUX,
3211 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003212 alias: Some("yek".to_string()),
3213 blob: None,
3214 };
3215
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003216 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003217 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003218 assert_eq!(*a, PVEC1);
3219 assert_eq!(
3220 *k,
3221 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003222 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003223 // namespace must be the supplied SELinux
3224 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003225 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003226 alias: Some("yek".to_string()),
3227 blob: None,
3228 }
3229 );
3230 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003231 })
3232 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003233
3234 assert_eq!(
3235 selinux_granted_key,
3236 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003237 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003238 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003239 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003240 alias: None,
3241 blob: None,
3242 }
3243 );
3244
3245 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003246 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003247 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003248 assert_eq!(*a, PVEC2);
3249 assert_eq!(
3250 *k,
3251 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003252 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003253 // namespace must be the supplied SELinux
3254 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003255 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003256 alias: Some("yek".to_string()),
3257 blob: None,
3258 }
3259 );
3260 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003261 })
3262 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003263
3264 assert_eq!(
3265 selinux_granted_key,
3266 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003267 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003268 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003269 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003270 alias: None,
3271 blob: None,
3272 }
3273 );
3274
3275 {
3276 // Limiting scope of stmt, because it borrows db.
3277 let mut stmt = db
3278 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003279 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003280 let mut rows =
3281 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3282 Ok((
3283 row.get(0)?,
3284 row.get(1)?,
3285 row.get(2)?,
3286 KeyPermSet::from(row.get::<_, i32>(3)?),
3287 ))
3288 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003289
3290 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003291 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003292 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003293 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003294 assert!(rows.next().is_none());
3295 }
3296
3297 debug_dump_keyentry_table(&mut db)?;
3298 println!("app_key {:?}", app_key);
3299 println!("selinux_key {:?}", selinux_key);
3300
Janis Danisevskis66784c42021-01-27 08:40:25 -08003301 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3302 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003303
3304 Ok(())
3305 }
3306
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003307 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003308 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3309 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3310
3311 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003312 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003313 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003314 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003315 let mut blob_metadata = BlobMetaData::new();
3316 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3317 db.set_blob(
3318 &key_id,
3319 SubComponentType::KEY_BLOB,
3320 Some(TEST_KEY_BLOB),
3321 Some(&blob_metadata),
3322 )?;
3323 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3324 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003325 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003326
3327 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003328 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003329 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003330 )?;
3331 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003332 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3333 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003334 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003335 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003336 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003337 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003338 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003339 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003340 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003341
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003342 drop(rows);
3343 drop(stmt);
3344
3345 assert_eq!(
3346 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3347 BlobMetaData::load_from_db(id, tx).no_gc()
3348 })
3349 .expect("Should find blob metadata."),
3350 blob_metadata
3351 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003352 Ok(())
3353 }
3354
3355 static TEST_ALIAS: &str = "my super duper key";
3356
3357 #[test]
3358 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3359 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003360 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003361 .context("test_insert_and_load_full_keyentry_domain_app")?
3362 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003363 let (_key_guard, key_entry) = db
3364 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003365 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003366 domain: Domain::APP,
3367 nspace: 0,
3368 alias: Some(TEST_ALIAS.to_string()),
3369 blob: None,
3370 },
3371 KeyType::Client,
3372 KeyEntryLoadBits::BOTH,
3373 1,
3374 |_k, _av| Ok(()),
3375 )
3376 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003377 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003378
3379 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003380 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003381 domain: Domain::APP,
3382 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003383 alias: Some(TEST_ALIAS.to_string()),
3384 blob: None,
3385 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003386 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003387 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003388 |_, _| Ok(()),
3389 )
3390 .unwrap();
3391
3392 assert_eq!(
3393 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3394 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003395 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003396 domain: Domain::APP,
3397 nspace: 0,
3398 alias: Some(TEST_ALIAS.to_string()),
3399 blob: None,
3400 },
3401 KeyType::Client,
3402 KeyEntryLoadBits::NONE,
3403 1,
3404 |_k, _av| Ok(()),
3405 )
3406 .unwrap_err()
3407 .root_cause()
3408 .downcast_ref::<KsError>()
3409 );
3410
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003411 Ok(())
3412 }
3413
3414 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003415 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3416 let mut db = new_test_db()?;
3417
3418 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003419 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003420 domain: Domain::APP,
3421 nspace: 1,
3422 alias: Some(TEST_ALIAS.to_string()),
3423 blob: None,
3424 },
3425 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003426 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003427 )
3428 .expect("Trying to insert cert.");
3429
3430 let (_key_guard, mut key_entry) = db
3431 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003432 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003433 domain: Domain::APP,
3434 nspace: 1,
3435 alias: Some(TEST_ALIAS.to_string()),
3436 blob: None,
3437 },
3438 KeyType::Client,
3439 KeyEntryLoadBits::PUBLIC,
3440 1,
3441 |_k, _av| Ok(()),
3442 )
3443 .expect("Trying to read certificate entry.");
3444
3445 assert!(key_entry.pure_cert());
3446 assert!(key_entry.cert().is_none());
3447 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3448
3449 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003450 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003451 domain: Domain::APP,
3452 nspace: 1,
3453 alias: Some(TEST_ALIAS.to_string()),
3454 blob: None,
3455 },
3456 KeyType::Client,
3457 1,
3458 |_, _| Ok(()),
3459 )
3460 .unwrap();
3461
3462 assert_eq!(
3463 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3464 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003465 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003466 domain: Domain::APP,
3467 nspace: 1,
3468 alias: Some(TEST_ALIAS.to_string()),
3469 blob: None,
3470 },
3471 KeyType::Client,
3472 KeyEntryLoadBits::NONE,
3473 1,
3474 |_k, _av| Ok(()),
3475 )
3476 .unwrap_err()
3477 .root_cause()
3478 .downcast_ref::<KsError>()
3479 );
3480
3481 Ok(())
3482 }
3483
3484 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003485 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3486 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003487 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003488 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3489 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003490 let (_key_guard, key_entry) = db
3491 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003492 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003493 domain: Domain::SELINUX,
3494 nspace: 1,
3495 alias: Some(TEST_ALIAS.to_string()),
3496 blob: None,
3497 },
3498 KeyType::Client,
3499 KeyEntryLoadBits::BOTH,
3500 1,
3501 |_k, _av| Ok(()),
3502 )
3503 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003504 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003505
3506 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003507 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003508 domain: Domain::SELINUX,
3509 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003510 alias: Some(TEST_ALIAS.to_string()),
3511 blob: None,
3512 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003513 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003514 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003515 |_, _| Ok(()),
3516 )
3517 .unwrap();
3518
3519 assert_eq!(
3520 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3521 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003522 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003523 domain: Domain::SELINUX,
3524 nspace: 1,
3525 alias: Some(TEST_ALIAS.to_string()),
3526 blob: None,
3527 },
3528 KeyType::Client,
3529 KeyEntryLoadBits::NONE,
3530 1,
3531 |_k, _av| Ok(()),
3532 )
3533 .unwrap_err()
3534 .root_cause()
3535 .downcast_ref::<KsError>()
3536 );
3537
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003538 Ok(())
3539 }
3540
3541 #[test]
3542 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3543 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003544 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003545 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3546 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003547 let (_, key_entry) = db
3548 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003549 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003550 KeyType::Client,
3551 KeyEntryLoadBits::BOTH,
3552 1,
3553 |_k, _av| Ok(()),
3554 )
3555 .unwrap();
3556
Qi Wub9433b52020-12-01 14:52:46 +08003557 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003558
3559 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003560 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003561 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003562 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003563 |_, _| Ok(()),
3564 )
3565 .unwrap();
3566
3567 assert_eq!(
3568 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3569 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003570 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003571 KeyType::Client,
3572 KeyEntryLoadBits::NONE,
3573 1,
3574 |_k, _av| Ok(()),
3575 )
3576 .unwrap_err()
3577 .root_cause()
3578 .downcast_ref::<KsError>()
3579 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003580
3581 Ok(())
3582 }
3583
3584 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003585 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3586 let mut db = new_test_db()?;
3587 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3588 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3589 .0;
3590 // Update the usage count of the limited use key.
3591 db.check_and_update_key_usage_count(key_id)?;
3592
3593 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003594 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003595 KeyType::Client,
3596 KeyEntryLoadBits::BOTH,
3597 1,
3598 |_k, _av| Ok(()),
3599 )?;
3600
3601 // The usage count is decremented now.
3602 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3603
3604 Ok(())
3605 }
3606
3607 #[test]
3608 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3609 let mut db = new_test_db()?;
3610 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3611 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3612 .0;
3613 // Update the usage count of the limited use key.
3614 db.check_and_update_key_usage_count(key_id).expect(concat!(
3615 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3616 "This should succeed."
3617 ));
3618
3619 // Try to update the exhausted limited use key.
3620 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3621 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3622 "This should fail."
3623 ));
3624 assert_eq!(
3625 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3626 e.root_cause().downcast_ref::<KsError>().unwrap()
3627 );
3628
3629 Ok(())
3630 }
3631
3632 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003633 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3634 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003635 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003636 .context("test_insert_and_load_full_keyentry_from_grant")?
3637 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003638
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003639 let granted_key = db
3640 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003641 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003642 domain: Domain::APP,
3643 nspace: 0,
3644 alias: Some(TEST_ALIAS.to_string()),
3645 blob: None,
3646 },
3647 1,
3648 2,
3649 key_perm_set![KeyPerm::use_()],
3650 |_k, _av| Ok(()),
3651 )
3652 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003653
3654 debug_dump_grant_table(&mut db)?;
3655
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003656 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003657 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3658 assert_eq!(Domain::GRANT, k.domain);
3659 assert!(av.unwrap().includes(KeyPerm::use_()));
3660 Ok(())
3661 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003662 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003663
Qi Wub9433b52020-12-01 14:52:46 +08003664 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003665
Janis Danisevskis66784c42021-01-27 08:40:25 -08003666 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003667
3668 assert_eq!(
3669 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3670 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003671 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003672 KeyType::Client,
3673 KeyEntryLoadBits::NONE,
3674 2,
3675 |_k, _av| Ok(()),
3676 )
3677 .unwrap_err()
3678 .root_cause()
3679 .downcast_ref::<KsError>()
3680 );
3681
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003682 Ok(())
3683 }
3684
Janis Danisevskis45760022021-01-19 16:34:10 -08003685 // This test attempts to load a key by key id while the caller is not the owner
3686 // but a grant exists for the given key and the caller.
3687 #[test]
3688 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3689 let mut db = new_test_db()?;
3690 const OWNER_UID: u32 = 1u32;
3691 const GRANTEE_UID: u32 = 2u32;
3692 const SOMEONE_ELSE_UID: u32 = 3u32;
3693 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3694 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3695 .0;
3696
3697 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003698 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003699 domain: Domain::APP,
3700 nspace: 0,
3701 alias: Some(TEST_ALIAS.to_string()),
3702 blob: None,
3703 },
3704 OWNER_UID,
3705 GRANTEE_UID,
3706 key_perm_set![KeyPerm::use_()],
3707 |_k, _av| Ok(()),
3708 )
3709 .unwrap();
3710
3711 debug_dump_grant_table(&mut db)?;
3712
3713 let id_descriptor =
3714 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3715
3716 let (_, key_entry) = db
3717 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003718 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003719 KeyType::Client,
3720 KeyEntryLoadBits::BOTH,
3721 GRANTEE_UID,
3722 |k, av| {
3723 assert_eq!(Domain::APP, k.domain);
3724 assert_eq!(OWNER_UID as i64, k.nspace);
3725 assert!(av.unwrap().includes(KeyPerm::use_()));
3726 Ok(())
3727 },
3728 )
3729 .unwrap();
3730
3731 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3732
3733 let (_, key_entry) = db
3734 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003735 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003736 KeyType::Client,
3737 KeyEntryLoadBits::BOTH,
3738 SOMEONE_ELSE_UID,
3739 |k, av| {
3740 assert_eq!(Domain::APP, k.domain);
3741 assert_eq!(OWNER_UID as i64, k.nspace);
3742 assert!(av.is_none());
3743 Ok(())
3744 },
3745 )
3746 .unwrap();
3747
3748 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3749
Janis Danisevskis66784c42021-01-27 08:40:25 -08003750 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003751
3752 assert_eq!(
3753 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3754 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003755 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003756 KeyType::Client,
3757 KeyEntryLoadBits::NONE,
3758 GRANTEE_UID,
3759 |_k, _av| Ok(()),
3760 )
3761 .unwrap_err()
3762 .root_cause()
3763 .downcast_ref::<KsError>()
3764 );
3765
3766 Ok(())
3767 }
3768
Janis Danisevskisaec14592020-11-12 09:41:49 -08003769 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
3770
Janis Danisevskisaec14592020-11-12 09:41:49 -08003771 #[test]
3772 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
3773 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003774 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
3775 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003776 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08003777 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003778 .context("test_insert_and_load_full_keyentry_domain_app")?
3779 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003780 let (_key_guard, key_entry) = db
3781 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003782 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003783 domain: Domain::APP,
3784 nspace: 0,
3785 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
3786 blob: None,
3787 },
3788 KeyType::Client,
3789 KeyEntryLoadBits::BOTH,
3790 33,
3791 |_k, _av| Ok(()),
3792 )
3793 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003794 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08003795 let state = Arc::new(AtomicU8::new(1));
3796 let state2 = state.clone();
3797
3798 // Spawning a second thread that attempts to acquire the key id lock
3799 // for the same key as the primary thread. The primary thread then
3800 // waits, thereby forcing the secondary thread into the second stage
3801 // of acquiring the lock (see KEY ID LOCK 2/2 above).
3802 // The test succeeds if the secondary thread observes the transition
3803 // of `state` from 1 to 2, despite having a whole second to overtake
3804 // the primary thread.
3805 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003806 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003807 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08003808 assert!(db
3809 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003810 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08003811 domain: Domain::APP,
3812 nspace: 0,
3813 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
3814 blob: None,
3815 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003816 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08003817 KeyEntryLoadBits::BOTH,
3818 33,
3819 |_k, _av| Ok(()),
3820 )
3821 .is_ok());
3822 // We should only see a 2 here because we can only return
3823 // from load_key_entry when the `_key_guard` expires,
3824 // which happens at the end of the scope.
3825 assert_eq!(2, state2.load(Ordering::Relaxed));
3826 });
3827
3828 thread::sleep(std::time::Duration::from_millis(1000));
3829
3830 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
3831
3832 // Return the handle from this scope so we can join with the
3833 // secondary thread after the key id lock has expired.
3834 handle
3835 // This is where the `_key_guard` goes out of scope,
3836 // which is the reason for concurrent load_key_entry on the same key
3837 // to unblock.
3838 };
3839 // Join with the secondary thread and unwrap, to propagate failing asserts to the
3840 // main test thread. We will not see failing asserts in secondary threads otherwise.
3841 handle.join().unwrap();
3842 Ok(())
3843 }
3844
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003845 #[test]
Janis Danisevskis66784c42021-01-27 08:40:25 -08003846 fn teset_database_busy_error_code() {
3847 let temp_dir =
3848 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
3849
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003850 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
3851 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08003852
3853 let _tx1 = db1
3854 .conn
3855 .transaction_with_behavior(TransactionBehavior::Immediate)
3856 .expect("Failed to create first transaction.");
3857
3858 let error = db2
3859 .conn
3860 .transaction_with_behavior(TransactionBehavior::Immediate)
3861 .context("Transaction begin failed.")
3862 .expect_err("This should fail.");
3863 let root_cause = error.root_cause();
3864 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
3865 root_cause.downcast_ref::<rusqlite::ffi::Error>()
3866 {
3867 return;
3868 }
3869 panic!(
3870 "Unexpected error {:?} \n{:?} \n{:?}",
3871 error,
3872 root_cause,
3873 root_cause.downcast_ref::<rusqlite::ffi::Error>()
3874 )
3875 }
3876
3877 #[cfg(disabled)]
3878 #[test]
3879 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
3880 let temp_dir = Arc::new(
3881 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
3882 .expect("Failed to create temp dir."),
3883 );
3884
3885 let test_begin = Instant::now();
3886
3887 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
3888 const KEY_COUNT: u32 = 500u32;
3889 const OPEN_DB_COUNT: u32 = 50u32;
3890
3891 let mut actual_key_count = KEY_COUNT;
3892 // First insert KEY_COUNT keys.
3893 for count in 0..KEY_COUNT {
3894 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
3895 actual_key_count = count;
3896 break;
3897 }
3898 let alias = format!("test_alias_{}", count);
3899 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
3900 .expect("Failed to make key entry.");
3901 }
3902
3903 // Insert more keys from a different thread and into a different namespace.
3904 let temp_dir1 = temp_dir.clone();
3905 let handle1 = thread::spawn(move || {
3906 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
3907
3908 for count in 0..actual_key_count {
3909 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
3910 return;
3911 }
3912 let alias = format!("test_alias_{}", count);
3913 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
3914 .expect("Failed to make key entry.");
3915 }
3916
3917 // then unbind them again.
3918 for count in 0..actual_key_count {
3919 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
3920 return;
3921 }
3922 let key = KeyDescriptor {
3923 domain: Domain::APP,
3924 nspace: -1,
3925 alias: Some(format!("test_alias_{}", count)),
3926 blob: None,
3927 };
3928 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
3929 }
3930 });
3931
3932 // And start unbinding the first set of keys.
3933 let temp_dir2 = temp_dir.clone();
3934 let handle2 = thread::spawn(move || {
3935 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
3936
3937 for count in 0..actual_key_count {
3938 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
3939 return;
3940 }
3941 let key = KeyDescriptor {
3942 domain: Domain::APP,
3943 nspace: -1,
3944 alias: Some(format!("test_alias_{}", count)),
3945 blob: None,
3946 };
3947 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
3948 }
3949 });
3950
3951 let stop_deleting = Arc::new(AtomicU8::new(0));
3952 let stop_deleting2 = stop_deleting.clone();
3953
3954 // And delete anything that is unreferenced keys.
3955 let temp_dir3 = temp_dir.clone();
3956 let handle3 = thread::spawn(move || {
3957 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
3958
3959 while stop_deleting2.load(Ordering::Relaxed) != 1 {
3960 while let Some((key_guard, _key)) =
3961 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
3962 {
3963 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
3964 return;
3965 }
3966 db.purge_key_entry(key_guard).expect("Failed to purge key.");
3967 }
3968 std::thread::sleep(std::time::Duration::from_millis(100));
3969 }
3970 });
3971
3972 // While a lot of inserting and deleting is going on we have to open database connections
3973 // successfully and use them.
3974 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
3975 // out of scope.
3976 #[allow(clippy::redundant_clone)]
3977 let temp_dir4 = temp_dir.clone();
3978 let handle4 = thread::spawn(move || {
3979 for count in 0..OPEN_DB_COUNT {
3980 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
3981 return;
3982 }
3983 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
3984
3985 let alias = format!("test_alias_{}", count);
3986 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
3987 .expect("Failed to make key entry.");
3988 let key = KeyDescriptor {
3989 domain: Domain::APP,
3990 nspace: -1,
3991 alias: Some(alias),
3992 blob: None,
3993 };
3994 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
3995 }
3996 });
3997
3998 handle1.join().expect("Thread 1 panicked.");
3999 handle2.join().expect("Thread 2 panicked.");
4000 handle4.join().expect("Thread 4 panicked.");
4001
4002 stop_deleting.store(1, Ordering::Relaxed);
4003 handle3.join().expect("Thread 3 panicked.");
4004
4005 Ok(())
4006 }
4007
4008 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004009 fn list() -> Result<()> {
4010 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004011 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004012 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4013 (Domain::APP, 1, "test1"),
4014 (Domain::APP, 1, "test2"),
4015 (Domain::APP, 1, "test3"),
4016 (Domain::APP, 1, "test4"),
4017 (Domain::APP, 1, "test5"),
4018 (Domain::APP, 1, "test6"),
4019 (Domain::APP, 1, "test7"),
4020 (Domain::APP, 2, "test1"),
4021 (Domain::APP, 2, "test2"),
4022 (Domain::APP, 2, "test3"),
4023 (Domain::APP, 2, "test4"),
4024 (Domain::APP, 2, "test5"),
4025 (Domain::APP, 2, "test6"),
4026 (Domain::APP, 2, "test8"),
4027 (Domain::SELINUX, 100, "test1"),
4028 (Domain::SELINUX, 100, "test2"),
4029 (Domain::SELINUX, 100, "test3"),
4030 (Domain::SELINUX, 100, "test4"),
4031 (Domain::SELINUX, 100, "test5"),
4032 (Domain::SELINUX, 100, "test6"),
4033 (Domain::SELINUX, 100, "test9"),
4034 ];
4035
4036 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4037 .iter()
4038 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004039 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4040 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004041 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4042 });
4043 (entry.id(), *ns)
4044 })
4045 .collect();
4046
4047 for (domain, namespace) in
4048 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4049 {
4050 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4051 .iter()
4052 .filter_map(|(domain, ns, alias)| match ns {
4053 ns if *ns == *namespace => Some(KeyDescriptor {
4054 domain: *domain,
4055 nspace: *ns,
4056 alias: Some(alias.to_string()),
4057 blob: None,
4058 }),
4059 _ => None,
4060 })
4061 .collect();
4062 list_o_descriptors.sort();
4063 let mut list_result = db.list(*domain, *namespace)?;
4064 list_result.sort();
4065 assert_eq!(list_o_descriptors, list_result);
4066
4067 let mut list_o_ids: Vec<i64> = list_o_descriptors
4068 .into_iter()
4069 .map(|d| {
4070 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004071 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004072 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004073 KeyType::Client,
4074 KeyEntryLoadBits::NONE,
4075 *namespace as u32,
4076 |_, _| Ok(()),
4077 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004078 .unwrap();
4079 entry.id()
4080 })
4081 .collect();
4082 list_o_ids.sort_unstable();
4083 let mut loaded_entries: Vec<i64> = list_o_keys
4084 .iter()
4085 .filter_map(|(id, ns)| match ns {
4086 ns if *ns == *namespace => Some(*id),
4087 _ => None,
4088 })
4089 .collect();
4090 loaded_entries.sort_unstable();
4091 assert_eq!(list_o_ids, loaded_entries);
4092 }
4093 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4094
4095 Ok(())
4096 }
4097
Joel Galenson0891bc12020-07-20 10:37:03 -07004098 // Helpers
4099
4100 // Checks that the given result is an error containing the given string.
4101 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4102 let error_str = format!(
4103 "{:#?}",
4104 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4105 );
4106 assert!(
4107 error_str.contains(target),
4108 "The string \"{}\" should contain \"{}\"",
4109 error_str,
4110 target
4111 );
4112 }
4113
Joel Galenson2aab4432020-07-22 15:27:57 -07004114 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004115 #[allow(dead_code)]
4116 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004117 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004118 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004119 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004120 namespace: Option<i64>,
4121 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004122 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004123 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004124 }
4125
4126 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4127 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004128 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004129 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004130 Ok(KeyEntryRow {
4131 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004132 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004133 domain: match row.get(2)? {
4134 Some(i) => Some(Domain(i)),
4135 None => None,
4136 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004137 namespace: row.get(3)?,
4138 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004139 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004140 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004141 })
4142 })?
4143 .map(|r| r.context("Could not read keyentry row."))
4144 .collect::<Result<Vec<_>>>()
4145 }
4146
Max Bires2b2e6562020-09-22 11:22:36 -07004147 fn load_attestation_key_pool(
4148 db: &mut KeystoreDB,
4149 expiration_date: i64,
4150 namespace: i64,
4151 base_byte: u8,
4152 ) -> Result<Vec<Vec<u8>>> {
4153 let mut chain: Vec<Vec<u8>> = Vec::new();
4154 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4155 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4156 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4157 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
4158 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4159 db.store_signed_attestation_certificate_chain(
4160 &raw_public_key,
4161 &cert_chain,
4162 expiration_date,
4163 &KEYSTORE_UUID,
4164 )?;
4165 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
4166 chain.push(public_key);
4167 chain.push(cert_chain);
4168 chain.push(priv_key);
4169 chain.push(raw_public_key);
4170 Ok(chain)
4171 }
4172
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004173 // Note: The parameters and SecurityLevel associations are nonsensical. This
4174 // collection is only used to check if the parameters are preserved as expected by the
4175 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004176 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4177 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004178 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4179 KeyParameter::new(
4180 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4181 SecurityLevel::TRUSTED_ENVIRONMENT,
4182 ),
4183 KeyParameter::new(
4184 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4185 SecurityLevel::TRUSTED_ENVIRONMENT,
4186 ),
4187 KeyParameter::new(
4188 KeyParameterValue::Algorithm(Algorithm::RSA),
4189 SecurityLevel::TRUSTED_ENVIRONMENT,
4190 ),
4191 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4192 KeyParameter::new(
4193 KeyParameterValue::BlockMode(BlockMode::ECB),
4194 SecurityLevel::TRUSTED_ENVIRONMENT,
4195 ),
4196 KeyParameter::new(
4197 KeyParameterValue::BlockMode(BlockMode::GCM),
4198 SecurityLevel::TRUSTED_ENVIRONMENT,
4199 ),
4200 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4201 KeyParameter::new(
4202 KeyParameterValue::Digest(Digest::MD5),
4203 SecurityLevel::TRUSTED_ENVIRONMENT,
4204 ),
4205 KeyParameter::new(
4206 KeyParameterValue::Digest(Digest::SHA_2_224),
4207 SecurityLevel::TRUSTED_ENVIRONMENT,
4208 ),
4209 KeyParameter::new(
4210 KeyParameterValue::Digest(Digest::SHA_2_256),
4211 SecurityLevel::STRONGBOX,
4212 ),
4213 KeyParameter::new(
4214 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4215 SecurityLevel::TRUSTED_ENVIRONMENT,
4216 ),
4217 KeyParameter::new(
4218 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4219 SecurityLevel::TRUSTED_ENVIRONMENT,
4220 ),
4221 KeyParameter::new(
4222 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4223 SecurityLevel::STRONGBOX,
4224 ),
4225 KeyParameter::new(
4226 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4227 SecurityLevel::TRUSTED_ENVIRONMENT,
4228 ),
4229 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4230 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4231 KeyParameter::new(
4232 KeyParameterValue::EcCurve(EcCurve::P_224),
4233 SecurityLevel::TRUSTED_ENVIRONMENT,
4234 ),
4235 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4236 KeyParameter::new(
4237 KeyParameterValue::EcCurve(EcCurve::P_384),
4238 SecurityLevel::TRUSTED_ENVIRONMENT,
4239 ),
4240 KeyParameter::new(
4241 KeyParameterValue::EcCurve(EcCurve::P_521),
4242 SecurityLevel::TRUSTED_ENVIRONMENT,
4243 ),
4244 KeyParameter::new(
4245 KeyParameterValue::RSAPublicExponent(3),
4246 SecurityLevel::TRUSTED_ENVIRONMENT,
4247 ),
4248 KeyParameter::new(
4249 KeyParameterValue::IncludeUniqueID,
4250 SecurityLevel::TRUSTED_ENVIRONMENT,
4251 ),
4252 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4253 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4254 KeyParameter::new(
4255 KeyParameterValue::ActiveDateTime(1234567890),
4256 SecurityLevel::STRONGBOX,
4257 ),
4258 KeyParameter::new(
4259 KeyParameterValue::OriginationExpireDateTime(1234567890),
4260 SecurityLevel::TRUSTED_ENVIRONMENT,
4261 ),
4262 KeyParameter::new(
4263 KeyParameterValue::UsageExpireDateTime(1234567890),
4264 SecurityLevel::TRUSTED_ENVIRONMENT,
4265 ),
4266 KeyParameter::new(
4267 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4268 SecurityLevel::TRUSTED_ENVIRONMENT,
4269 ),
4270 KeyParameter::new(
4271 KeyParameterValue::MaxUsesPerBoot(1234567890),
4272 SecurityLevel::TRUSTED_ENVIRONMENT,
4273 ),
4274 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4275 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4276 KeyParameter::new(
4277 KeyParameterValue::NoAuthRequired,
4278 SecurityLevel::TRUSTED_ENVIRONMENT,
4279 ),
4280 KeyParameter::new(
4281 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4282 SecurityLevel::TRUSTED_ENVIRONMENT,
4283 ),
4284 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4285 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4286 KeyParameter::new(
4287 KeyParameterValue::TrustedUserPresenceRequired,
4288 SecurityLevel::TRUSTED_ENVIRONMENT,
4289 ),
4290 KeyParameter::new(
4291 KeyParameterValue::TrustedConfirmationRequired,
4292 SecurityLevel::TRUSTED_ENVIRONMENT,
4293 ),
4294 KeyParameter::new(
4295 KeyParameterValue::UnlockedDeviceRequired,
4296 SecurityLevel::TRUSTED_ENVIRONMENT,
4297 ),
4298 KeyParameter::new(
4299 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4300 SecurityLevel::SOFTWARE,
4301 ),
4302 KeyParameter::new(
4303 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4304 SecurityLevel::SOFTWARE,
4305 ),
4306 KeyParameter::new(
4307 KeyParameterValue::CreationDateTime(12345677890),
4308 SecurityLevel::SOFTWARE,
4309 ),
4310 KeyParameter::new(
4311 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4312 SecurityLevel::TRUSTED_ENVIRONMENT,
4313 ),
4314 KeyParameter::new(
4315 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4316 SecurityLevel::TRUSTED_ENVIRONMENT,
4317 ),
4318 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4319 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4320 KeyParameter::new(
4321 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4322 SecurityLevel::SOFTWARE,
4323 ),
4324 KeyParameter::new(
4325 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4326 SecurityLevel::TRUSTED_ENVIRONMENT,
4327 ),
4328 KeyParameter::new(
4329 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4330 SecurityLevel::TRUSTED_ENVIRONMENT,
4331 ),
4332 KeyParameter::new(
4333 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4334 SecurityLevel::TRUSTED_ENVIRONMENT,
4335 ),
4336 KeyParameter::new(
4337 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4338 SecurityLevel::TRUSTED_ENVIRONMENT,
4339 ),
4340 KeyParameter::new(
4341 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4342 SecurityLevel::TRUSTED_ENVIRONMENT,
4343 ),
4344 KeyParameter::new(
4345 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4346 SecurityLevel::TRUSTED_ENVIRONMENT,
4347 ),
4348 KeyParameter::new(
4349 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4350 SecurityLevel::TRUSTED_ENVIRONMENT,
4351 ),
4352 KeyParameter::new(
4353 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4354 SecurityLevel::TRUSTED_ENVIRONMENT,
4355 ),
4356 KeyParameter::new(
4357 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4358 SecurityLevel::TRUSTED_ENVIRONMENT,
4359 ),
4360 KeyParameter::new(
4361 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4362 SecurityLevel::TRUSTED_ENVIRONMENT,
4363 ),
4364 KeyParameter::new(
4365 KeyParameterValue::VendorPatchLevel(3),
4366 SecurityLevel::TRUSTED_ENVIRONMENT,
4367 ),
4368 KeyParameter::new(
4369 KeyParameterValue::BootPatchLevel(4),
4370 SecurityLevel::TRUSTED_ENVIRONMENT,
4371 ),
4372 KeyParameter::new(
4373 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4374 SecurityLevel::TRUSTED_ENVIRONMENT,
4375 ),
4376 KeyParameter::new(
4377 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4378 SecurityLevel::TRUSTED_ENVIRONMENT,
4379 ),
4380 KeyParameter::new(
4381 KeyParameterValue::MacLength(256),
4382 SecurityLevel::TRUSTED_ENVIRONMENT,
4383 ),
4384 KeyParameter::new(
4385 KeyParameterValue::ResetSinceIdRotation,
4386 SecurityLevel::TRUSTED_ENVIRONMENT,
4387 ),
4388 KeyParameter::new(
4389 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4390 SecurityLevel::TRUSTED_ENVIRONMENT,
4391 ),
Qi Wub9433b52020-12-01 14:52:46 +08004392 ];
4393 if let Some(value) = max_usage_count {
4394 params.push(KeyParameter::new(
4395 KeyParameterValue::UsageCountLimit(value),
4396 SecurityLevel::SOFTWARE,
4397 ));
4398 }
4399 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004400 }
4401
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004402 fn make_test_key_entry(
4403 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004404 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004405 namespace: i64,
4406 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004407 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004408 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004409 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004410 let mut blob_metadata = BlobMetaData::new();
4411 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4412 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4413 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4414 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4415 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4416
4417 db.set_blob(
4418 &key_id,
4419 SubComponentType::KEY_BLOB,
4420 Some(TEST_KEY_BLOB),
4421 Some(&blob_metadata),
4422 )?;
4423 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4424 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004425
4426 let params = make_test_params(max_usage_count);
4427 db.insert_keyparameter(&key_id, &params)?;
4428
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004429 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004430 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004431 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004432 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004433 Ok(key_id)
4434 }
4435
Qi Wub9433b52020-12-01 14:52:46 +08004436 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4437 let params = make_test_params(max_usage_count);
4438
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004439 let mut blob_metadata = BlobMetaData::new();
4440 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4441 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4442 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4443 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4444 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4445
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004446 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004447 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004448
4449 KeyEntry {
4450 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004451 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004452 cert: Some(TEST_CERT_BLOB.to_vec()),
4453 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004454 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004455 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004456 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004457 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004458 }
4459 }
4460
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004461 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004462 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004463 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004464 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004465 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004466 NO_PARAMS,
4467 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004468 Ok((
4469 row.get(0)?,
4470 row.get(1)?,
4471 row.get(2)?,
4472 row.get(3)?,
4473 row.get(4)?,
4474 row.get(5)?,
4475 row.get(6)?,
4476 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004477 },
4478 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004479
4480 println!("Key entry table rows:");
4481 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004482 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004483 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004484 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4485 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004486 );
4487 }
4488 Ok(())
4489 }
4490
4491 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004492 let mut stmt = db
4493 .conn
4494 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004495 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
4496 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4497 })?;
4498
4499 println!("Grant table rows:");
4500 for r in rows {
4501 let (id, gt, ki, av) = r.unwrap();
4502 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4503 }
4504 Ok(())
4505 }
4506
Joel Galenson0891bc12020-07-20 10:37:03 -07004507 // Use a custom random number generator that repeats each number once.
4508 // This allows us to test repeated elements.
4509
4510 thread_local! {
4511 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4512 }
4513
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004514 fn reset_random() {
4515 RANDOM_COUNTER.with(|counter| {
4516 *counter.borrow_mut() = 0;
4517 })
4518 }
4519
Joel Galenson0891bc12020-07-20 10:37:03 -07004520 pub fn random() -> i64 {
4521 RANDOM_COUNTER.with(|counter| {
4522 let result = *counter.borrow() / 2;
4523 *counter.borrow_mut() += 1;
4524 result
4525 })
4526 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004527
4528 #[test]
4529 fn test_last_off_body() -> Result<()> {
4530 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08004531 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004532 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4533 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
4534 tx.commit()?;
4535 let one_second = Duration::from_secs(1);
4536 thread::sleep(one_second);
4537 db.update_last_off_body(MonotonicRawTime::now())?;
4538 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4539 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
4540 tx2.commit()?;
4541 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
4542 Ok(())
4543 }
Joel Galenson26f4d012020-07-17 14:57:21 -07004544}