blob: 6cdbc3e10957014ccf34fa347bd8ab6bf86ca5a4 [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 Gunasingheda895552021-01-27 19:34:37 +000048use crate::utils::{get_current_time_in_seconds, AID_USER_OFFSET};
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
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000795 /// The alias of the user super key.
796 pub const USER_SUPER_KEY_ALIAS: &'static str = &"USER_SUPER_KEY";
797
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800798 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
799 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
800 let conn = Connection::open_in_memory()
801 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
802
803 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
804 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
805 Ok(PerBootDbKeepAlive(conn))
806 }
807
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700808 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800809 /// files persistent.sqlite and perboot.sqlite in the given directory.
810 /// It also attempts to initialize all of the tables.
811 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700812 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800813 pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800814 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800815 let mut persistent_path = db_root.to_path_buf();
816 persistent_path.push("persistent.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700817
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800818 // Now convert them to strings prefixed with "file:"
819 let mut persistent_path_str = "file:".to_owned();
820 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800821
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800822 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800823
Janis Danisevskis66784c42021-01-27 08:40:25 -0800824 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
825 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
826
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800827 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800828 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800829 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800830 })?;
831 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700832 }
833
Janis Danisevskis66784c42021-01-27 08:40:25 -0800834 fn init_tables(tx: &Transaction) -> Result<()> {
835 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700836 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700837 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800838 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700839 domain INTEGER,
840 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800841 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800842 state INTEGER,
843 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700844 NO_PARAMS,
845 )
846 .context("Failed to initialize \"keyentry\" table.")?;
847
Janis Danisevskis66784c42021-01-27 08:40:25 -0800848 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800849 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
850 ON keyentry(id);",
851 NO_PARAMS,
852 )
853 .context("Failed to create index keyentry_id_index.")?;
854
855 tx.execute(
856 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
857 ON keyentry(domain, namespace, alias);",
858 NO_PARAMS,
859 )
860 .context("Failed to create index keyentry_domain_namespace_index.")?;
861
862 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700863 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
864 id INTEGER PRIMARY KEY,
865 subcomponent_type INTEGER,
866 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800867 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700868 NO_PARAMS,
869 )
870 .context("Failed to initialize \"blobentry\" table.")?;
871
Janis Danisevskis66784c42021-01-27 08:40:25 -0800872 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800873 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
874 ON blobentry(keyentryid);",
875 NO_PARAMS,
876 )
877 .context("Failed to create index blobentry_keyentryid_index.")?;
878
879 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800880 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
881 id INTEGER PRIMARY KEY,
882 blobentryid INTEGER,
883 tag INTEGER,
884 data ANY,
885 UNIQUE (blobentryid, tag));",
886 NO_PARAMS,
887 )
888 .context("Failed to initialize \"blobmetadata\" table.")?;
889
890 tx.execute(
891 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
892 ON blobmetadata(blobentryid);",
893 NO_PARAMS,
894 )
895 .context("Failed to create index blobmetadata_blobentryid_index.")?;
896
897 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700898 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000899 keyentryid INTEGER,
900 tag INTEGER,
901 data ANY,
902 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700903 NO_PARAMS,
904 )
905 .context("Failed to initialize \"keyparameter\" table.")?;
906
Janis Danisevskis66784c42021-01-27 08:40:25 -0800907 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800908 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
909 ON keyparameter(keyentryid);",
910 NO_PARAMS,
911 )
912 .context("Failed to create index keyparameter_keyentryid_index.")?;
913
914 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800915 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
916 keyentryid INTEGER,
917 tag INTEGER,
918 data ANY);",
919 NO_PARAMS,
920 )
921 .context("Failed to initialize \"keymetadata\" table.")?;
922
Janis Danisevskis66784c42021-01-27 08:40:25 -0800923 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800924 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
925 ON keymetadata(keyentryid);",
926 NO_PARAMS,
927 )
928 .context("Failed to create index keymetadata_keyentryid_index.")?;
929
930 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800931 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700932 id INTEGER UNIQUE,
933 grantee INTEGER,
934 keyentryid INTEGER,
935 access_vector INTEGER);",
936 NO_PARAMS,
937 )
938 .context("Failed to initialize \"grant\" table.")?;
939
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000940 //TODO: only drop the following two perboot tables if this is the first start up
941 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800942 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000943 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800944 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000945 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
946 id INTEGER PRIMARY KEY,
947 challenge INTEGER,
948 user_id INTEGER,
949 auth_id INTEGER,
950 authenticator_type INTEGER,
951 timestamp INTEGER,
952 mac BLOB,
953 time_received INTEGER,
954 UNIQUE(user_id, auth_id, authenticator_type));",
955 NO_PARAMS,
956 )
957 .context("Failed to initialize \"authtoken\" table.")?;
958
Janis Danisevskis66784c42021-01-27 08:40:25 -0800959 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000960 // .context("Failed to drop perboot.metadata table")?;
961 // metadata table stores certain miscellaneous information required for keystore functioning
962 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800963 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000964 "CREATE TABLE IF NOT EXISTS perboot.metadata (
965 key TEXT,
966 value BLOB,
967 UNIQUE(key));",
968 NO_PARAMS,
969 )
970 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -0700971 Ok(())
972 }
973
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700974 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
975 let conn =
976 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
977
Janis Danisevskis66784c42021-01-27 08:40:25 -0800978 loop {
979 if let Err(e) = conn
980 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
981 .context("Failed to attach database persistent.")
982 {
983 if Self::is_locked_error(&e) {
984 std::thread::sleep(std::time::Duration::from_micros(500));
985 continue;
986 } else {
987 return Err(e);
988 }
989 }
990 break;
991 }
992 loop {
993 if let Err(e) = conn
994 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
995 .context("Failed to attach database perboot.")
996 {
997 if Self::is_locked_error(&e) {
998 std::thread::sleep(std::time::Duration::from_micros(500));
999 continue;
1000 } else {
1001 return Err(e);
1002 }
1003 }
1004 break;
1005 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001006
1007 Ok(conn)
1008 }
1009
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001010 /// This function is intended to be used by the garbage collector.
1011 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1012 /// key blob that might need special handling by the garbage collector.
1013 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1014 /// need special handling and returns None.
1015 pub fn handle_next_superseded_blob(
1016 &mut self,
1017 blob_id_to_delete: Option<i64>,
1018 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001019 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001020 // Delete the given blob if one was given.
1021 if let Some(blob_id_to_delete) = blob_id_to_delete {
1022 tx.execute(
1023 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1024 params![blob_id_to_delete],
1025 )
1026 .context("Trying to delete blob metadata.")?;
1027 tx.execute(
1028 "DELETE FROM persistent.blobentry WHERE id = ?;",
1029 params![blob_id_to_delete],
1030 )
1031 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001032 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001033
1034 // Find another superseded keyblob load its metadata and return it.
1035 if let Some((blob_id, blob)) = tx
1036 .query_row(
1037 "SELECT id, blob FROM persistent.blobentry
1038 WHERE subcomponent_type = ?
1039 AND (
1040 id NOT IN (
1041 SELECT MAX(id) FROM persistent.blobentry
1042 WHERE subcomponent_type = ?
1043 GROUP BY keyentryid, subcomponent_type
1044 )
1045 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1046 );",
1047 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1048 |row| Ok((row.get(0)?, row.get(1)?)),
1049 )
1050 .optional()
1051 .context("Trying to query superseded blob.")?
1052 {
1053 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1054 .context("Trying to load blob metadata.")?;
1055 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1056 }
1057
1058 // We did not find any superseded key blob, so let's remove other superseded blob in
1059 // one transaction.
1060 tx.execute(
1061 "DELETE FROM persistent.blobentry
1062 WHERE NOT subcomponent_type = ?
1063 AND (
1064 id NOT IN (
1065 SELECT MAX(id) FROM persistent.blobentry
1066 WHERE NOT subcomponent_type = ?
1067 GROUP BY keyentryid, subcomponent_type
1068 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1069 );",
1070 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1071 )
1072 .context("Trying to purge superseded blobs.")?;
1073
1074 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001075 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001076 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001077 }
1078
1079 /// This maintenance function should be called only once before the database is used for the
1080 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1081 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1082 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1083 /// Keystore crashed at some point during key generation. Callers may want to log such
1084 /// occurrences.
1085 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1086 /// it to `KeyLifeCycle::Live` may have grants.
1087 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001088 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1089 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001090 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1091 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1092 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001093 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001094 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001095 })
1096 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001097 }
1098
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001099 /// Checks if a key exists with given key type and key descriptor properties.
1100 pub fn key_exists(
1101 &mut self,
1102 domain: Domain,
1103 nspace: i64,
1104 alias: &str,
1105 key_type: KeyType,
1106 ) -> Result<bool> {
1107 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1108 let key_descriptor =
1109 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1110 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1111 match result {
1112 Ok(_) => Ok(true),
1113 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1114 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1115 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1116 },
1117 }
1118 .no_gc()
1119 })
1120 .context("In key_exists.")
1121 }
1122
Hasini Gunasingheda895552021-01-27 19:34:37 +00001123 /// Stores a super key in the database.
1124 pub fn store_super_key(
1125 &mut self,
1126 user_id: i64,
1127 blob_info: &(&[u8], &BlobMetaData),
1128 ) -> Result<KeyEntry> {
1129 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1130 let key_id = Self::insert_with_retry(|id| {
1131 tx.execute(
1132 "INSERT into persistent.keyentry
1133 (id, key_type, domain, namespace, alias, state, km_uuid)
1134 VALUES(?, ?, NULL, ?, ?, ?, ?);",
1135 params![
1136 id,
1137 KeyType::Super,
1138 user_id,
1139 Self::USER_SUPER_KEY_ALIAS,
1140 KeyLifeCycle::Live,
1141 &KEYSTORE_UUID,
1142 ],
1143 )
1144 })
1145 .context("Failed to insert into keyentry table.")?;
1146
1147 let (blob, blob_metadata) = *blob_info;
1148 Self::set_blob_internal(
1149 &tx,
1150 key_id,
1151 SubComponentType::KEY_BLOB,
1152 Some(blob),
1153 Some(blob_metadata),
1154 )
1155 .context("Failed to store key blob.")?;
1156
1157 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1158 .context("Trying to load key components.")
1159 .no_gc()
1160 })
1161 .context("In store_super_key.")
1162 }
1163
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001164 /// Atomically loads a key entry and associated metadata or creates it using the
1165 /// callback create_new_key callback. The callback is called during a database
1166 /// transaction. This means that implementers should be mindful about using
1167 /// blocking operations such as IPC or grabbing mutexes.
1168 pub fn get_or_create_key_with<F>(
1169 &mut self,
1170 domain: Domain,
1171 namespace: i64,
1172 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001173 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001174 create_new_key: F,
1175 ) -> Result<(KeyIdGuard, KeyEntry)>
1176 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001177 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001178 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001179 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1180 let id = {
1181 let mut stmt = tx
1182 .prepare(
1183 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001184 WHERE
1185 key_type = ?
1186 AND domain = ?
1187 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001188 AND alias = ?
1189 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001190 )
1191 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1192 let mut rows = stmt
1193 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1194 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001195
Janis Danisevskis66784c42021-01-27 08:40:25 -08001196 db_utils::with_rows_extract_one(&mut rows, |row| {
1197 Ok(match row {
1198 Some(r) => r.get(0).context("Failed to unpack id.")?,
1199 None => None,
1200 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001201 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001202 .context("In get_or_create_key_with.")?
1203 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001204
Janis Danisevskis66784c42021-01-27 08:40:25 -08001205 let (id, entry) = match id {
1206 Some(id) => (
1207 id,
1208 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1209 .context("In get_or_create_key_with.")?,
1210 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001211
Janis Danisevskis66784c42021-01-27 08:40:25 -08001212 None => {
1213 let id = Self::insert_with_retry(|id| {
1214 tx.execute(
1215 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001216 (id, key_type, domain, namespace, alias, state, km_uuid)
1217 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001218 params![
1219 id,
1220 KeyType::Super,
1221 domain.0,
1222 namespace,
1223 alias,
1224 KeyLifeCycle::Live,
1225 km_uuid,
1226 ],
1227 )
1228 })
1229 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001230
Janis Danisevskis66784c42021-01-27 08:40:25 -08001231 let (blob, metadata) =
1232 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001233 Self::set_blob_internal(
1234 &tx,
1235 id,
1236 SubComponentType::KEY_BLOB,
1237 Some(&blob),
1238 Some(&metadata),
1239 )
1240 .context("In get_of_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001241 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001242 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001243 KeyEntry {
1244 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001245 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001246 pure_cert: false,
1247 ..Default::default()
1248 },
1249 )
1250 }
1251 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001252 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001253 })
1254 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001255 }
1256
Janis Danisevskis66784c42021-01-27 08:40:25 -08001257 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1258 /// waiting for the database file to become available. This makes it
1259 /// impossible to successfully recover from a locked database when the
1260 /// transaction holding the device busy is in the same process on a
1261 /// different connection. As a result the busy handler has to time out and
1262 /// fail in order to make progress.
1263 ///
1264 /// Instead, we set the busy handler to None (return immediately). And catch
1265 /// Busy and Locked errors (the latter occur on in memory databases with
1266 /// shared cache, e.g., the per-boot database.) and restart the transaction
1267 /// after a grace period of half a millisecond.
1268 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001269 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001270 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1271 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001272 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1273 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001274 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001275 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001276 loop {
1277 match self
1278 .conn
1279 .transaction_with_behavior(behavior)
1280 .context("In with_transaction.")
1281 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1282 .and_then(|(result, tx)| {
1283 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1284 Ok(result)
1285 }) {
1286 Ok(result) => break Ok(result),
1287 Err(e) => {
1288 if Self::is_locked_error(&e) {
1289 std::thread::sleep(std::time::Duration::from_micros(500));
1290 continue;
1291 } else {
1292 return Err(e).context("In with_transaction.");
1293 }
1294 }
1295 }
1296 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001297 .map(|(need_gc, result)| {
1298 if need_gc {
1299 if let Some(ref gc) = self.gc {
1300 gc.notify_gc();
1301 }
1302 }
1303 result
1304 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001305 }
1306
1307 fn is_locked_error(e: &anyhow::Error) -> bool {
1308 matches!(e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1309 Some(rusqlite::ffi::Error {
1310 code: rusqlite::ErrorCode::DatabaseBusy,
1311 ..
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001312 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001313 | Some(rusqlite::ffi::Error {
1314 code: rusqlite::ErrorCode::DatabaseLocked,
1315 ..
1316 }))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001317 }
1318
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001319 /// Creates a new key entry and allocates a new randomized id for the new key.
1320 /// The key id gets associated with a domain and namespace but not with an alias.
1321 /// To complete key generation `rebind_alias` should be called after all of the
1322 /// key artifacts, i.e., blobs and parameters have been associated with the new
1323 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1324 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001325 pub fn create_key_entry(
1326 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001327 domain: &Domain,
1328 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001329 km_uuid: &Uuid,
1330 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001331 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001332 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001333 })
1334 .context("In create_key_entry.")
1335 }
1336
1337 fn create_key_entry_internal(
1338 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001339 domain: &Domain,
1340 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001341 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001342 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001343 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001344 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001345 _ => {
1346 return Err(KsError::sys())
1347 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1348 }
1349 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001350 Ok(KEY_ID_LOCK.get(
1351 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001352 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001353 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001354 (id, key_type, domain, namespace, alias, state, km_uuid)
1355 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001356 params![
1357 id,
1358 KeyType::Client,
1359 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001360 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001361 KeyLifeCycle::Existing,
1362 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001363 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001364 )
1365 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001366 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001367 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001368 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001369
Max Bires2b2e6562020-09-22 11:22:36 -07001370 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1371 /// The key id gets associated with a domain and namespace later but not with an alias. The
1372 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1373 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1374 /// a key.
1375 pub fn create_attestation_key_entry(
1376 &mut self,
1377 maced_public_key: &[u8],
1378 raw_public_key: &[u8],
1379 private_key: &[u8],
1380 km_uuid: &Uuid,
1381 ) -> Result<()> {
1382 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1383 let key_id = KEY_ID_LOCK.get(
1384 Self::insert_with_retry(|id| {
1385 tx.execute(
1386 "INSERT into persistent.keyentry
1387 (id, key_type, domain, namespace, alias, state, km_uuid)
1388 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1389 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1390 )
1391 })
1392 .context("In create_key_entry")?,
1393 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001394 Self::set_blob_internal(
1395 &tx,
1396 key_id.0,
1397 SubComponentType::KEY_BLOB,
1398 Some(private_key),
1399 None,
1400 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001401 let mut metadata = KeyMetaData::new();
1402 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1403 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1404 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001405 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001406 })
1407 .context("In create_attestation_key_entry")
1408 }
1409
Janis Danisevskis377d1002021-01-27 19:07:48 -08001410 /// Set a new blob and associates it with the given key id. Each blob
1411 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001412 /// Each key can have one of each sub component type associated. If more
1413 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001414 /// will get garbage collected.
1415 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1416 /// removed by setting blob to None.
1417 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001418 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001419 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001420 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001421 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001422 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001423 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001424 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001425 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001426 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001427 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001428 }
1429
Janis Danisevskis377d1002021-01-27 19:07:48 -08001430 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001431 tx: &Transaction,
1432 key_id: i64,
1433 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001434 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001435 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001436 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001437 match (blob, sc_type) {
1438 (Some(blob), _) => {
1439 tx.execute(
1440 "INSERT INTO persistent.blobentry
1441 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1442 params![sc_type, key_id, blob],
1443 )
1444 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001445 if let Some(blob_metadata) = blob_metadata {
1446 let blob_id = tx
1447 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1448 row.get(0)
1449 })
1450 .context("In set_blob_internal: Failed to get new blob id.")?;
1451 blob_metadata
1452 .store_in_db(blob_id, tx)
1453 .context("In set_blob_internal: Trying to store blob metadata.")?;
1454 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001455 }
1456 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1457 tx.execute(
1458 "DELETE FROM persistent.blobentry
1459 WHERE subcomponent_type = ? AND keyentryid = ?;",
1460 params![sc_type, key_id],
1461 )
1462 .context("In set_blob_internal: Failed to delete blob.")?;
1463 }
1464 (None, _) => {
1465 return Err(KsError::sys())
1466 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1467 }
1468 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001469 Ok(())
1470 }
1471
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001472 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1473 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001474 #[cfg(test)]
1475 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001476 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001477 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001478 })
1479 .context("In insert_keyparameter.")
1480 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001481
Janis Danisevskis66784c42021-01-27 08:40:25 -08001482 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001483 tx: &Transaction,
1484 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001485 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001486 ) -> Result<()> {
1487 let mut stmt = tx
1488 .prepare(
1489 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1490 VALUES (?, ?, ?, ?);",
1491 )
1492 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1493
Janis Danisevskis66784c42021-01-27 08:40:25 -08001494 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001495 stmt.insert(params![
1496 key_id.0,
1497 p.get_tag().0,
1498 p.key_parameter_value(),
1499 p.security_level().0
1500 ])
1501 .with_context(|| {
1502 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1503 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001504 }
1505 Ok(())
1506 }
1507
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001508 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001509 #[cfg(test)]
1510 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001511 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001512 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001513 })
1514 .context("In insert_key_metadata.")
1515 }
1516
Max Bires2b2e6562020-09-22 11:22:36 -07001517 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1518 /// on the public key.
1519 pub fn store_signed_attestation_certificate_chain(
1520 &mut self,
1521 raw_public_key: &[u8],
1522 cert_chain: &[u8],
1523 expiration_date: i64,
1524 km_uuid: &Uuid,
1525 ) -> Result<()> {
1526 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1527 let mut stmt = tx
1528 .prepare(
1529 "SELECT keyentryid
1530 FROM persistent.keymetadata
1531 WHERE tag = ? AND data = ? AND keyentryid IN
1532 (SELECT id
1533 FROM persistent.keyentry
1534 WHERE
1535 alias IS NULL AND
1536 domain IS NULL AND
1537 namespace IS NULL AND
1538 key_type = ? AND
1539 km_uuid = ?);",
1540 )
1541 .context("Failed to store attestation certificate chain.")?;
1542 let mut rows = stmt
1543 .query(params![
1544 KeyMetaData::AttestationRawPubKey,
1545 raw_public_key,
1546 KeyType::Attestation,
1547 km_uuid
1548 ])
1549 .context("Failed to fetch keyid")?;
1550 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1551 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1552 .get(0)
1553 .context("Failed to unpack id.")
1554 })
1555 .context("Failed to get key_id.")?;
1556 let num_updated = tx
1557 .execute(
1558 "UPDATE persistent.keyentry
1559 SET alias = ?
1560 WHERE id = ?;",
1561 params!["signed", key_id],
1562 )
1563 .context("Failed to update alias.")?;
1564 if num_updated != 1 {
1565 return Err(KsError::sys()).context("Alias not updated for the key.");
1566 }
1567 let mut metadata = KeyMetaData::new();
1568 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1569 expiration_date,
1570 )));
1571 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001572 Self::set_blob_internal(
1573 &tx,
1574 key_id,
1575 SubComponentType::CERT_CHAIN,
1576 Some(cert_chain),
1577 None,
1578 )
1579 .context("Failed to insert cert chain")?;
1580 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001581 })
1582 .context("In store_signed_attestation_certificate_chain: ")
1583 }
1584
1585 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1586 /// currently have a key assigned to it.
1587 pub fn assign_attestation_key(
1588 &mut self,
1589 domain: Domain,
1590 namespace: i64,
1591 km_uuid: &Uuid,
1592 ) -> Result<()> {
1593 match domain {
1594 Domain::APP | Domain::SELINUX => {}
1595 _ => {
1596 return Err(KsError::sys()).context(format!(
1597 concat!(
1598 "In assign_attestation_key: Domain {:?} ",
1599 "must be either App or SELinux.",
1600 ),
1601 domain
1602 ));
1603 }
1604 }
1605 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1606 let result = tx
1607 .execute(
1608 "UPDATE persistent.keyentry
1609 SET domain=?1, namespace=?2
1610 WHERE
1611 id =
1612 (SELECT MIN(id)
1613 FROM persistent.keyentry
1614 WHERE ALIAS IS NOT NULL
1615 AND domain IS NULL
1616 AND key_type IS ?3
1617 AND state IS ?4
1618 AND km_uuid IS ?5)
1619 AND
1620 (SELECT COUNT(*)
1621 FROM persistent.keyentry
1622 WHERE domain=?1
1623 AND namespace=?2
1624 AND key_type IS ?3
1625 AND state IS ?4
1626 AND km_uuid IS ?5) = 0;",
1627 params![
1628 domain.0 as u32,
1629 namespace,
1630 KeyType::Attestation,
1631 KeyLifeCycle::Live,
1632 km_uuid,
1633 ],
1634 )
1635 .context("Failed to assign attestation key")?;
1636 if result != 1 {
1637 return Err(KsError::sys()).context(format!(
1638 "Expected to update a single entry but instead updated {}.",
1639 result
1640 ));
1641 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001642 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001643 })
1644 .context("In assign_attestation_key: ")
1645 }
1646
1647 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1648 /// provisioning server, or the maximum number available if there are not num_keys number of
1649 /// entries in the table.
1650 pub fn fetch_unsigned_attestation_keys(
1651 &mut self,
1652 num_keys: i32,
1653 km_uuid: &Uuid,
1654 ) -> Result<Vec<Vec<u8>>> {
1655 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1656 let mut stmt = tx
1657 .prepare(
1658 "SELECT data
1659 FROM persistent.keymetadata
1660 WHERE tag = ? AND keyentryid IN
1661 (SELECT id
1662 FROM persistent.keyentry
1663 WHERE
1664 alias IS NULL AND
1665 domain IS NULL AND
1666 namespace IS NULL AND
1667 key_type = ? AND
1668 km_uuid = ?
1669 LIMIT ?);",
1670 )
1671 .context("Failed to prepare statement")?;
1672 let rows = stmt
1673 .query_map(
1674 params![
1675 KeyMetaData::AttestationMacedPublicKey,
1676 KeyType::Attestation,
1677 km_uuid,
1678 num_keys
1679 ],
1680 |row| Ok(row.get(0)?),
1681 )?
1682 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1683 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001684 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001685 })
1686 .context("In fetch_unsigned_attestation_keys")
1687 }
1688
1689 /// Removes any keys that have expired as of the current time. Returns the number of keys
1690 /// marked unreferenced that are bound to be garbage collected.
1691 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
1692 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1693 let mut stmt = tx
1694 .prepare(
1695 "SELECT keyentryid, data
1696 FROM persistent.keymetadata
1697 WHERE tag = ? AND keyentryid IN
1698 (SELECT id
1699 FROM persistent.keyentry
1700 WHERE key_type = ?);",
1701 )
1702 .context("Failed to prepare query")?;
1703 let key_ids_to_check = stmt
1704 .query_map(
1705 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1706 |row| Ok((row.get(0)?, row.get(1)?)),
1707 )?
1708 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1709 .context("Failed to get date metadata")?;
1710 let curr_time = DateTime::from_millis_epoch(
1711 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1712 );
1713 let mut num_deleted = 0;
1714 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1715 if Self::mark_unreferenced(&tx, id)? {
1716 num_deleted += 1;
1717 }
1718 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001719 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001720 })
1721 .context("In delete_expired_attestation_keys: ")
1722 }
1723
1724 /// Counts the number of keys that will expire by the provided epoch date and the number of
1725 /// keys not currently assigned to a domain.
1726 pub fn get_attestation_pool_status(
1727 &mut self,
1728 date: i64,
1729 km_uuid: &Uuid,
1730 ) -> Result<AttestationPoolStatus> {
1731 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1732 let mut stmt = tx.prepare(
1733 "SELECT data
1734 FROM persistent.keymetadata
1735 WHERE tag = ? AND keyentryid IN
1736 (SELECT id
1737 FROM persistent.keyentry
1738 WHERE alias IS NOT NULL
1739 AND key_type = ?
1740 AND km_uuid = ?
1741 AND state = ?);",
1742 )?;
1743 let times = stmt
1744 .query_map(
1745 params![
1746 KeyMetaData::AttestationExpirationDate,
1747 KeyType::Attestation,
1748 km_uuid,
1749 KeyLifeCycle::Live
1750 ],
1751 |row| Ok(row.get(0)?),
1752 )?
1753 .collect::<rusqlite::Result<Vec<DateTime>>>()
1754 .context("Failed to execute metadata statement")?;
1755 let expiring =
1756 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1757 as i32;
1758 stmt = tx.prepare(
1759 "SELECT alias, domain
1760 FROM persistent.keyentry
1761 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1762 )?;
1763 let rows = stmt
1764 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1765 Ok((row.get(0)?, row.get(1)?))
1766 })?
1767 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1768 .context("Failed to execute keyentry statement")?;
1769 let mut unassigned = 0i32;
1770 let mut attested = 0i32;
1771 let total = rows.len() as i32;
1772 for (alias, domain) in rows {
1773 match (alias, domain) {
1774 (Some(_alias), None) => {
1775 attested += 1;
1776 unassigned += 1;
1777 }
1778 (Some(_alias), Some(_domain)) => {
1779 attested += 1;
1780 }
1781 _ => {}
1782 }
1783 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001784 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001785 })
1786 .context("In get_attestation_pool_status: ")
1787 }
1788
1789 /// Fetches the private key and corresponding certificate chain assigned to a
1790 /// domain/namespace pair. Will either return nothing if the domain/namespace is
1791 /// not assigned, or one CertificateChain.
1792 pub fn retrieve_attestation_key_and_cert_chain(
1793 &mut self,
1794 domain: Domain,
1795 namespace: i64,
1796 km_uuid: &Uuid,
1797 ) -> Result<Option<CertificateChain>> {
1798 match domain {
1799 Domain::APP | Domain::SELINUX => {}
1800 _ => {
1801 return Err(KsError::sys())
1802 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1803 }
1804 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001805 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1806 let mut stmt = tx.prepare(
1807 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07001808 FROM persistent.blobentry
1809 WHERE keyentryid IN
1810 (SELECT id
1811 FROM persistent.keyentry
1812 WHERE key_type = ?
1813 AND domain = ?
1814 AND namespace = ?
1815 AND state = ?
1816 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001817 )?;
1818 let rows = stmt
1819 .query_map(
1820 params![
1821 KeyType::Attestation,
1822 domain.0 as u32,
1823 namespace,
1824 KeyLifeCycle::Live,
1825 km_uuid
1826 ],
1827 |row| Ok((row.get(0)?, row.get(1)?)),
1828 )?
1829 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
1830 .context("In retrieve_attestation_key_and_cert_chain: query failed.")?;
1831 if rows.is_empty() {
1832 return Ok(None).no_gc();
1833 } else if rows.len() != 2 {
1834 return Err(KsError::sys()).context(format!(
1835 concat!(
Max Bires2b2e6562020-09-22 11:22:36 -07001836 "In retrieve_attestation_key_and_cert_chain: Expected to get a single attestation",
1837 "key chain but instead got {}."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001838 rows.len()
1839 ));
Max Bires2b2e6562020-09-22 11:22:36 -07001840 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001841 let mut km_blob: Vec<u8> = Vec::new();
1842 let mut cert_chain_blob: Vec<u8> = Vec::new();
1843 for row in rows {
1844 let sub_type: SubComponentType = row.0;
1845 match sub_type {
1846 SubComponentType::KEY_BLOB => {
1847 km_blob = row.1;
1848 }
1849 SubComponentType::CERT_CHAIN => {
1850 cert_chain_blob = row.1;
1851 }
1852 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
1853 }
1854 }
1855 Ok(Some(CertificateChain {
1856 private_key: ZVec::try_from(km_blob)?,
1857 cert_chain: ZVec::try_from(cert_chain_blob)?,
1858 }))
1859 .no_gc()
1860 })
Max Bires2b2e6562020-09-22 11:22:36 -07001861 }
1862
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001863 /// Updates the alias column of the given key id `newid` with the given alias,
1864 /// and atomically, removes the alias, domain, and namespace from another row
1865 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001866 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1867 /// collector.
1868 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001869 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001870 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001871 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001872 domain: &Domain,
1873 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001874 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001875 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001876 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001877 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001878 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001879 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001880 domain
1881 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001882 }
1883 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001884 let updated = tx
1885 .execute(
1886 "UPDATE persistent.keyentry
1887 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07001888 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001889 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
1890 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001891 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001892 let result = tx
1893 .execute(
1894 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001895 SET alias = ?, state = ?
1896 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
1897 params![
1898 alias,
1899 KeyLifeCycle::Live,
1900 newid.0,
1901 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001902 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001903 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001904 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001905 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001906 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001907 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001908 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001909 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001910 result
1911 ));
1912 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001913 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001914 }
1915
1916 /// Store a new key in a single transaction.
1917 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1918 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001919 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1920 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001921 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001922 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001923 key: &KeyDescriptor,
1924 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001925 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08001926 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001927 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001928 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001929 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001930 let (alias, domain, namespace) = match key {
1931 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1932 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1933 (alias, key.domain, nspace)
1934 }
1935 _ => {
1936 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1937 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
1938 }
1939 };
1940 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001941 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001942 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001943 let (blob, blob_metadata) = *blob_info;
1944 Self::set_blob_internal(
1945 tx,
1946 key_id.id(),
1947 SubComponentType::KEY_BLOB,
1948 Some(blob),
1949 Some(&blob_metadata),
1950 )
1951 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001952 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001953 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001954 .context("Trying to insert the certificate.")?;
1955 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001956 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001957 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001958 tx,
1959 key_id.id(),
1960 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001961 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001962 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001963 )
1964 .context("Trying to insert the certificate chain.")?;
1965 }
1966 Self::insert_keyparameter_internal(tx, &key_id, params)
1967 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001968 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001969 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001970 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001971 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001972 })
1973 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001974 }
1975
Janis Danisevskis377d1002021-01-27 19:07:48 -08001976 /// Store a new certificate
1977 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1978 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001979 pub fn store_new_certificate(
1980 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001981 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08001982 cert: &[u8],
1983 km_uuid: &Uuid,
1984 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001985 let (alias, domain, namespace) = match key {
1986 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1987 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1988 (alias, key.domain, nspace)
1989 }
1990 _ => {
1991 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
1992 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
1993 )
1994 }
1995 };
1996 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001997 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001998 .context("Trying to create new key entry.")?;
1999
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002000 Self::set_blob_internal(
2001 tx,
2002 key_id.id(),
2003 SubComponentType::CERT_CHAIN,
2004 Some(cert),
2005 None,
2006 )
2007 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002008
2009 let mut metadata = KeyMetaData::new();
2010 metadata.add(KeyMetaEntry::CreationDate(
2011 DateTime::now().context("Trying to make creation time.")?,
2012 ));
2013
2014 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2015
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002016 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002017 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002018 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002019 })
2020 .context("In store_new_certificate.")
2021 }
2022
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002023 // Helper function loading the key_id given the key descriptor
2024 // tuple comprising domain, namespace, and alias.
2025 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002026 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002027 let alias = key
2028 .alias
2029 .as_ref()
2030 .map_or_else(|| Err(KsError::sys()), Ok)
2031 .context("In load_key_entry_id: Alias must be specified.")?;
2032 let mut stmt = tx
2033 .prepare(
2034 "SELECT id FROM persistent.keyentry
2035 WHERE
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002036 key_type = ?
2037 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002038 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002039 AND alias = ?
2040 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002041 )
2042 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2043 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002044 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002045 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002046 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002047 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002048 .get(0)
2049 .context("Failed to unpack id.")
2050 })
2051 .context("In load_key_entry_id.")
2052 }
2053
2054 /// This helper function completes the access tuple of a key, which is required
2055 /// to perform access control. The strategy depends on the `domain` field in the
2056 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002057 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002058 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002059 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002060 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002061 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002062 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002063 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002064 /// `namespace`.
2065 /// In each case the information returned is sufficient to perform the access
2066 /// check and the key id can be used to load further key artifacts.
2067 fn load_access_tuple(
2068 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002069 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002070 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002071 caller_uid: u32,
2072 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2073 match key.domain {
2074 // Domain App or SELinux. In this case we load the key_id from
2075 // the keyentry database for further loading of key components.
2076 // We already have the full access tuple to perform access control.
2077 // The only distinction is that we use the caller_uid instead
2078 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002079 // Domain::APP.
2080 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002081 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002082 if access_key.domain == Domain::APP {
2083 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002084 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002085 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002086 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002087
2088 Ok((key_id, access_key, None))
2089 }
2090
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002091 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002092 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002093 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002094 let mut stmt = tx
2095 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002096 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002097 WHERE grantee = ? AND id = ?;",
2098 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002099 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002100 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002101 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002102 .context("Domain:Grant: query failed.")?;
2103 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002104 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002105 let r =
2106 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002107 Ok((
2108 r.get(0).context("Failed to unpack key_id.")?,
2109 r.get(1).context("Failed to unpack access_vector.")?,
2110 ))
2111 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002112 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002113 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002114 }
2115
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002116 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002117 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002118 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002119 let (domain, namespace): (Domain, i64) = {
2120 let mut stmt = tx
2121 .prepare(
2122 "SELECT domain, namespace FROM persistent.keyentry
2123 WHERE
2124 id = ?
2125 AND state = ?;",
2126 )
2127 .context("Domain::KEY_ID: prepare statement failed")?;
2128 let mut rows = stmt
2129 .query(params![key.nspace, KeyLifeCycle::Live])
2130 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002131 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002132 let r =
2133 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002134 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002135 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002136 r.get(1).context("Failed to unpack namespace.")?,
2137 ))
2138 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002139 .context("Domain::KEY_ID.")?
2140 };
2141
2142 // We may use a key by id after loading it by grant.
2143 // In this case we have to check if the caller has a grant for this particular
2144 // key. We can skip this if we already know that the caller is the owner.
2145 // But we cannot know this if domain is anything but App. E.g. in the case
2146 // of Domain::SELINUX we have to speculatively check for grants because we have to
2147 // consult the SEPolicy before we know if the caller is the owner.
2148 let access_vector: Option<KeyPermSet> =
2149 if domain != Domain::APP || namespace != caller_uid as i64 {
2150 let access_vector: Option<i32> = tx
2151 .query_row(
2152 "SELECT access_vector FROM persistent.grant
2153 WHERE grantee = ? AND keyentryid = ?;",
2154 params![caller_uid as i64, key.nspace],
2155 |row| row.get(0),
2156 )
2157 .optional()
2158 .context("Domain::KEY_ID: query grant failed.")?;
2159 access_vector.map(|p| p.into())
2160 } else {
2161 None
2162 };
2163
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002164 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002165 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002166 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002167 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002168
Janis Danisevskis45760022021-01-19 16:34:10 -08002169 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002170 }
2171 _ => Err(anyhow!(KsError::sys())),
2172 }
2173 }
2174
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002175 fn load_blob_components(
2176 key_id: i64,
2177 load_bits: KeyEntryLoadBits,
2178 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002179 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002180 let mut stmt = tx
2181 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002182 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002183 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2184 )
2185 .context("In load_blob_components: prepare statement failed.")?;
2186
2187 let mut rows =
2188 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2189
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002190 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002191 let mut cert_blob: Option<Vec<u8>> = None;
2192 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002193 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002194 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002195 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002196 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002197 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002198 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2199 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002200 key_blob = Some((
2201 row.get(0).context("Failed to extract key blob id.")?,
2202 row.get(2).context("Failed to extract key blob.")?,
2203 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002204 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002205 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002206 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002207 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002208 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002209 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002210 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002211 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002212 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002213 (SubComponentType::CERT, _, _)
2214 | (SubComponentType::CERT_CHAIN, _, _)
2215 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002216 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2217 }
2218 Ok(())
2219 })
2220 .context("In load_blob_components.")?;
2221
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002222 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2223 Ok(Some((
2224 blob,
2225 BlobMetaData::load_from_db(blob_id, tx)
2226 .context("In load_blob_components: Trying to load blob_metadata.")?,
2227 )))
2228 })?;
2229
2230 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002231 }
2232
2233 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2234 let mut stmt = tx
2235 .prepare(
2236 "SELECT tag, data, security_level from persistent.keyparameter
2237 WHERE keyentryid = ?;",
2238 )
2239 .context("In load_key_parameters: prepare statement failed.")?;
2240
2241 let mut parameters: Vec<KeyParameter> = Vec::new();
2242
2243 let mut rows =
2244 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002245 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002246 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2247 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002248 parameters.push(
2249 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2250 .context("Failed to read KeyParameter.")?,
2251 );
2252 Ok(())
2253 })
2254 .context("In load_key_parameters.")?;
2255
2256 Ok(parameters)
2257 }
2258
Qi Wub9433b52020-12-01 14:52:46 +08002259 /// Decrements the usage count of a limited use key. This function first checks whether the
2260 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2261 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2262 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002263 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002264 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2265 let limit: Option<i32> = tx
2266 .query_row(
2267 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2268 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2269 |row| row.get(0),
2270 )
2271 .optional()
2272 .context("Trying to load usage count")?;
2273
2274 let limit = limit
2275 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2276 .context("The Key no longer exists. Key is exhausted.")?;
2277
2278 tx.execute(
2279 "UPDATE persistent.keyparameter
2280 SET data = data - 1
2281 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2282 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2283 )
2284 .context("Failed to update key usage count.")?;
2285
2286 match limit {
2287 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002288 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002289 .context("Trying to mark limited use key for deletion."),
2290 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002291 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002292 }
2293 })
2294 .context("In check_and_update_key_usage_count.")
2295 }
2296
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002297 /// Load a key entry by the given key descriptor.
2298 /// It uses the `check_permission` callback to verify if the access is allowed
2299 /// given the key access tuple read from the database using `load_access_tuple`.
2300 /// With `load_bits` the caller may specify which blobs shall be loaded from
2301 /// the blob database.
2302 pub fn load_key_entry(
2303 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002304 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002305 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002306 load_bits: KeyEntryLoadBits,
2307 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002308 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2309 ) -> Result<(KeyIdGuard, KeyEntry)> {
2310 loop {
2311 match self.load_key_entry_internal(
2312 key,
2313 key_type,
2314 load_bits,
2315 caller_uid,
2316 &check_permission,
2317 ) {
2318 Ok(result) => break Ok(result),
2319 Err(e) => {
2320 if Self::is_locked_error(&e) {
2321 std::thread::sleep(std::time::Duration::from_micros(500));
2322 continue;
2323 } else {
2324 return Err(e).context("In load_key_entry.");
2325 }
2326 }
2327 }
2328 }
2329 }
2330
2331 fn load_key_entry_internal(
2332 &mut self,
2333 key: &KeyDescriptor,
2334 key_type: KeyType,
2335 load_bits: KeyEntryLoadBits,
2336 caller_uid: u32,
2337 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002338 ) -> Result<(KeyIdGuard, KeyEntry)> {
2339 // KEY ID LOCK 1/2
2340 // If we got a key descriptor with a key id we can get the lock right away.
2341 // Otherwise we have to defer it until we know the key id.
2342 let key_id_guard = match key.domain {
2343 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2344 _ => None,
2345 };
2346
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002347 let tx = self
2348 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002349 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002350 .context("In load_key_entry: Failed to initialize transaction.")?;
2351
2352 // Load the key_id and complete the access control tuple.
2353 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002354 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2355 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002356
2357 // Perform access control. It is vital that we return here if the permission is denied.
2358 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002359 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002360
Janis Danisevskisaec14592020-11-12 09:41:49 -08002361 // KEY ID LOCK 2/2
2362 // If we did not get a key id lock by now, it was because we got a key descriptor
2363 // without a key id. At this point we got the key id, so we can try and get a lock.
2364 // However, we cannot block here, because we are in the middle of the transaction.
2365 // So first we try to get the lock non blocking. If that fails, we roll back the
2366 // transaction and block until we get the lock. After we successfully got the lock,
2367 // we start a new transaction and load the access tuple again.
2368 //
2369 // We don't need to perform access control again, because we already established
2370 // that the caller had access to the given key. But we need to make sure that the
2371 // key id still exists. So we have to load the key entry by key id this time.
2372 let (key_id_guard, tx) = match key_id_guard {
2373 None => match KEY_ID_LOCK.try_get(key_id) {
2374 None => {
2375 // Roll back the transaction.
2376 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002377
Janis Danisevskisaec14592020-11-12 09:41:49 -08002378 // Block until we have a key id lock.
2379 let key_id_guard = KEY_ID_LOCK.get(key_id);
2380
2381 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002382 let tx = self
2383 .conn
2384 .unchecked_transaction()
2385 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002386
2387 Self::load_access_tuple(
2388 &tx,
2389 // This time we have to load the key by the retrieved key id, because the
2390 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002391 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002392 domain: Domain::KEY_ID,
2393 nspace: key_id,
2394 ..Default::default()
2395 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002396 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002397 caller_uid,
2398 )
2399 .context("In load_key_entry. (deferred key lock)")?;
2400 (key_id_guard, tx)
2401 }
2402 Some(l) => (l, tx),
2403 },
2404 Some(key_id_guard) => (key_id_guard, tx),
2405 };
2406
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002407 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2408 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002409
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002410 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2411
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002412 Ok((key_id_guard, key_entry))
2413 }
2414
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002415 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002416 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002417 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2418 .context("Trying to delete keyentry.")?;
2419 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2420 .context("Trying to delete keymetadata.")?;
2421 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2422 .context("Trying to delete keyparameters.")?;
2423 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2424 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002425 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002426 }
2427
2428 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002429 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002430 pub fn unbind_key(
2431 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002432 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002433 key_type: KeyType,
2434 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002435 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002436 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002437 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2438 let (key_id, access_key_descriptor, access_vector) =
2439 Self::load_access_tuple(tx, key, key_type, caller_uid)
2440 .context("Trying to get access tuple.")?;
2441
2442 // Perform access control. It is vital that we return here if the permission is denied.
2443 // So do not touch that '?' at the end.
2444 check_permission(&access_key_descriptor, access_vector)
2445 .context("While checking permission.")?;
2446
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002447 Self::mark_unreferenced(tx, key_id)
2448 .map(|need_gc| (need_gc, ()))
2449 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002450 })
2451 .context("In unbind_key.")
2452 }
2453
Max Bires8e93d2b2021-01-14 13:17:59 -08002454 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2455 tx.query_row(
2456 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2457 params![key_id],
2458 |row| row.get(0),
2459 )
2460 .context("In get_key_km_uuid.")
2461 }
2462
Hasini Gunasingheda895552021-01-27 19:34:37 +00002463 /// Delete the keys created on behalf of the user, denoted by the user id.
2464 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2465 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2466 /// The caller of this function should notify the gc if the returned value is true.
2467 pub fn unbind_keys_for_user(
2468 &mut self,
2469 user_id: u32,
2470 keep_non_super_encrypted_keys: bool,
2471 ) -> Result<()> {
2472 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2473 let mut stmt = tx
2474 .prepare(&format!(
2475 "SELECT id from persistent.keyentry
2476 WHERE (
2477 key_type = ?
2478 AND domain = ?
2479 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2480 AND state = ?
2481 ) OR (
2482 key_type = ?
2483 AND namespace = ?
2484 AND alias = ?
2485 AND state = ?
2486 );",
2487 aid_user_offset = AID_USER_OFFSET
2488 ))
2489 .context(concat!(
2490 "In unbind_keys_for_user. ",
2491 "Failed to prepare the query to find the keys created by apps."
2492 ))?;
2493
2494 let mut rows = stmt
2495 .query(params![
2496 // WHERE client key:
2497 KeyType::Client,
2498 Domain::APP.0 as u32,
2499 user_id,
2500 KeyLifeCycle::Live,
2501 // OR super key:
2502 KeyType::Super,
2503 user_id,
2504 Self::USER_SUPER_KEY_ALIAS,
2505 KeyLifeCycle::Live
2506 ])
2507 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2508
2509 let mut key_ids: Vec<i64> = Vec::new();
2510 db_utils::with_rows_extract_all(&mut rows, |row| {
2511 key_ids
2512 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2513 Ok(())
2514 })
2515 .context("In unbind_keys_for_user.")?;
2516
2517 let mut notify_gc = false;
2518 for key_id in key_ids {
2519 if keep_non_super_encrypted_keys {
2520 // Load metadata and filter out non-super-encrypted keys.
2521 if let (_, Some((_, blob_metadata)), _, _) =
2522 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2523 .context("In unbind_keys_for_user: Trying to load blob info.")?
2524 {
2525 if blob_metadata.encrypted_by().is_none() {
2526 continue;
2527 }
2528 }
2529 }
2530 notify_gc = Self::mark_unreferenced(&tx, key_id as u64 as i64)
2531 .context("In unbind_keys_for_user.")?
2532 || notify_gc;
2533 }
2534 Ok(()).do_gc(notify_gc)
2535 })
2536 .context("In unbind_keys_for_user.")
2537 }
2538
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002539 fn load_key_components(
2540 tx: &Transaction,
2541 load_bits: KeyEntryLoadBits,
2542 key_id: i64,
2543 ) -> Result<KeyEntry> {
2544 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2545
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002546 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002547 Self::load_blob_components(key_id, load_bits, &tx)
2548 .context("In load_key_components.")?;
2549
Max Bires8e93d2b2021-01-14 13:17:59 -08002550 let parameters = Self::load_key_parameters(key_id, &tx)
2551 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002552
Max Bires8e93d2b2021-01-14 13:17:59 -08002553 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2554 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002555
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002556 Ok(KeyEntry {
2557 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002558 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002559 cert: cert_blob,
2560 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002561 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002562 parameters,
2563 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002564 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002565 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002566 }
2567
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002568 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2569 /// The key descriptors will have the domain, nspace, and alias field set.
2570 /// Domain must be APP or SELINUX, the caller must make sure of that.
2571 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002572 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2573 let mut stmt = tx
2574 .prepare(
2575 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002576 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002577 )
2578 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002579
Janis Danisevskis66784c42021-01-27 08:40:25 -08002580 let mut rows = stmt
2581 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2582 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002583
Janis Danisevskis66784c42021-01-27 08:40:25 -08002584 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2585 db_utils::with_rows_extract_all(&mut rows, |row| {
2586 descriptors.push(KeyDescriptor {
2587 domain,
2588 nspace: namespace,
2589 alias: Some(row.get(0).context("Trying to extract alias.")?),
2590 blob: None,
2591 });
2592 Ok(())
2593 })
2594 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002595 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002596 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002597 }
2598
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002599 /// Adds a grant to the grant table.
2600 /// Like `load_key_entry` this function loads the access tuple before
2601 /// it uses the callback for a permission check. Upon success,
2602 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2603 /// grant table. The new row will have a randomized id, which is used as
2604 /// grant id in the namespace field of the resulting KeyDescriptor.
2605 pub fn grant(
2606 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002607 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002608 caller_uid: u32,
2609 grantee_uid: u32,
2610 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002611 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002612 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002613 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2614 // Load the key_id and complete the access control tuple.
2615 // We ignore the access vector here because grants cannot be granted.
2616 // The access vector returned here expresses the permissions the
2617 // grantee has if key.domain == Domain::GRANT. But this vector
2618 // cannot include the grant permission by design, so there is no way the
2619 // subsequent permission check can pass.
2620 // We could check key.domain == Domain::GRANT and fail early.
2621 // But even if we load the access tuple by grant here, the permission
2622 // check denies the attempt to create a grant by grant descriptor.
2623 let (key_id, access_key_descriptor, _) =
2624 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2625 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002626
Janis Danisevskis66784c42021-01-27 08:40:25 -08002627 // Perform access control. It is vital that we return here if the permission
2628 // was denied. So do not touch that '?' at the end of the line.
2629 // This permission check checks if the caller has the grant permission
2630 // for the given key and in addition to all of the permissions
2631 // expressed in `access_vector`.
2632 check_permission(&access_key_descriptor, &access_vector)
2633 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002634
Janis Danisevskis66784c42021-01-27 08:40:25 -08002635 let grant_id = if let Some(grant_id) = tx
2636 .query_row(
2637 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002638 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002639 params![key_id, grantee_uid],
2640 |row| row.get(0),
2641 )
2642 .optional()
2643 .context("In grant: Failed get optional existing grant id.")?
2644 {
2645 tx.execute(
2646 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002647 SET access_vector = ?
2648 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002649 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002650 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002651 .context("In grant: Failed to update existing grant.")?;
2652 grant_id
2653 } else {
2654 Self::insert_with_retry(|id| {
2655 tx.execute(
2656 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2657 VALUES (?, ?, ?, ?);",
2658 params![id, grantee_uid, key_id, i32::from(access_vector)],
2659 )
2660 })
2661 .context("In grant")?
2662 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002663
Janis Danisevskis66784c42021-01-27 08:40:25 -08002664 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002665 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002666 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002667 }
2668
2669 /// This function checks permissions like `grant` and `load_key_entry`
2670 /// before removing a grant from the grant table.
2671 pub fn ungrant(
2672 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002673 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002674 caller_uid: u32,
2675 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002676 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002677 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002678 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2679 // Load the key_id and complete the access control tuple.
2680 // We ignore the access vector here because grants cannot be granted.
2681 let (key_id, access_key_descriptor, _) =
2682 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2683 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002684
Janis Danisevskis66784c42021-01-27 08:40:25 -08002685 // Perform access control. We must return here if the permission
2686 // was denied. So do not touch the '?' at the end of this line.
2687 check_permission(&access_key_descriptor)
2688 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002689
Janis Danisevskis66784c42021-01-27 08:40:25 -08002690 tx.execute(
2691 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002692 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002693 params![key_id, grantee_uid],
2694 )
2695 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002696
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002697 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002698 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002699 }
2700
Joel Galenson845f74b2020-09-09 14:11:55 -07002701 // Generates a random id and passes it to the given function, which will
2702 // try to insert it into a database. If that insertion fails, retry;
2703 // otherwise return the id.
2704 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2705 loop {
2706 let newid: i64 = random();
2707 match inserter(newid) {
2708 // If the id already existed, try again.
2709 Err(rusqlite::Error::SqliteFailure(
2710 libsqlite3_sys::Error {
2711 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2712 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2713 },
2714 _,
2715 )) => (),
2716 Err(e) => {
2717 return Err(e).context("In insert_with_retry: failed to insert into database.")
2718 }
2719 _ => return Ok(newid),
2720 }
2721 }
2722 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002723
2724 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
2725 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002726 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2727 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002728 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
2729 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
2730 params![
2731 auth_token.challenge,
2732 auth_token.userId,
2733 auth_token.authenticatorId,
2734 auth_token.authenticatorType.0 as i32,
2735 auth_token.timestamp.milliSeconds as i64,
2736 auth_token.mac,
2737 MonotonicRawTime::now(),
2738 ],
2739 )
2740 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002741 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002742 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002743 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002744
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002745 /// Find the newest auth token matching the given predicate.
2746 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002747 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002748 p: F,
2749 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
2750 where
2751 F: Fn(&AuthTokenEntry) -> bool,
2752 {
2753 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2754 let mut stmt = tx
2755 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
2756 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002757
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002758 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002759
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002760 while let Some(row) = rows.next().context("Failed to get next row.")? {
2761 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002762 HardwareAuthToken {
2763 challenge: row.get(1)?,
2764 userId: row.get(2)?,
2765 authenticatorId: row.get(3)?,
2766 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2767 timestamp: Timestamp { milliSeconds: row.get(5)? },
2768 mac: row.get(6)?,
2769 },
2770 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002771 );
2772 if p(&entry) {
2773 return Ok(Some((
2774 entry,
2775 Self::get_last_off_body(tx)
2776 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002777 )))
2778 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002779 }
2780 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002781 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002782 })
2783 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002784 }
2785
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002786 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08002787 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2788 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2789 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002790 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
2791 params!["last_off_body", last_off_body],
2792 )
2793 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002794 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002795 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002796 }
2797
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002798 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08002799 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2800 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2801 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002802 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
2803 params![last_off_body, "last_off_body"],
2804 )
2805 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002806 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002807 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002808 }
2809
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002810 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002811 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002812 tx.query_row(
2813 "SELECT value from perboot.metadata WHERE key = ?;",
2814 params!["last_off_body"],
2815 |row| Ok(row.get(0)?),
2816 )
2817 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002818 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002819}
2820
2821#[cfg(test)]
2822mod tests {
2823
2824 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002825 use crate::key_parameter::{
2826 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2827 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2828 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002829 use crate::key_perm_set;
2830 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00002831 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002832 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002833 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2834 HardwareAuthToken::HardwareAuthToken,
2835 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002836 };
2837 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002838 Timestamp::Timestamp,
2839 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002840 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002841 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07002842 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002843 use std::sync::atomic::{AtomicU8, Ordering};
2844 use std::sync::Arc;
2845 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002846 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08002847 #[cfg(disabled)]
2848 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002849
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002850 fn new_test_db() -> Result<KeystoreDB> {
2851 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
2852
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002853 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002854 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002855 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002856 })?;
2857 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002858 }
2859
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002860 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
2861 where
2862 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
2863 {
2864 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
2865 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db));
2866
2867 KeystoreDB::new(path, Some(gc))
2868 }
2869
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002870 fn rebind_alias(
2871 db: &mut KeystoreDB,
2872 newid: &KeyIdGuard,
2873 alias: &str,
2874 domain: Domain,
2875 namespace: i64,
2876 ) -> Result<bool> {
2877 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002878 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002879 })
2880 .context("In rebind_alias.")
2881 }
2882
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002883 #[test]
2884 fn datetime() -> Result<()> {
2885 let conn = Connection::open_in_memory()?;
2886 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
2887 let now = SystemTime::now();
2888 let duration = Duration::from_secs(1000);
2889 let then = now.checked_sub(duration).unwrap();
2890 let soon = now.checked_add(duration).unwrap();
2891 conn.execute(
2892 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2893 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2894 )?;
2895 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
2896 let mut rows = stmt.query(NO_PARAMS)?;
2897 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2898 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2899 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2900 assert!(rows.next()?.is_none());
2901 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2902 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2903 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2904 Ok(())
2905 }
2906
Joel Galenson0891bc12020-07-20 10:37:03 -07002907 // Ensure that we're using the "injected" random function, not the real one.
2908 #[test]
2909 fn test_mocked_random() {
2910 let rand1 = random();
2911 let rand2 = random();
2912 let rand3 = random();
2913 if rand1 == rand2 {
2914 assert_eq!(rand2 + 1, rand3);
2915 } else {
2916 assert_eq!(rand1 + 1, rand2);
2917 assert_eq!(rand2, rand3);
2918 }
2919 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002920
Joel Galenson26f4d012020-07-17 14:57:21 -07002921 // Test that we have the correct tables.
2922 #[test]
2923 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002924 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002925 let tables = db
2926 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002927 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002928 .query_map(params![], |row| row.get(0))?
2929 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002930 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002931 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002932 assert_eq!(tables[1], "blobmetadata");
2933 assert_eq!(tables[2], "grant");
2934 assert_eq!(tables[3], "keyentry");
2935 assert_eq!(tables[4], "keymetadata");
2936 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002937 let tables = db
2938 .conn
2939 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
2940 .query_map(params![], |row| row.get(0))?
2941 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002942
2943 assert_eq!(tables.len(), 2);
2944 assert_eq!(tables[0], "authtoken");
2945 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07002946 Ok(())
2947 }
2948
2949 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002950 fn test_auth_token_table_invariant() -> Result<()> {
2951 let mut db = new_test_db()?;
2952 let auth_token1 = HardwareAuthToken {
2953 challenge: i64::MAX,
2954 userId: 200,
2955 authenticatorId: 200,
2956 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2957 timestamp: Timestamp { milliSeconds: 500 },
2958 mac: String::from("mac").into_bytes(),
2959 };
2960 db.insert_auth_token(&auth_token1)?;
2961 let auth_tokens_returned = get_auth_tokens(&mut db)?;
2962 assert_eq!(auth_tokens_returned.len(), 1);
2963
2964 // insert another auth token with the same values for the columns in the UNIQUE constraint
2965 // of the auth token table and different value for timestamp
2966 let auth_token2 = HardwareAuthToken {
2967 challenge: i64::MAX,
2968 userId: 200,
2969 authenticatorId: 200,
2970 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2971 timestamp: Timestamp { milliSeconds: 600 },
2972 mac: String::from("mac").into_bytes(),
2973 };
2974
2975 db.insert_auth_token(&auth_token2)?;
2976 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
2977 assert_eq!(auth_tokens_returned.len(), 1);
2978
2979 if let Some(auth_token) = auth_tokens_returned.pop() {
2980 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
2981 }
2982
2983 // insert another auth token with the different values for the columns in the UNIQUE
2984 // constraint of the auth token table
2985 let auth_token3 = HardwareAuthToken {
2986 challenge: i64::MAX,
2987 userId: 201,
2988 authenticatorId: 200,
2989 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2990 timestamp: Timestamp { milliSeconds: 600 },
2991 mac: String::from("mac").into_bytes(),
2992 };
2993
2994 db.insert_auth_token(&auth_token3)?;
2995 let auth_tokens_returned = get_auth_tokens(&mut db)?;
2996 assert_eq!(auth_tokens_returned.len(), 2);
2997
2998 Ok(())
2999 }
3000
3001 // utility function for test_auth_token_table_invariant()
3002 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3003 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3004
3005 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3006 .query_map(NO_PARAMS, |row| {
3007 Ok(AuthTokenEntry::new(
3008 HardwareAuthToken {
3009 challenge: row.get(1)?,
3010 userId: row.get(2)?,
3011 authenticatorId: row.get(3)?,
3012 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3013 timestamp: Timestamp { milliSeconds: row.get(5)? },
3014 mac: row.get(6)?,
3015 },
3016 row.get(7)?,
3017 ))
3018 })?
3019 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3020 Ok(auth_token_entries)
3021 }
3022
3023 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003024 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003025 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003026 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003027
Janis Danisevskis66784c42021-01-27 08:40:25 -08003028 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003029 let entries = get_keyentry(&db)?;
3030 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003031
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003032 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003033
3034 let entries_new = get_keyentry(&db)?;
3035 assert_eq!(entries, entries_new);
3036 Ok(())
3037 }
3038
3039 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003040 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003041 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3042 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003043 }
3044
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003045 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003046
Janis Danisevskis66784c42021-01-27 08:40:25 -08003047 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3048 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003049
3050 let entries = get_keyentry(&db)?;
3051 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003052 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3053 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003054
3055 // Test that we must pass in a valid Domain.
3056 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003057 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003058 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003059 );
3060 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003061 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003062 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003063 );
3064 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003065 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003066 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003067 );
3068
3069 Ok(())
3070 }
3071
Joel Galenson33c04ad2020-08-03 11:04:38 -07003072 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003073 fn test_add_unsigned_key() -> Result<()> {
3074 let mut db = new_test_db()?;
3075 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3076 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3077 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3078 db.create_attestation_key_entry(
3079 &public_key,
3080 &raw_public_key,
3081 &private_key,
3082 &KEYSTORE_UUID,
3083 )?;
3084 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3085 assert_eq!(keys.len(), 1);
3086 assert_eq!(keys[0], public_key);
3087 Ok(())
3088 }
3089
3090 #[test]
3091 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3092 let mut db = new_test_db()?;
3093 let expiration_date: i64 = 20;
3094 let namespace: i64 = 30;
3095 let base_byte: u8 = 1;
3096 let loaded_values =
3097 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3098 let chain =
3099 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3100 assert_eq!(true, chain.is_some());
3101 let cert_chain = chain.unwrap();
3102 assert_eq!(cert_chain.private_key.to_vec(), loaded_values[2]);
3103 assert_eq!(cert_chain.cert_chain.to_vec(), loaded_values[1]);
3104 Ok(())
3105 }
3106
3107 #[test]
3108 fn test_get_attestation_pool_status() -> Result<()> {
3109 let mut db = new_test_db()?;
3110 let namespace: i64 = 30;
3111 load_attestation_key_pool(
3112 &mut db, 10, /* expiration */
3113 namespace, 0x01, /* base_byte */
3114 )?;
3115 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3116 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3117 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3118 assert_eq!(status.expiring, 0);
3119 assert_eq!(status.attested, 3);
3120 assert_eq!(status.unassigned, 0);
3121 assert_eq!(status.total, 3);
3122 assert_eq!(
3123 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3124 1
3125 );
3126 assert_eq!(
3127 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3128 2
3129 );
3130 assert_eq!(
3131 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3132 3
3133 );
3134 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3135 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3136 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3137 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
3138 db.create_attestation_key_entry(
3139 &public_key,
3140 &raw_public_key,
3141 &private_key,
3142 &KEYSTORE_UUID,
3143 )?;
3144 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3145 assert_eq!(status.attested, 3);
3146 assert_eq!(status.unassigned, 0);
3147 assert_eq!(status.total, 4);
3148 db.store_signed_attestation_certificate_chain(
3149 &raw_public_key,
3150 &cert_chain,
3151 20,
3152 &KEYSTORE_UUID,
3153 )?;
3154 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3155 assert_eq!(status.attested, 4);
3156 assert_eq!(status.unassigned, 1);
3157 assert_eq!(status.total, 4);
3158 Ok(())
3159 }
3160
3161 #[test]
3162 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003163 let temp_dir =
3164 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3165 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003166 let expiration_date: i64 =
3167 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3168 let namespace: i64 = 30;
3169 let namespace_del1: i64 = 45;
3170 let namespace_del2: i64 = 60;
3171 let entry_values = load_attestation_key_pool(
3172 &mut db,
3173 expiration_date,
3174 namespace,
3175 0x01, /* base_byte */
3176 )?;
3177 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3178 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003179
3180 let blob_entry_row_count: u32 = db
3181 .conn
3182 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3183 .expect("Failed to get blob entry row count.");
3184 // We expect 6 rows here because there are two blobs per attestation key, i.e.,
3185 // One key and one certificate.
3186 assert_eq!(blob_entry_row_count, 6);
3187
Max Bires2b2e6562020-09-22 11:22:36 -07003188 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3189
3190 let mut cert_chain =
3191 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003192 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003193 let value = cert_chain.unwrap();
3194 assert_eq!(entry_values[1], value.cert_chain.to_vec());
3195 assert_eq!(entry_values[2], value.private_key.to_vec());
3196
3197 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3198 Domain::APP,
3199 namespace_del1,
3200 &KEYSTORE_UUID,
3201 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003202 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003203 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3204 Domain::APP,
3205 namespace_del2,
3206 &KEYSTORE_UUID,
3207 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003208 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003209
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003210 // Give the garbage collector half a second to catch up.
3211 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003212
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003213 let blob_entry_row_count: u32 = db
3214 .conn
3215 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3216 .expect("Failed to get blob entry row count.");
3217 // There shound be 2 blob entries left, because we deleted two of the attestation
3218 // key entries with two blobs each.
3219 assert_eq!(blob_entry_row_count, 2);
Max Bires2b2e6562020-09-22 11:22:36 -07003220
Max Bires2b2e6562020-09-22 11:22:36 -07003221 Ok(())
3222 }
3223
3224 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003225 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003226 fn extractor(
3227 ke: &KeyEntryRow,
3228 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3229 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003230 }
3231
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003232 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003233 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3234 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003235 let entries = get_keyentry(&db)?;
3236 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003237 assert_eq!(
3238 extractor(&entries[0]),
3239 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3240 );
3241 assert_eq!(
3242 extractor(&entries[1]),
3243 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3244 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003245
3246 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003247 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003248 let entries = get_keyentry(&db)?;
3249 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003250 assert_eq!(
3251 extractor(&entries[0]),
3252 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3253 );
3254 assert_eq!(
3255 extractor(&entries[1]),
3256 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3257 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003258
3259 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003260 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003261 let entries = get_keyentry(&db)?;
3262 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003263 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3264 assert_eq!(
3265 extractor(&entries[1]),
3266 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3267 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003268
3269 // Test that we must pass in a valid Domain.
3270 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003271 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003272 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003273 );
3274 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003275 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003276 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003277 );
3278 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003279 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003280 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003281 );
3282
3283 // Test that we correctly handle setting an alias for something that does not exist.
3284 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003285 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003286 "Expected to update a single entry but instead updated 0",
3287 );
3288 // Test that we correctly abort the transaction in this case.
3289 let entries = get_keyentry(&db)?;
3290 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003291 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3292 assert_eq!(
3293 extractor(&entries[1]),
3294 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3295 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003296
3297 Ok(())
3298 }
3299
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003300 #[test]
3301 fn test_grant_ungrant() -> Result<()> {
3302 const CALLER_UID: u32 = 15;
3303 const GRANTEE_UID: u32 = 12;
3304 const SELINUX_NAMESPACE: i64 = 7;
3305
3306 let mut db = new_test_db()?;
3307 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003308 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3309 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3310 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003311 )?;
3312 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003313 domain: super::Domain::APP,
3314 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003315 alias: Some("key".to_string()),
3316 blob: None,
3317 };
3318 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3319 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3320
3321 // Reset totally predictable random number generator in case we
3322 // are not the first test running on this thread.
3323 reset_random();
3324 let next_random = 0i64;
3325
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003326 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003327 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003328 assert_eq!(*a, PVEC1);
3329 assert_eq!(
3330 *k,
3331 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003332 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003333 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003334 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003335 alias: Some("key".to_string()),
3336 blob: None,
3337 }
3338 );
3339 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003340 })
3341 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003342
3343 assert_eq!(
3344 app_granted_key,
3345 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003346 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003347 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003348 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003349 alias: None,
3350 blob: None,
3351 }
3352 );
3353
3354 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003355 domain: super::Domain::SELINUX,
3356 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003357 alias: Some("yek".to_string()),
3358 blob: None,
3359 };
3360
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003361 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003362 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003363 assert_eq!(*a, PVEC1);
3364 assert_eq!(
3365 *k,
3366 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003367 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003368 // namespace must be the supplied SELinux
3369 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003370 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003371 alias: Some("yek".to_string()),
3372 blob: None,
3373 }
3374 );
3375 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003376 })
3377 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003378
3379 assert_eq!(
3380 selinux_granted_key,
3381 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003382 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003383 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003384 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003385 alias: None,
3386 blob: None,
3387 }
3388 );
3389
3390 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003391 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003392 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003393 assert_eq!(*a, PVEC2);
3394 assert_eq!(
3395 *k,
3396 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003397 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003398 // namespace must be the supplied SELinux
3399 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003400 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003401 alias: Some("yek".to_string()),
3402 blob: None,
3403 }
3404 );
3405 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003406 })
3407 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003408
3409 assert_eq!(
3410 selinux_granted_key,
3411 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003412 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003413 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003414 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003415 alias: None,
3416 blob: None,
3417 }
3418 );
3419
3420 {
3421 // Limiting scope of stmt, because it borrows db.
3422 let mut stmt = db
3423 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003424 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003425 let mut rows =
3426 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3427 Ok((
3428 row.get(0)?,
3429 row.get(1)?,
3430 row.get(2)?,
3431 KeyPermSet::from(row.get::<_, i32>(3)?),
3432 ))
3433 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003434
3435 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003436 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003437 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003438 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003439 assert!(rows.next().is_none());
3440 }
3441
3442 debug_dump_keyentry_table(&mut db)?;
3443 println!("app_key {:?}", app_key);
3444 println!("selinux_key {:?}", selinux_key);
3445
Janis Danisevskis66784c42021-01-27 08:40:25 -08003446 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3447 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003448
3449 Ok(())
3450 }
3451
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003452 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003453 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3454 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3455
3456 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003457 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003458 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003459 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003460 let mut blob_metadata = BlobMetaData::new();
3461 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3462 db.set_blob(
3463 &key_id,
3464 SubComponentType::KEY_BLOB,
3465 Some(TEST_KEY_BLOB),
3466 Some(&blob_metadata),
3467 )?;
3468 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3469 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003470 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003471
3472 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003473 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003474 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003475 )?;
3476 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003477 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3478 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003479 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003480 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003481 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003482 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003483 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003484 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003485 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003486
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003487 drop(rows);
3488 drop(stmt);
3489
3490 assert_eq!(
3491 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3492 BlobMetaData::load_from_db(id, tx).no_gc()
3493 })
3494 .expect("Should find blob metadata."),
3495 blob_metadata
3496 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003497 Ok(())
3498 }
3499
3500 static TEST_ALIAS: &str = "my super duper key";
3501
3502 #[test]
3503 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3504 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003505 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003506 .context("test_insert_and_load_full_keyentry_domain_app")?
3507 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003508 let (_key_guard, key_entry) = db
3509 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003510 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003511 domain: Domain::APP,
3512 nspace: 0,
3513 alias: Some(TEST_ALIAS.to_string()),
3514 blob: None,
3515 },
3516 KeyType::Client,
3517 KeyEntryLoadBits::BOTH,
3518 1,
3519 |_k, _av| Ok(()),
3520 )
3521 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003522 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003523
3524 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003525 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003526 domain: Domain::APP,
3527 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003528 alias: Some(TEST_ALIAS.to_string()),
3529 blob: None,
3530 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003531 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003532 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003533 |_, _| Ok(()),
3534 )
3535 .unwrap();
3536
3537 assert_eq!(
3538 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3539 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003540 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003541 domain: Domain::APP,
3542 nspace: 0,
3543 alias: Some(TEST_ALIAS.to_string()),
3544 blob: None,
3545 },
3546 KeyType::Client,
3547 KeyEntryLoadBits::NONE,
3548 1,
3549 |_k, _av| Ok(()),
3550 )
3551 .unwrap_err()
3552 .root_cause()
3553 .downcast_ref::<KsError>()
3554 );
3555
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003556 Ok(())
3557 }
3558
3559 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003560 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3561 let mut db = new_test_db()?;
3562
3563 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003564 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003565 domain: Domain::APP,
3566 nspace: 1,
3567 alias: Some(TEST_ALIAS.to_string()),
3568 blob: None,
3569 },
3570 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003571 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003572 )
3573 .expect("Trying to insert cert.");
3574
3575 let (_key_guard, mut key_entry) = db
3576 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003577 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003578 domain: Domain::APP,
3579 nspace: 1,
3580 alias: Some(TEST_ALIAS.to_string()),
3581 blob: None,
3582 },
3583 KeyType::Client,
3584 KeyEntryLoadBits::PUBLIC,
3585 1,
3586 |_k, _av| Ok(()),
3587 )
3588 .expect("Trying to read certificate entry.");
3589
3590 assert!(key_entry.pure_cert());
3591 assert!(key_entry.cert().is_none());
3592 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3593
3594 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003595 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003596 domain: Domain::APP,
3597 nspace: 1,
3598 alias: Some(TEST_ALIAS.to_string()),
3599 blob: None,
3600 },
3601 KeyType::Client,
3602 1,
3603 |_, _| Ok(()),
3604 )
3605 .unwrap();
3606
3607 assert_eq!(
3608 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3609 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003610 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003611 domain: Domain::APP,
3612 nspace: 1,
3613 alias: Some(TEST_ALIAS.to_string()),
3614 blob: None,
3615 },
3616 KeyType::Client,
3617 KeyEntryLoadBits::NONE,
3618 1,
3619 |_k, _av| Ok(()),
3620 )
3621 .unwrap_err()
3622 .root_cause()
3623 .downcast_ref::<KsError>()
3624 );
3625
3626 Ok(())
3627 }
3628
3629 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003630 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3631 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003632 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003633 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3634 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003635 let (_key_guard, key_entry) = db
3636 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003637 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003638 domain: Domain::SELINUX,
3639 nspace: 1,
3640 alias: Some(TEST_ALIAS.to_string()),
3641 blob: None,
3642 },
3643 KeyType::Client,
3644 KeyEntryLoadBits::BOTH,
3645 1,
3646 |_k, _av| Ok(()),
3647 )
3648 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003649 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003650
3651 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003652 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003653 domain: Domain::SELINUX,
3654 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003655 alias: Some(TEST_ALIAS.to_string()),
3656 blob: None,
3657 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003658 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003659 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003660 |_, _| Ok(()),
3661 )
3662 .unwrap();
3663
3664 assert_eq!(
3665 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3666 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003667 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003668 domain: Domain::SELINUX,
3669 nspace: 1,
3670 alias: Some(TEST_ALIAS.to_string()),
3671 blob: None,
3672 },
3673 KeyType::Client,
3674 KeyEntryLoadBits::NONE,
3675 1,
3676 |_k, _av| Ok(()),
3677 )
3678 .unwrap_err()
3679 .root_cause()
3680 .downcast_ref::<KsError>()
3681 );
3682
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003683 Ok(())
3684 }
3685
3686 #[test]
3687 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3688 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003689 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003690 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3691 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003692 let (_, key_entry) = db
3693 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003694 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003695 KeyType::Client,
3696 KeyEntryLoadBits::BOTH,
3697 1,
3698 |_k, _av| Ok(()),
3699 )
3700 .unwrap();
3701
Qi Wub9433b52020-12-01 14:52:46 +08003702 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003703
3704 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003705 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003706 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003707 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003708 |_, _| Ok(()),
3709 )
3710 .unwrap();
3711
3712 assert_eq!(
3713 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3714 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003715 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003716 KeyType::Client,
3717 KeyEntryLoadBits::NONE,
3718 1,
3719 |_k, _av| Ok(()),
3720 )
3721 .unwrap_err()
3722 .root_cause()
3723 .downcast_ref::<KsError>()
3724 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725
3726 Ok(())
3727 }
3728
3729 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003730 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3731 let mut db = new_test_db()?;
3732 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3733 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3734 .0;
3735 // Update the usage count of the limited use key.
3736 db.check_and_update_key_usage_count(key_id)?;
3737
3738 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003739 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003740 KeyType::Client,
3741 KeyEntryLoadBits::BOTH,
3742 1,
3743 |_k, _av| Ok(()),
3744 )?;
3745
3746 // The usage count is decremented now.
3747 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3748
3749 Ok(())
3750 }
3751
3752 #[test]
3753 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3754 let mut db = new_test_db()?;
3755 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3756 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3757 .0;
3758 // Update the usage count of the limited use key.
3759 db.check_and_update_key_usage_count(key_id).expect(concat!(
3760 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3761 "This should succeed."
3762 ));
3763
3764 // Try to update the exhausted limited use key.
3765 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3766 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3767 "This should fail."
3768 ));
3769 assert_eq!(
3770 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3771 e.root_cause().downcast_ref::<KsError>().unwrap()
3772 );
3773
3774 Ok(())
3775 }
3776
3777 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003778 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3779 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003780 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003781 .context("test_insert_and_load_full_keyentry_from_grant")?
3782 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003783
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003784 let granted_key = db
3785 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003786 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003787 domain: Domain::APP,
3788 nspace: 0,
3789 alias: Some(TEST_ALIAS.to_string()),
3790 blob: None,
3791 },
3792 1,
3793 2,
3794 key_perm_set![KeyPerm::use_()],
3795 |_k, _av| Ok(()),
3796 )
3797 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003798
3799 debug_dump_grant_table(&mut db)?;
3800
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003801 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003802 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3803 assert_eq!(Domain::GRANT, k.domain);
3804 assert!(av.unwrap().includes(KeyPerm::use_()));
3805 Ok(())
3806 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003807 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003808
Qi Wub9433b52020-12-01 14:52:46 +08003809 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003810
Janis Danisevskis66784c42021-01-27 08:40:25 -08003811 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003812
3813 assert_eq!(
3814 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3815 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003816 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003817 KeyType::Client,
3818 KeyEntryLoadBits::NONE,
3819 2,
3820 |_k, _av| Ok(()),
3821 )
3822 .unwrap_err()
3823 .root_cause()
3824 .downcast_ref::<KsError>()
3825 );
3826
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003827 Ok(())
3828 }
3829
Janis Danisevskis45760022021-01-19 16:34:10 -08003830 // This test attempts to load a key by key id while the caller is not the owner
3831 // but a grant exists for the given key and the caller.
3832 #[test]
3833 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3834 let mut db = new_test_db()?;
3835 const OWNER_UID: u32 = 1u32;
3836 const GRANTEE_UID: u32 = 2u32;
3837 const SOMEONE_ELSE_UID: u32 = 3u32;
3838 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3839 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3840 .0;
3841
3842 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003843 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003844 domain: Domain::APP,
3845 nspace: 0,
3846 alias: Some(TEST_ALIAS.to_string()),
3847 blob: None,
3848 },
3849 OWNER_UID,
3850 GRANTEE_UID,
3851 key_perm_set![KeyPerm::use_()],
3852 |_k, _av| Ok(()),
3853 )
3854 .unwrap();
3855
3856 debug_dump_grant_table(&mut db)?;
3857
3858 let id_descriptor =
3859 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3860
3861 let (_, key_entry) = db
3862 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003863 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003864 KeyType::Client,
3865 KeyEntryLoadBits::BOTH,
3866 GRANTEE_UID,
3867 |k, av| {
3868 assert_eq!(Domain::APP, k.domain);
3869 assert_eq!(OWNER_UID as i64, k.nspace);
3870 assert!(av.unwrap().includes(KeyPerm::use_()));
3871 Ok(())
3872 },
3873 )
3874 .unwrap();
3875
3876 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3877
3878 let (_, key_entry) = db
3879 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003880 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003881 KeyType::Client,
3882 KeyEntryLoadBits::BOTH,
3883 SOMEONE_ELSE_UID,
3884 |k, av| {
3885 assert_eq!(Domain::APP, k.domain);
3886 assert_eq!(OWNER_UID as i64, k.nspace);
3887 assert!(av.is_none());
3888 Ok(())
3889 },
3890 )
3891 .unwrap();
3892
3893 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3894
Janis Danisevskis66784c42021-01-27 08:40:25 -08003895 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003896
3897 assert_eq!(
3898 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3899 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003900 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003901 KeyType::Client,
3902 KeyEntryLoadBits::NONE,
3903 GRANTEE_UID,
3904 |_k, _av| Ok(()),
3905 )
3906 .unwrap_err()
3907 .root_cause()
3908 .downcast_ref::<KsError>()
3909 );
3910
3911 Ok(())
3912 }
3913
Janis Danisevskisaec14592020-11-12 09:41:49 -08003914 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
3915
Janis Danisevskisaec14592020-11-12 09:41:49 -08003916 #[test]
3917 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
3918 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003919 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
3920 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003921 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08003922 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003923 .context("test_insert_and_load_full_keyentry_domain_app")?
3924 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003925 let (_key_guard, key_entry) = db
3926 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003927 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003928 domain: Domain::APP,
3929 nspace: 0,
3930 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
3931 blob: None,
3932 },
3933 KeyType::Client,
3934 KeyEntryLoadBits::BOTH,
3935 33,
3936 |_k, _av| Ok(()),
3937 )
3938 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003939 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08003940 let state = Arc::new(AtomicU8::new(1));
3941 let state2 = state.clone();
3942
3943 // Spawning a second thread that attempts to acquire the key id lock
3944 // for the same key as the primary thread. The primary thread then
3945 // waits, thereby forcing the secondary thread into the second stage
3946 // of acquiring the lock (see KEY ID LOCK 2/2 above).
3947 // The test succeeds if the secondary thread observes the transition
3948 // of `state` from 1 to 2, despite having a whole second to overtake
3949 // the primary thread.
3950 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003951 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003952 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08003953 assert!(db
3954 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003955 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08003956 domain: Domain::APP,
3957 nspace: 0,
3958 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
3959 blob: None,
3960 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003961 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08003962 KeyEntryLoadBits::BOTH,
3963 33,
3964 |_k, _av| Ok(()),
3965 )
3966 .is_ok());
3967 // We should only see a 2 here because we can only return
3968 // from load_key_entry when the `_key_guard` expires,
3969 // which happens at the end of the scope.
3970 assert_eq!(2, state2.load(Ordering::Relaxed));
3971 });
3972
3973 thread::sleep(std::time::Duration::from_millis(1000));
3974
3975 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
3976
3977 // Return the handle from this scope so we can join with the
3978 // secondary thread after the key id lock has expired.
3979 handle
3980 // This is where the `_key_guard` goes out of scope,
3981 // which is the reason for concurrent load_key_entry on the same key
3982 // to unblock.
3983 };
3984 // Join with the secondary thread and unwrap, to propagate failing asserts to the
3985 // main test thread. We will not see failing asserts in secondary threads otherwise.
3986 handle.join().unwrap();
3987 Ok(())
3988 }
3989
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003990 #[test]
Janis Danisevskis66784c42021-01-27 08:40:25 -08003991 fn teset_database_busy_error_code() {
3992 let temp_dir =
3993 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
3994
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003995 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
3996 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08003997
3998 let _tx1 = db1
3999 .conn
4000 .transaction_with_behavior(TransactionBehavior::Immediate)
4001 .expect("Failed to create first transaction.");
4002
4003 let error = db2
4004 .conn
4005 .transaction_with_behavior(TransactionBehavior::Immediate)
4006 .context("Transaction begin failed.")
4007 .expect_err("This should fail.");
4008 let root_cause = error.root_cause();
4009 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4010 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4011 {
4012 return;
4013 }
4014 panic!(
4015 "Unexpected error {:?} \n{:?} \n{:?}",
4016 error,
4017 root_cause,
4018 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4019 )
4020 }
4021
4022 #[cfg(disabled)]
4023 #[test]
4024 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4025 let temp_dir = Arc::new(
4026 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4027 .expect("Failed to create temp dir."),
4028 );
4029
4030 let test_begin = Instant::now();
4031
4032 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4033 const KEY_COUNT: u32 = 500u32;
4034 const OPEN_DB_COUNT: u32 = 50u32;
4035
4036 let mut actual_key_count = KEY_COUNT;
4037 // First insert KEY_COUNT keys.
4038 for count in 0..KEY_COUNT {
4039 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4040 actual_key_count = count;
4041 break;
4042 }
4043 let alias = format!("test_alias_{}", count);
4044 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4045 .expect("Failed to make key entry.");
4046 }
4047
4048 // Insert more keys from a different thread and into a different namespace.
4049 let temp_dir1 = temp_dir.clone();
4050 let handle1 = thread::spawn(move || {
4051 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4052
4053 for count in 0..actual_key_count {
4054 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4055 return;
4056 }
4057 let alias = format!("test_alias_{}", count);
4058 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4059 .expect("Failed to make key entry.");
4060 }
4061
4062 // then unbind them again.
4063 for count in 0..actual_key_count {
4064 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4065 return;
4066 }
4067 let key = KeyDescriptor {
4068 domain: Domain::APP,
4069 nspace: -1,
4070 alias: Some(format!("test_alias_{}", count)),
4071 blob: None,
4072 };
4073 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4074 }
4075 });
4076
4077 // And start unbinding the first set of keys.
4078 let temp_dir2 = temp_dir.clone();
4079 let handle2 = thread::spawn(move || {
4080 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4081
4082 for count in 0..actual_key_count {
4083 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4084 return;
4085 }
4086 let key = KeyDescriptor {
4087 domain: Domain::APP,
4088 nspace: -1,
4089 alias: Some(format!("test_alias_{}", count)),
4090 blob: None,
4091 };
4092 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4093 }
4094 });
4095
4096 let stop_deleting = Arc::new(AtomicU8::new(0));
4097 let stop_deleting2 = stop_deleting.clone();
4098
4099 // And delete anything that is unreferenced keys.
4100 let temp_dir3 = temp_dir.clone();
4101 let handle3 = thread::spawn(move || {
4102 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4103
4104 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4105 while let Some((key_guard, _key)) =
4106 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4107 {
4108 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4109 return;
4110 }
4111 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4112 }
4113 std::thread::sleep(std::time::Duration::from_millis(100));
4114 }
4115 });
4116
4117 // While a lot of inserting and deleting is going on we have to open database connections
4118 // successfully and use them.
4119 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4120 // out of scope.
4121 #[allow(clippy::redundant_clone)]
4122 let temp_dir4 = temp_dir.clone();
4123 let handle4 = thread::spawn(move || {
4124 for count in 0..OPEN_DB_COUNT {
4125 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4126 return;
4127 }
4128 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4129
4130 let alias = format!("test_alias_{}", count);
4131 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4132 .expect("Failed to make key entry.");
4133 let key = KeyDescriptor {
4134 domain: Domain::APP,
4135 nspace: -1,
4136 alias: Some(alias),
4137 blob: None,
4138 };
4139 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4140 }
4141 });
4142
4143 handle1.join().expect("Thread 1 panicked.");
4144 handle2.join().expect("Thread 2 panicked.");
4145 handle4.join().expect("Thread 4 panicked.");
4146
4147 stop_deleting.store(1, Ordering::Relaxed);
4148 handle3.join().expect("Thread 3 panicked.");
4149
4150 Ok(())
4151 }
4152
4153 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004154 fn list() -> Result<()> {
4155 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004156 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004157 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4158 (Domain::APP, 1, "test1"),
4159 (Domain::APP, 1, "test2"),
4160 (Domain::APP, 1, "test3"),
4161 (Domain::APP, 1, "test4"),
4162 (Domain::APP, 1, "test5"),
4163 (Domain::APP, 1, "test6"),
4164 (Domain::APP, 1, "test7"),
4165 (Domain::APP, 2, "test1"),
4166 (Domain::APP, 2, "test2"),
4167 (Domain::APP, 2, "test3"),
4168 (Domain::APP, 2, "test4"),
4169 (Domain::APP, 2, "test5"),
4170 (Domain::APP, 2, "test6"),
4171 (Domain::APP, 2, "test8"),
4172 (Domain::SELINUX, 100, "test1"),
4173 (Domain::SELINUX, 100, "test2"),
4174 (Domain::SELINUX, 100, "test3"),
4175 (Domain::SELINUX, 100, "test4"),
4176 (Domain::SELINUX, 100, "test5"),
4177 (Domain::SELINUX, 100, "test6"),
4178 (Domain::SELINUX, 100, "test9"),
4179 ];
4180
4181 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4182 .iter()
4183 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004184 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4185 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004186 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4187 });
4188 (entry.id(), *ns)
4189 })
4190 .collect();
4191
4192 for (domain, namespace) in
4193 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4194 {
4195 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4196 .iter()
4197 .filter_map(|(domain, ns, alias)| match ns {
4198 ns if *ns == *namespace => Some(KeyDescriptor {
4199 domain: *domain,
4200 nspace: *ns,
4201 alias: Some(alias.to_string()),
4202 blob: None,
4203 }),
4204 _ => None,
4205 })
4206 .collect();
4207 list_o_descriptors.sort();
4208 let mut list_result = db.list(*domain, *namespace)?;
4209 list_result.sort();
4210 assert_eq!(list_o_descriptors, list_result);
4211
4212 let mut list_o_ids: Vec<i64> = list_o_descriptors
4213 .into_iter()
4214 .map(|d| {
4215 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004216 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004217 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004218 KeyType::Client,
4219 KeyEntryLoadBits::NONE,
4220 *namespace as u32,
4221 |_, _| Ok(()),
4222 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004223 .unwrap();
4224 entry.id()
4225 })
4226 .collect();
4227 list_o_ids.sort_unstable();
4228 let mut loaded_entries: Vec<i64> = list_o_keys
4229 .iter()
4230 .filter_map(|(id, ns)| match ns {
4231 ns if *ns == *namespace => Some(*id),
4232 _ => None,
4233 })
4234 .collect();
4235 loaded_entries.sort_unstable();
4236 assert_eq!(list_o_ids, loaded_entries);
4237 }
4238 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4239
4240 Ok(())
4241 }
4242
Joel Galenson0891bc12020-07-20 10:37:03 -07004243 // Helpers
4244
4245 // Checks that the given result is an error containing the given string.
4246 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4247 let error_str = format!(
4248 "{:#?}",
4249 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4250 );
4251 assert!(
4252 error_str.contains(target),
4253 "The string \"{}\" should contain \"{}\"",
4254 error_str,
4255 target
4256 );
4257 }
4258
Joel Galenson2aab4432020-07-22 15:27:57 -07004259 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004260 #[allow(dead_code)]
4261 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004262 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004263 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004264 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004265 namespace: Option<i64>,
4266 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004267 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004268 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004269 }
4270
4271 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4272 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004273 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004274 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004275 Ok(KeyEntryRow {
4276 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004277 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004278 domain: match row.get(2)? {
4279 Some(i) => Some(Domain(i)),
4280 None => None,
4281 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004282 namespace: row.get(3)?,
4283 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004284 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004285 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004286 })
4287 })?
4288 .map(|r| r.context("Could not read keyentry row."))
4289 .collect::<Result<Vec<_>>>()
4290 }
4291
Max Bires2b2e6562020-09-22 11:22:36 -07004292 fn load_attestation_key_pool(
4293 db: &mut KeystoreDB,
4294 expiration_date: i64,
4295 namespace: i64,
4296 base_byte: u8,
4297 ) -> Result<Vec<Vec<u8>>> {
4298 let mut chain: Vec<Vec<u8>> = Vec::new();
4299 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4300 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4301 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4302 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
4303 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4304 db.store_signed_attestation_certificate_chain(
4305 &raw_public_key,
4306 &cert_chain,
4307 expiration_date,
4308 &KEYSTORE_UUID,
4309 )?;
4310 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
4311 chain.push(public_key);
4312 chain.push(cert_chain);
4313 chain.push(priv_key);
4314 chain.push(raw_public_key);
4315 Ok(chain)
4316 }
4317
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004318 // Note: The parameters and SecurityLevel associations are nonsensical. This
4319 // collection is only used to check if the parameters are preserved as expected by the
4320 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004321 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4322 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004323 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4324 KeyParameter::new(
4325 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4326 SecurityLevel::TRUSTED_ENVIRONMENT,
4327 ),
4328 KeyParameter::new(
4329 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4330 SecurityLevel::TRUSTED_ENVIRONMENT,
4331 ),
4332 KeyParameter::new(
4333 KeyParameterValue::Algorithm(Algorithm::RSA),
4334 SecurityLevel::TRUSTED_ENVIRONMENT,
4335 ),
4336 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4337 KeyParameter::new(
4338 KeyParameterValue::BlockMode(BlockMode::ECB),
4339 SecurityLevel::TRUSTED_ENVIRONMENT,
4340 ),
4341 KeyParameter::new(
4342 KeyParameterValue::BlockMode(BlockMode::GCM),
4343 SecurityLevel::TRUSTED_ENVIRONMENT,
4344 ),
4345 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4346 KeyParameter::new(
4347 KeyParameterValue::Digest(Digest::MD5),
4348 SecurityLevel::TRUSTED_ENVIRONMENT,
4349 ),
4350 KeyParameter::new(
4351 KeyParameterValue::Digest(Digest::SHA_2_224),
4352 SecurityLevel::TRUSTED_ENVIRONMENT,
4353 ),
4354 KeyParameter::new(
4355 KeyParameterValue::Digest(Digest::SHA_2_256),
4356 SecurityLevel::STRONGBOX,
4357 ),
4358 KeyParameter::new(
4359 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4360 SecurityLevel::TRUSTED_ENVIRONMENT,
4361 ),
4362 KeyParameter::new(
4363 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4364 SecurityLevel::TRUSTED_ENVIRONMENT,
4365 ),
4366 KeyParameter::new(
4367 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4368 SecurityLevel::STRONGBOX,
4369 ),
4370 KeyParameter::new(
4371 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4372 SecurityLevel::TRUSTED_ENVIRONMENT,
4373 ),
4374 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4375 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4376 KeyParameter::new(
4377 KeyParameterValue::EcCurve(EcCurve::P_224),
4378 SecurityLevel::TRUSTED_ENVIRONMENT,
4379 ),
4380 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4381 KeyParameter::new(
4382 KeyParameterValue::EcCurve(EcCurve::P_384),
4383 SecurityLevel::TRUSTED_ENVIRONMENT,
4384 ),
4385 KeyParameter::new(
4386 KeyParameterValue::EcCurve(EcCurve::P_521),
4387 SecurityLevel::TRUSTED_ENVIRONMENT,
4388 ),
4389 KeyParameter::new(
4390 KeyParameterValue::RSAPublicExponent(3),
4391 SecurityLevel::TRUSTED_ENVIRONMENT,
4392 ),
4393 KeyParameter::new(
4394 KeyParameterValue::IncludeUniqueID,
4395 SecurityLevel::TRUSTED_ENVIRONMENT,
4396 ),
4397 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4398 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4399 KeyParameter::new(
4400 KeyParameterValue::ActiveDateTime(1234567890),
4401 SecurityLevel::STRONGBOX,
4402 ),
4403 KeyParameter::new(
4404 KeyParameterValue::OriginationExpireDateTime(1234567890),
4405 SecurityLevel::TRUSTED_ENVIRONMENT,
4406 ),
4407 KeyParameter::new(
4408 KeyParameterValue::UsageExpireDateTime(1234567890),
4409 SecurityLevel::TRUSTED_ENVIRONMENT,
4410 ),
4411 KeyParameter::new(
4412 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4413 SecurityLevel::TRUSTED_ENVIRONMENT,
4414 ),
4415 KeyParameter::new(
4416 KeyParameterValue::MaxUsesPerBoot(1234567890),
4417 SecurityLevel::TRUSTED_ENVIRONMENT,
4418 ),
4419 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4420 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4421 KeyParameter::new(
4422 KeyParameterValue::NoAuthRequired,
4423 SecurityLevel::TRUSTED_ENVIRONMENT,
4424 ),
4425 KeyParameter::new(
4426 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4427 SecurityLevel::TRUSTED_ENVIRONMENT,
4428 ),
4429 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4430 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4431 KeyParameter::new(
4432 KeyParameterValue::TrustedUserPresenceRequired,
4433 SecurityLevel::TRUSTED_ENVIRONMENT,
4434 ),
4435 KeyParameter::new(
4436 KeyParameterValue::TrustedConfirmationRequired,
4437 SecurityLevel::TRUSTED_ENVIRONMENT,
4438 ),
4439 KeyParameter::new(
4440 KeyParameterValue::UnlockedDeviceRequired,
4441 SecurityLevel::TRUSTED_ENVIRONMENT,
4442 ),
4443 KeyParameter::new(
4444 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4445 SecurityLevel::SOFTWARE,
4446 ),
4447 KeyParameter::new(
4448 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4449 SecurityLevel::SOFTWARE,
4450 ),
4451 KeyParameter::new(
4452 KeyParameterValue::CreationDateTime(12345677890),
4453 SecurityLevel::SOFTWARE,
4454 ),
4455 KeyParameter::new(
4456 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4457 SecurityLevel::TRUSTED_ENVIRONMENT,
4458 ),
4459 KeyParameter::new(
4460 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4461 SecurityLevel::TRUSTED_ENVIRONMENT,
4462 ),
4463 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4464 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4465 KeyParameter::new(
4466 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4467 SecurityLevel::SOFTWARE,
4468 ),
4469 KeyParameter::new(
4470 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4471 SecurityLevel::TRUSTED_ENVIRONMENT,
4472 ),
4473 KeyParameter::new(
4474 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4475 SecurityLevel::TRUSTED_ENVIRONMENT,
4476 ),
4477 KeyParameter::new(
4478 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4479 SecurityLevel::TRUSTED_ENVIRONMENT,
4480 ),
4481 KeyParameter::new(
4482 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4483 SecurityLevel::TRUSTED_ENVIRONMENT,
4484 ),
4485 KeyParameter::new(
4486 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4487 SecurityLevel::TRUSTED_ENVIRONMENT,
4488 ),
4489 KeyParameter::new(
4490 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4491 SecurityLevel::TRUSTED_ENVIRONMENT,
4492 ),
4493 KeyParameter::new(
4494 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4495 SecurityLevel::TRUSTED_ENVIRONMENT,
4496 ),
4497 KeyParameter::new(
4498 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4499 SecurityLevel::TRUSTED_ENVIRONMENT,
4500 ),
4501 KeyParameter::new(
4502 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4503 SecurityLevel::TRUSTED_ENVIRONMENT,
4504 ),
4505 KeyParameter::new(
4506 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4507 SecurityLevel::TRUSTED_ENVIRONMENT,
4508 ),
4509 KeyParameter::new(
4510 KeyParameterValue::VendorPatchLevel(3),
4511 SecurityLevel::TRUSTED_ENVIRONMENT,
4512 ),
4513 KeyParameter::new(
4514 KeyParameterValue::BootPatchLevel(4),
4515 SecurityLevel::TRUSTED_ENVIRONMENT,
4516 ),
4517 KeyParameter::new(
4518 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4519 SecurityLevel::TRUSTED_ENVIRONMENT,
4520 ),
4521 KeyParameter::new(
4522 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4523 SecurityLevel::TRUSTED_ENVIRONMENT,
4524 ),
4525 KeyParameter::new(
4526 KeyParameterValue::MacLength(256),
4527 SecurityLevel::TRUSTED_ENVIRONMENT,
4528 ),
4529 KeyParameter::new(
4530 KeyParameterValue::ResetSinceIdRotation,
4531 SecurityLevel::TRUSTED_ENVIRONMENT,
4532 ),
4533 KeyParameter::new(
4534 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4535 SecurityLevel::TRUSTED_ENVIRONMENT,
4536 ),
Qi Wub9433b52020-12-01 14:52:46 +08004537 ];
4538 if let Some(value) = max_usage_count {
4539 params.push(KeyParameter::new(
4540 KeyParameterValue::UsageCountLimit(value),
4541 SecurityLevel::SOFTWARE,
4542 ));
4543 }
4544 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004545 }
4546
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004547 fn make_test_key_entry(
4548 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004549 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004550 namespace: i64,
4551 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004552 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004553 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004554 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004555 let mut blob_metadata = BlobMetaData::new();
4556 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4557 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4558 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4559 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4560 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4561
4562 db.set_blob(
4563 &key_id,
4564 SubComponentType::KEY_BLOB,
4565 Some(TEST_KEY_BLOB),
4566 Some(&blob_metadata),
4567 )?;
4568 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4569 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004570
4571 let params = make_test_params(max_usage_count);
4572 db.insert_keyparameter(&key_id, &params)?;
4573
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004574 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004575 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004576 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004577 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004578 Ok(key_id)
4579 }
4580
Qi Wub9433b52020-12-01 14:52:46 +08004581 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4582 let params = make_test_params(max_usage_count);
4583
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004584 let mut blob_metadata = BlobMetaData::new();
4585 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4586 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4587 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4588 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4589 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4590
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004591 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004592 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004593
4594 KeyEntry {
4595 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004596 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004597 cert: Some(TEST_CERT_BLOB.to_vec()),
4598 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004599 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004600 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004601 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004602 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004603 }
4604 }
4605
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004606 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004607 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004608 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004609 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004610 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004611 NO_PARAMS,
4612 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004613 Ok((
4614 row.get(0)?,
4615 row.get(1)?,
4616 row.get(2)?,
4617 row.get(3)?,
4618 row.get(4)?,
4619 row.get(5)?,
4620 row.get(6)?,
4621 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004622 },
4623 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004624
4625 println!("Key entry table rows:");
4626 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004627 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004628 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004629 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4630 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004631 );
4632 }
4633 Ok(())
4634 }
4635
4636 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004637 let mut stmt = db
4638 .conn
4639 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004640 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
4641 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4642 })?;
4643
4644 println!("Grant table rows:");
4645 for r in rows {
4646 let (id, gt, ki, av) = r.unwrap();
4647 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4648 }
4649 Ok(())
4650 }
4651
Joel Galenson0891bc12020-07-20 10:37:03 -07004652 // Use a custom random number generator that repeats each number once.
4653 // This allows us to test repeated elements.
4654
4655 thread_local! {
4656 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4657 }
4658
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004659 fn reset_random() {
4660 RANDOM_COUNTER.with(|counter| {
4661 *counter.borrow_mut() = 0;
4662 })
4663 }
4664
Joel Galenson0891bc12020-07-20 10:37:03 -07004665 pub fn random() -> i64 {
4666 RANDOM_COUNTER.with(|counter| {
4667 let result = *counter.borrow() / 2;
4668 *counter.borrow_mut() += 1;
4669 result
4670 })
4671 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004672
4673 #[test]
4674 fn test_last_off_body() -> Result<()> {
4675 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08004676 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004677 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4678 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
4679 tx.commit()?;
4680 let one_second = Duration::from_secs(1);
4681 thread::sleep(one_second);
4682 db.update_last_off_body(MonotonicRawTime::now())?;
4683 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4684 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
4685 tx2.commit()?;
4686 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
4687 Ok(())
4688 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00004689
4690 #[test]
4691 fn test_unbind_keys_for_user() -> Result<()> {
4692 let mut db = new_test_db()?;
4693 db.unbind_keys_for_user(1, false)?;
4694
4695 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4696 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4697 db.unbind_keys_for_user(2, false)?;
4698
4699 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
4700 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
4701
4702 db.unbind_keys_for_user(1, true)?;
4703 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
4704
4705 Ok(())
4706 }
4707
4708 #[test]
4709 fn test_store_super_key() -> Result<()> {
4710 let mut db = new_test_db()?;
4711 let pw = "xyzabc".as_bytes();
4712 let super_key = keystore2_crypto::generate_aes256_key()?;
4713 let secret = String::from("keystore2 is great.");
4714 let secret_bytes = secret.into_bytes();
4715 let (encrypted_secret, iv, tag) =
4716 keystore2_crypto::aes_gcm_encrypt(&secret_bytes, &super_key)?;
4717
4718 let (encrypted_super_key, metadata) =
4719 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4720 db.store_super_key(1, &(&encrypted_super_key, &metadata))?;
4721
4722 //load the super key from the database
4723 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4724 let key_descriptor = KeyDescriptor {
4725 domain: Domain::APP,
4726 nspace: 1,
4727 alias: Some(String::from("USER_SUPER_KEY")),
4728 blob: None,
4729 };
4730 let id = KeystoreDB::load_key_entry_id(&tx, &key_descriptor, KeyType::Super)?;
4731 let key_entry = KeystoreDB::load_key_components(&tx, KeyEntryLoadBits::KM, id)?;
4732 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(key_entry, &pw)?;
4733
4734 let decrypted_secret_bytes = keystore2_crypto::aes_gcm_decrypt(
4735 &encrypted_secret,
4736 &iv,
4737 &tag,
4738 &loaded_super_key.get_key(),
4739 )?;
4740 let decrypted_secret = String::from_utf8((&decrypted_secret_bytes).to_vec())?;
4741 assert_eq!(String::from("keystore2 is great."), decrypted_secret);
4742 Ok(())
4743 }
Joel Galenson26f4d012020-07-17 14:57:21 -07004744}