blob: c35956fef59bca654fe9231f60d066b1cc70cdb2 [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Jeff Vander Stoep46bbc612021-04-09 08:55:21 +020044#![allow(clippy::needless_question_mark)]
45
Janis Danisevskisb42fc182020-12-15 08:41:27 -080046use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080047use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070048use crate::permission::KeyPermSet;
Hasini Gunasingheda895552021-01-27 19:34:37 +000049use crate::utils::{get_current_time_in_seconds, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080050use crate::{
51 db_utils::{self, SqlField},
52 gc::Gc,
Paul Crowley7a658392021-03-18 17:08:20 -070053 super_key::USER_SUPER_KEY,
54};
55use crate::{
56 error::{Error as KsError, ErrorCode, ResponseCode},
57 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080058};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080059use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080060use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070061
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080063 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080065};
66use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000067 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000068};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070069use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070070 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070071};
Max Bires2b2e6562020-09-22 11:22:36 -070072use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
73 AttestationPoolStatus::AttestationPoolStatus,
74};
75
76use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080077use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000078use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070079#[cfg(not(test))]
80use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070081use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080082 params,
83 types::FromSql,
84 types::FromSqlResult,
85 types::ToSqlOutput,
86 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080087 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070088};
Max Bires2b2e6562020-09-22 11:22:36 -070089
Janis Danisevskisaec14592020-11-12 09:41:49 -080090use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080091 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080092 path::Path,
93 sync::{Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080095};
Max Bires2b2e6562020-09-22 11:22:36 -070096
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800100impl_metadata!(
101 /// A set of metadata for key entries.
102 #[derive(Debug, Default, Eq, PartialEq)]
103 pub struct KeyMetaData;
104 /// A metadata entry for key entries.
105 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
106 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800107 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800108 CreationDate(DateTime) with accessor creation_date,
109 /// Expiration date for attestation keys.
110 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700111 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
112 /// provisioning
113 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
114 /// Vector representing the raw public key so results from the server can be matched
115 /// to the right entry
116 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700117 /// SEC1 public key for ECDH encryption
118 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800119 // --- ADD NEW META DATA FIELDS HERE ---
120 // For backwards compatibility add new entries only to
121 // end of this list and above this comment.
122 };
123);
124
125impl KeyMetaData {
126 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
127 let mut stmt = tx
128 .prepare(
129 "SELECT tag, data from persistent.keymetadata
130 WHERE keyentryid = ?;",
131 )
132 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
133
134 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
135
136 let mut rows =
137 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
138 db_utils::with_rows_extract_all(&mut rows, |row| {
139 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
140 metadata.insert(
141 db_tag,
142 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
143 .context("Failed to read KeyMetaEntry.")?,
144 );
145 Ok(())
146 })
147 .context("In KeyMetaData::load_from_db.")?;
148
149 Ok(Self { data: metadata })
150 }
151
152 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
153 let mut stmt = tx
154 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000155 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800156 VALUES (?, ?, ?);",
157 )
158 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
159
160 let iter = self.data.iter();
161 for (tag, entry) in iter {
162 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
163 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
164 })?;
165 }
166 Ok(())
167 }
168}
169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170impl_metadata!(
171 /// A set of metadata for key blobs.
172 #[derive(Debug, Default, Eq, PartialEq)]
173 pub struct BlobMetaData;
174 /// A metadata entry for key blobs.
175 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
176 pub enum BlobMetaEntry {
177 /// If present, indicates that the blob is encrypted with another key or a key derived
178 /// from a password.
179 EncryptedBy(EncryptedBy) with accessor encrypted_by,
180 /// If the blob is password encrypted this field is set to the
181 /// salt used for the key derivation.
182 Salt(Vec<u8>) with accessor salt,
183 /// If the blob is encrypted, this field is set to the initialization vector.
184 Iv(Vec<u8>) with accessor iv,
185 /// If the blob is encrypted, this field holds the AEAD TAG.
186 AeadTag(Vec<u8>) with accessor aead_tag,
187 /// The uuid of the owning KeyMint instance.
188 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700189 /// If the key is ECDH encrypted, this is the ephemeral public key
190 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000191 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
192 /// of that key
193 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800194 // --- ADD NEW META DATA FIELDS HERE ---
195 // For backwards compatibility add new entries only to
196 // end of this list and above this comment.
197 };
198);
199
200impl BlobMetaData {
201 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
202 let mut stmt = tx
203 .prepare(
204 "SELECT tag, data from persistent.blobmetadata
205 WHERE blobentryid = ?;",
206 )
207 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
208
209 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
210
211 let mut rows =
212 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
213 db_utils::with_rows_extract_all(&mut rows, |row| {
214 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
215 metadata.insert(
216 db_tag,
217 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
218 .context("Failed to read BlobMetaEntry.")?,
219 );
220 Ok(())
221 })
222 .context("In BlobMetaData::load_from_db.")?;
223
224 Ok(Self { data: metadata })
225 }
226
227 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
228 let mut stmt = tx
229 .prepare(
230 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
231 VALUES (?, ?, ?);",
232 )
233 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
234
235 let iter = self.data.iter();
236 for (tag, entry) in iter {
237 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
238 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
239 })?;
240 }
241 Ok(())
242 }
243}
244
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800245/// Indicates the type of the keyentry.
246#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
247pub enum KeyType {
248 /// This is a client key type. These keys are created or imported through the Keystore 2.0
249 /// AIDL interface android.system.keystore2.
250 Client,
251 /// This is a super key type. These keys are created by keystore itself and used to encrypt
252 /// other key blobs to provide LSKF binding.
253 Super,
254 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
255 Attestation,
256}
257
258impl ToSql for KeyType {
259 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
260 Ok(ToSqlOutput::Owned(Value::Integer(match self {
261 KeyType::Client => 0,
262 KeyType::Super => 1,
263 KeyType::Attestation => 2,
264 })))
265 }
266}
267
268impl FromSql for KeyType {
269 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
270 match i64::column_result(value)? {
271 0 => Ok(KeyType::Client),
272 1 => Ok(KeyType::Super),
273 2 => Ok(KeyType::Attestation),
274 v => Err(FromSqlError::OutOfRange(v)),
275 }
276 }
277}
278
Max Bires8e93d2b2021-01-14 13:17:59 -0800279/// Uuid representation that can be stored in the database.
280/// Right now it can only be initialized from SecurityLevel.
281/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
282#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
283pub struct Uuid([u8; 16]);
284
285impl Deref for Uuid {
286 type Target = [u8; 16];
287
288 fn deref(&self) -> &Self::Target {
289 &self.0
290 }
291}
292
293impl From<SecurityLevel> for Uuid {
294 fn from(sec_level: SecurityLevel) -> Self {
295 Self((sec_level.0 as u128).to_be_bytes())
296 }
297}
298
299impl ToSql for Uuid {
300 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
301 self.0.to_sql()
302 }
303}
304
305impl FromSql for Uuid {
306 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
307 let blob = Vec::<u8>::column_result(value)?;
308 if blob.len() != 16 {
309 return Err(FromSqlError::OutOfRange(blob.len() as i64));
310 }
311 let mut arr = [0u8; 16];
312 arr.copy_from_slice(&blob);
313 Ok(Self(arr))
314 }
315}
316
317/// Key entries that are not associated with any KeyMint instance, such as pure certificate
318/// entries are associated with this UUID.
319pub static KEYSTORE_UUID: Uuid = Uuid([
320 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
321]);
322
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800323/// Indicates how the sensitive part of this key blob is encrypted.
324#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
325pub enum EncryptedBy {
326 /// The keyblob is encrypted by a user password.
327 /// In the database this variant is represented as NULL.
328 Password,
329 /// The keyblob is encrypted by another key with wrapped key id.
330 /// In the database this variant is represented as non NULL value
331 /// that is convertible to i64, typically NUMERIC.
332 KeyId(i64),
333}
334
335impl ToSql for EncryptedBy {
336 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
337 match self {
338 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
339 Self::KeyId(id) => id.to_sql(),
340 }
341 }
342}
343
344impl FromSql for EncryptedBy {
345 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
346 match value {
347 ValueRef::Null => Ok(Self::Password),
348 _ => Ok(Self::KeyId(i64::column_result(value)?)),
349 }
350 }
351}
352
353/// A database representation of wall clock time. DateTime stores unix epoch time as
354/// i64 in milliseconds.
355#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
356pub struct DateTime(i64);
357
358/// Error type returned when creating DateTime or converting it from and to
359/// SystemTime.
360#[derive(thiserror::Error, Debug)]
361pub enum DateTimeError {
362 /// This is returned when SystemTime and Duration computations fail.
363 #[error(transparent)]
364 SystemTimeError(#[from] SystemTimeError),
365
366 /// This is returned when type conversions fail.
367 #[error(transparent)]
368 TypeConversion(#[from] std::num::TryFromIntError),
369
370 /// This is returned when checked time arithmetic failed.
371 #[error("Time arithmetic failed.")]
372 TimeArithmetic,
373}
374
375impl DateTime {
376 /// Constructs a new DateTime object denoting the current time. This may fail during
377 /// conversion to unix epoch time and during conversion to the internal i64 representation.
378 pub fn now() -> Result<Self, DateTimeError> {
379 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
380 }
381
382 /// Constructs a new DateTime object from milliseconds.
383 pub fn from_millis_epoch(millis: i64) -> Self {
384 Self(millis)
385 }
386
387 /// Returns unix epoch time in milliseconds.
388 pub fn to_millis_epoch(&self) -> i64 {
389 self.0
390 }
391
392 /// Returns unix epoch time in seconds.
393 pub fn to_secs_epoch(&self) -> i64 {
394 self.0 / 1000
395 }
396}
397
398impl ToSql for DateTime {
399 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
400 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
401 }
402}
403
404impl FromSql for DateTime {
405 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
406 Ok(Self(i64::column_result(value)?))
407 }
408}
409
410impl TryInto<SystemTime> for DateTime {
411 type Error = DateTimeError;
412
413 fn try_into(self) -> Result<SystemTime, Self::Error> {
414 // We want to construct a SystemTime representation equivalent to self, denoting
415 // a point in time THEN, but we cannot set the time directly. We can only construct
416 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
417 // and between EPOCH and THEN. With this common reference we can construct the
418 // duration between NOW and THEN which we can add to our SystemTime representation
419 // of NOW to get a SystemTime representation of THEN.
420 // Durations can only be positive, thus the if statement below.
421 let now = SystemTime::now();
422 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
423 let then_epoch = Duration::from_millis(self.0.try_into()?);
424 Ok(if now_epoch > then_epoch {
425 // then = now - (now_epoch - then_epoch)
426 now_epoch
427 .checked_sub(then_epoch)
428 .and_then(|d| now.checked_sub(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 } else {
431 // then = now + (then_epoch - now_epoch)
432 then_epoch
433 .checked_sub(now_epoch)
434 .and_then(|d| now.checked_add(d))
435 .ok_or(DateTimeError::TimeArithmetic)?
436 })
437 }
438}
439
440impl TryFrom<SystemTime> for DateTime {
441 type Error = DateTimeError;
442
443 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
444 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
445 }
446}
447
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800448#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
449enum KeyLifeCycle {
450 /// Existing keys have a key ID but are not fully populated yet.
451 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
452 /// them to Unreferenced for garbage collection.
453 Existing,
454 /// A live key is fully populated and usable by clients.
455 Live,
456 /// An unreferenced key is scheduled for garbage collection.
457 Unreferenced,
458}
459
460impl ToSql for KeyLifeCycle {
461 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
462 match self {
463 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
464 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
465 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
466 }
467 }
468}
469
470impl FromSql for KeyLifeCycle {
471 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
472 match i64::column_result(value)? {
473 0 => Ok(KeyLifeCycle::Existing),
474 1 => Ok(KeyLifeCycle::Live),
475 2 => Ok(KeyLifeCycle::Unreferenced),
476 v => Err(FromSqlError::OutOfRange(v)),
477 }
478 }
479}
480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700481/// Keys have a KeyMint blob component and optional public certificate and
482/// certificate chain components.
483/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
484/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800485#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700486pub struct KeyEntryLoadBits(u32);
487
488impl KeyEntryLoadBits {
489 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
490 pub const NONE: KeyEntryLoadBits = Self(0);
491 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
492 pub const KM: KeyEntryLoadBits = Self(1);
493 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
494 pub const PUBLIC: KeyEntryLoadBits = Self(2);
495 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
496 pub const BOTH: KeyEntryLoadBits = Self(3);
497
498 /// Returns true if this object indicates that the public components shall be loaded.
499 pub const fn load_public(&self) -> bool {
500 self.0 & Self::PUBLIC.0 != 0
501 }
502
503 /// Returns true if the object indicates that the KeyMint component shall be loaded.
504 pub const fn load_km(&self) -> bool {
505 self.0 & Self::KM.0 != 0
506 }
507}
508
Janis Danisevskisaec14592020-11-12 09:41:49 -0800509lazy_static! {
510 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
511}
512
513struct KeyIdLockDb {
514 locked_keys: Mutex<HashSet<i64>>,
515 cond_var: Condvar,
516}
517
518/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
519/// from the database a second time. Most functions manipulating the key blob database
520/// require a KeyIdGuard.
521#[derive(Debug)]
522pub struct KeyIdGuard(i64);
523
524impl KeyIdLockDb {
525 fn new() -> Self {
526 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
527 }
528
529 /// This function blocks until an exclusive lock for the given key entry id can
530 /// be acquired. It returns a guard object, that represents the lifecycle of the
531 /// acquired lock.
532 pub fn get(&self, key_id: i64) -> KeyIdGuard {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 while locked_keys.contains(&key_id) {
535 locked_keys = self.cond_var.wait(locked_keys).unwrap();
536 }
537 locked_keys.insert(key_id);
538 KeyIdGuard(key_id)
539 }
540
541 /// This function attempts to acquire an exclusive lock on a given key id. If the
542 /// given key id is already taken the function returns None immediately. If a lock
543 /// can be acquired this function returns a guard object, that represents the
544 /// lifecycle of the acquired lock.
545 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
546 let mut locked_keys = self.locked_keys.lock().unwrap();
547 if locked_keys.insert(key_id) {
548 Some(KeyIdGuard(key_id))
549 } else {
550 None
551 }
552 }
553}
554
555impl KeyIdGuard {
556 /// Get the numeric key id of the locked key.
557 pub fn id(&self) -> i64 {
558 self.0
559 }
560}
561
562impl Drop for KeyIdGuard {
563 fn drop(&mut self) {
564 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
565 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800566 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800567 KEY_ID_LOCK.cond_var.notify_all();
568 }
569}
570
Max Bires8e93d2b2021-01-14 13:17:59 -0800571/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700572#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800573pub struct CertificateInfo {
574 cert: Option<Vec<u8>>,
575 cert_chain: Option<Vec<u8>>,
576}
577
578impl CertificateInfo {
579 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
580 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
581 Self { cert, cert_chain }
582 }
583
584 /// Take the cert
585 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
586 self.cert.take()
587 }
588
589 /// Take the cert chain
590 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
591 self.cert_chain.take()
592 }
593}
594
Max Bires2b2e6562020-09-22 11:22:36 -0700595/// This type represents a certificate chain with a private key corresponding to the leaf
596/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
Max Bires2b2e6562020-09-22 11:22:36 -0700597pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800598 /// A KM key blob
599 pub private_key: ZVec,
600 /// A batch cert for private_key
601 pub batch_cert: Vec<u8>,
602 /// A full certificate chain from root signing authority to private_key, including batch_cert
603 /// for convenience.
604 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700605}
606
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700607/// This type represents a Keystore 2.0 key entry.
608/// An entry has a unique `id` by which it can be found in the database.
609/// It has a security level field, key parameters, and three optional fields
610/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800611#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700612pub struct KeyEntry {
613 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800614 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615 cert: Option<Vec<u8>>,
616 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800617 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700618 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800619 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800620 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700621}
622
623impl KeyEntry {
624 /// Returns the unique id of the Key entry.
625 pub fn id(&self) -> i64 {
626 self.id
627 }
628 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800629 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
630 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 /// Extracts the Optional KeyMint blob including its metadata.
633 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
634 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700635 }
636 /// Exposes the optional public certificate.
637 pub fn cert(&self) -> &Option<Vec<u8>> {
638 &self.cert
639 }
640 /// Extracts the optional public certificate.
641 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
642 self.cert.take()
643 }
644 /// Exposes the optional public certificate chain.
645 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
646 &self.cert_chain
647 }
648 /// Extracts the optional public certificate_chain.
649 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
650 self.cert_chain.take()
651 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800652 /// Returns the uuid of the owning KeyMint instance.
653 pub fn km_uuid(&self) -> &Uuid {
654 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700656 /// Exposes the key parameters of this key entry.
657 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
658 &self.parameters
659 }
660 /// Consumes this key entry and extracts the keyparameters from it.
661 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
662 self.parameters
663 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800664 /// Exposes the key metadata of this key entry.
665 pub fn metadata(&self) -> &KeyMetaData {
666 &self.metadata
667 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800668 /// This returns true if the entry is a pure certificate entry with no
669 /// private key component.
670 pub fn pure_cert(&self) -> bool {
671 self.pure_cert
672 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000673 /// Consumes this key entry and extracts the keyparameters and metadata from it.
674 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
675 (self.parameters, self.metadata)
676 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700677}
678
679/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800680#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681pub struct SubComponentType(u32);
682impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800683 /// Persistent identifier for a key blob.
684 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700685 /// Persistent identifier for a certificate blob.
686 pub const CERT: SubComponentType = Self(1);
687 /// Persistent identifier for a certificate chain blob.
688 pub const CERT_CHAIN: SubComponentType = Self(2);
689}
690
691impl ToSql for SubComponentType {
692 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
693 self.0.to_sql()
694 }
695}
696
697impl FromSql for SubComponentType {
698 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
699 Ok(Self(u32::column_result(value)?))
700 }
701}
702
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800703/// This trait is private to the database module. It is used to convey whether or not the garbage
704/// collector shall be invoked after a database access. All closures passed to
705/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
706/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
707/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
708/// `.need_gc()`.
709trait DoGc<T> {
710 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
711
712 fn no_gc(self) -> Result<(bool, T)>;
713
714 fn need_gc(self) -> Result<(bool, T)>;
715}
716
717impl<T> DoGc<T> for Result<T> {
718 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
719 self.map(|r| (need_gc, r))
720 }
721
722 fn no_gc(self) -> Result<(bool, T)> {
723 self.do_gc(false)
724 }
725
726 fn need_gc(self) -> Result<(bool, T)> {
727 self.do_gc(true)
728 }
729}
730
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700731/// KeystoreDB wraps a connection to an SQLite database and tracks its
732/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700733pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700734 conn: Connection,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800735 gc: Option<Gc>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700736}
737
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000738/// Database representation of the monotonic time retrieved from the system call clock_gettime with
739/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
740#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
741pub struct MonotonicRawTime(i64);
742
743impl MonotonicRawTime {
744 /// Constructs a new MonotonicRawTime
745 pub fn now() -> Self {
746 Self(get_current_time_in_seconds())
747 }
748
David Drysdale0e45a612021-02-25 17:24:36 +0000749 /// Constructs a new MonotonicRawTime from a given number of seconds.
750 pub fn from_secs(val: i64) -> Self {
751 Self(val)
752 }
753
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000754 /// Returns the integer value of MonotonicRawTime as i64
755 pub fn seconds(&self) -> i64 {
756 self.0
757 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800758
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000759 /// Returns the value of MonotonicRawTime in milli seconds as i64
760 pub fn milli_seconds(&self) -> i64 {
761 self.0 * 1000
762 }
763
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800764 /// Like i64::checked_sub.
765 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
766 self.0.checked_sub(other.0).map(Self)
767 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000768}
769
770impl ToSql for MonotonicRawTime {
771 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
772 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
773 }
774}
775
776impl FromSql for MonotonicRawTime {
777 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
778 Ok(Self(i64::column_result(value)?))
779 }
780}
781
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000782/// This struct encapsulates the information to be stored in the database about the auth tokens
783/// received by keystore.
784pub struct AuthTokenEntry {
785 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000786 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000787}
788
789impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000790 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000791 AuthTokenEntry { auth_token, time_received }
792 }
793
794 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800795 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000796 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800797 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
798 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000799 })
800 }
801
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000802 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800803 pub fn auth_token(&self) -> &HardwareAuthToken {
804 &self.auth_token
805 }
806
807 /// Returns the auth token wrapped by the AuthTokenEntry
808 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000809 self.auth_token
810 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800811
812 /// Returns the time that this auth token was received.
813 pub fn time_received(&self) -> MonotonicRawTime {
814 self.time_received
815 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000816
817 /// Returns the challenge value of the auth token.
818 pub fn challenge(&self) -> i64 {
819 self.auth_token.challenge
820 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000821}
822
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800823/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
824/// This object does not allow access to the database connection. But it keeps a database
825/// connection alive in order to keep the in memory per boot database alive.
826pub struct PerBootDbKeepAlive(Connection);
827
Joel Galenson26f4d012020-07-17 14:57:21 -0700828impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800829 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800830 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
831
832 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
833 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
834 let conn = Connection::open_in_memory()
835 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
836
837 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
838 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
839 Ok(PerBootDbKeepAlive(conn))
840 }
841
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700842 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800843 /// files persistent.sqlite and perboot.sqlite in the given directory.
844 /// It also attempts to initialize all of the tables.
845 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700846 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800847 pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800848 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800849 let mut persistent_path = db_root.to_path_buf();
850 persistent_path.push("persistent.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700851
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800852 // Now convert them to strings prefixed with "file:"
853 let mut persistent_path_str = "file:".to_owned();
854 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800855
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800856 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800857
Janis Danisevskis66784c42021-01-27 08:40:25 -0800858 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
859 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
860
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800861 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800862 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800863 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800864 })?;
865 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700866 }
867
Janis Danisevskis66784c42021-01-27 08:40:25 -0800868 fn init_tables(tx: &Transaction) -> Result<()> {
869 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700870 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700871 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800872 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700873 domain INTEGER,
874 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800875 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800876 state INTEGER,
877 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700878 NO_PARAMS,
879 )
880 .context("Failed to initialize \"keyentry\" table.")?;
881
Janis Danisevskis66784c42021-01-27 08:40:25 -0800882 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800883 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
884 ON keyentry(id);",
885 NO_PARAMS,
886 )
887 .context("Failed to create index keyentry_id_index.")?;
888
889 tx.execute(
890 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
891 ON keyentry(domain, namespace, alias);",
892 NO_PARAMS,
893 )
894 .context("Failed to create index keyentry_domain_namespace_index.")?;
895
896 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700897 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
898 id INTEGER PRIMARY KEY,
899 subcomponent_type INTEGER,
900 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800901 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700902 NO_PARAMS,
903 )
904 .context("Failed to initialize \"blobentry\" table.")?;
905
Janis Danisevskis66784c42021-01-27 08:40:25 -0800906 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800907 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
908 ON blobentry(keyentryid);",
909 NO_PARAMS,
910 )
911 .context("Failed to create index blobentry_keyentryid_index.")?;
912
913 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800914 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
915 id INTEGER PRIMARY KEY,
916 blobentryid INTEGER,
917 tag INTEGER,
918 data ANY,
919 UNIQUE (blobentryid, tag));",
920 NO_PARAMS,
921 )
922 .context("Failed to initialize \"blobmetadata\" table.")?;
923
924 tx.execute(
925 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
926 ON blobmetadata(blobentryid);",
927 NO_PARAMS,
928 )
929 .context("Failed to create index blobmetadata_blobentryid_index.")?;
930
931 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700932 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000933 keyentryid INTEGER,
934 tag INTEGER,
935 data ANY,
936 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700937 NO_PARAMS,
938 )
939 .context("Failed to initialize \"keyparameter\" table.")?;
940
Janis Danisevskis66784c42021-01-27 08:40:25 -0800941 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800942 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
943 ON keyparameter(keyentryid);",
944 NO_PARAMS,
945 )
946 .context("Failed to create index keyparameter_keyentryid_index.")?;
947
948 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800949 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
950 keyentryid INTEGER,
951 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000952 data ANY,
953 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800954 NO_PARAMS,
955 )
956 .context("Failed to initialize \"keymetadata\" table.")?;
957
Janis Danisevskis66784c42021-01-27 08:40:25 -0800958 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800959 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
960 ON keymetadata(keyentryid);",
961 NO_PARAMS,
962 )
963 .context("Failed to create index keymetadata_keyentryid_index.")?;
964
965 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800966 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700967 id INTEGER UNIQUE,
968 grantee INTEGER,
969 keyentryid INTEGER,
970 access_vector INTEGER);",
971 NO_PARAMS,
972 )
973 .context("Failed to initialize \"grant\" table.")?;
974
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000975 //TODO: only drop the following two perboot tables if this is the first start up
976 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800977 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000978 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800979 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000980 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
981 id INTEGER PRIMARY KEY,
982 challenge INTEGER,
983 user_id INTEGER,
984 auth_id INTEGER,
985 authenticator_type INTEGER,
986 timestamp INTEGER,
987 mac BLOB,
988 time_received INTEGER,
989 UNIQUE(user_id, auth_id, authenticator_type));",
990 NO_PARAMS,
991 )
992 .context("Failed to initialize \"authtoken\" table.")?;
993
Janis Danisevskis66784c42021-01-27 08:40:25 -0800994 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000995 // .context("Failed to drop perboot.metadata table")?;
996 // metadata table stores certain miscellaneous information required for keystore functioning
997 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800998 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000999 "CREATE TABLE IF NOT EXISTS perboot.metadata (
1000 key TEXT,
1001 value BLOB,
1002 UNIQUE(key));",
1003 NO_PARAMS,
1004 )
1005 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -07001006 Ok(())
1007 }
1008
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001009 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
1010 let conn =
1011 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1012
Janis Danisevskis66784c42021-01-27 08:40:25 -08001013 loop {
1014 if let Err(e) = conn
1015 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1016 .context("Failed to attach database persistent.")
1017 {
1018 if Self::is_locked_error(&e) {
1019 std::thread::sleep(std::time::Duration::from_micros(500));
1020 continue;
1021 } else {
1022 return Err(e);
1023 }
1024 }
1025 break;
1026 }
1027 loop {
1028 if let Err(e) = conn
1029 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1030 .context("Failed to attach database perboot.")
1031 {
1032 if Self::is_locked_error(&e) {
1033 std::thread::sleep(std::time::Duration::from_micros(500));
1034 continue;
1035 } else {
1036 return Err(e);
1037 }
1038 }
1039 break;
1040 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001041
1042 Ok(conn)
1043 }
1044
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001045 /// This function is intended to be used by the garbage collector.
1046 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1047 /// key blob that might need special handling by the garbage collector.
1048 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1049 /// need special handling and returns None.
1050 pub fn handle_next_superseded_blob(
1051 &mut self,
1052 blob_id_to_delete: Option<i64>,
1053 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001054 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001055 // Delete the given blob if one was given.
1056 if let Some(blob_id_to_delete) = blob_id_to_delete {
1057 tx.execute(
1058 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1059 params![blob_id_to_delete],
1060 )
1061 .context("Trying to delete blob metadata.")?;
1062 tx.execute(
1063 "DELETE FROM persistent.blobentry WHERE id = ?;",
1064 params![blob_id_to_delete],
1065 )
1066 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001067 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001068
1069 // Find another superseded keyblob load its metadata and return it.
1070 if let Some((blob_id, blob)) = tx
1071 .query_row(
1072 "SELECT id, blob FROM persistent.blobentry
1073 WHERE subcomponent_type = ?
1074 AND (
1075 id NOT IN (
1076 SELECT MAX(id) FROM persistent.blobentry
1077 WHERE subcomponent_type = ?
1078 GROUP BY keyentryid, subcomponent_type
1079 )
1080 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1081 );",
1082 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1083 |row| Ok((row.get(0)?, row.get(1)?)),
1084 )
1085 .optional()
1086 .context("Trying to query superseded blob.")?
1087 {
1088 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1089 .context("Trying to load blob metadata.")?;
1090 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1091 }
1092
1093 // We did not find any superseded key blob, so let's remove other superseded blob in
1094 // one transaction.
1095 tx.execute(
1096 "DELETE FROM persistent.blobentry
1097 WHERE NOT subcomponent_type = ?
1098 AND (
1099 id NOT IN (
1100 SELECT MAX(id) FROM persistent.blobentry
1101 WHERE NOT subcomponent_type = ?
1102 GROUP BY keyentryid, subcomponent_type
1103 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1104 );",
1105 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1106 )
1107 .context("Trying to purge superseded blobs.")?;
1108
1109 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001110 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001111 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001112 }
1113
1114 /// This maintenance function should be called only once before the database is used for the
1115 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1116 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1117 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1118 /// Keystore crashed at some point during key generation. Callers may want to log such
1119 /// occurrences.
1120 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1121 /// it to `KeyLifeCycle::Live` may have grants.
1122 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001123 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1124 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001125 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1126 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1127 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001128 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001129 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001130 })
1131 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001132 }
1133
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001134 /// Checks if a key exists with given key type and key descriptor properties.
1135 pub fn key_exists(
1136 &mut self,
1137 domain: Domain,
1138 nspace: i64,
1139 alias: &str,
1140 key_type: KeyType,
1141 ) -> Result<bool> {
1142 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1143 let key_descriptor =
1144 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1145 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1146 match result {
1147 Ok(_) => Ok(true),
1148 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1149 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1150 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1151 },
1152 }
1153 .no_gc()
1154 })
1155 .context("In key_exists.")
1156 }
1157
Hasini Gunasingheda895552021-01-27 19:34:37 +00001158 /// Stores a super key in the database.
1159 pub fn store_super_key(
1160 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001161 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001162 key_type: &SuperKeyType,
1163 blob: &[u8],
1164 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001165 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001166 ) -> Result<KeyEntry> {
1167 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1168 let key_id = Self::insert_with_retry(|id| {
1169 tx.execute(
1170 "INSERT into persistent.keyentry
1171 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001172 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001173 params![
1174 id,
1175 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001176 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001177 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001178 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001179 KeyLifeCycle::Live,
1180 &KEYSTORE_UUID,
1181 ],
1182 )
1183 })
1184 .context("Failed to insert into keyentry table.")?;
1185
Paul Crowley8d5b2532021-03-19 10:53:07 -07001186 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1187
Hasini Gunasingheda895552021-01-27 19:34:37 +00001188 Self::set_blob_internal(
1189 &tx,
1190 key_id,
1191 SubComponentType::KEY_BLOB,
1192 Some(blob),
1193 Some(blob_metadata),
1194 )
1195 .context("Failed to store key blob.")?;
1196
1197 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1198 .context("Trying to load key components.")
1199 .no_gc()
1200 })
1201 .context("In store_super_key.")
1202 }
1203
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001204 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001205 pub fn load_super_key(
1206 &mut self,
1207 key_type: &SuperKeyType,
1208 user_id: u32,
1209 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001210 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1211 let key_descriptor = KeyDescriptor {
1212 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001213 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001214 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001215 blob: None,
1216 };
1217 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1218 match id {
1219 Ok(id) => {
1220 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1221 .context("In load_super_key. Failed to load key entry.")?;
1222 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1223 }
1224 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1225 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1226 _ => Err(error).context("In load_super_key."),
1227 },
1228 }
1229 .no_gc()
1230 })
1231 .context("In load_super_key.")
1232 }
1233
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001234 /// Atomically loads a key entry and associated metadata or creates it using the
1235 /// callback create_new_key callback. The callback is called during a database
1236 /// transaction. This means that implementers should be mindful about using
1237 /// blocking operations such as IPC or grabbing mutexes.
1238 pub fn get_or_create_key_with<F>(
1239 &mut self,
1240 domain: Domain,
1241 namespace: i64,
1242 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001243 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001244 create_new_key: F,
1245 ) -> Result<(KeyIdGuard, KeyEntry)>
1246 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001247 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001248 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001249 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1250 let id = {
1251 let mut stmt = tx
1252 .prepare(
1253 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001254 WHERE
1255 key_type = ?
1256 AND domain = ?
1257 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001258 AND alias = ?
1259 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001260 )
1261 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1262 let mut rows = stmt
1263 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1264 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001265
Janis Danisevskis66784c42021-01-27 08:40:25 -08001266 db_utils::with_rows_extract_one(&mut rows, |row| {
1267 Ok(match row {
1268 Some(r) => r.get(0).context("Failed to unpack id.")?,
1269 None => None,
1270 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001271 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001272 .context("In get_or_create_key_with.")?
1273 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001274
Janis Danisevskis66784c42021-01-27 08:40:25 -08001275 let (id, entry) = match id {
1276 Some(id) => (
1277 id,
1278 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1279 .context("In get_or_create_key_with.")?,
1280 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001281
Janis Danisevskis66784c42021-01-27 08:40:25 -08001282 None => {
1283 let id = Self::insert_with_retry(|id| {
1284 tx.execute(
1285 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001286 (id, key_type, domain, namespace, alias, state, km_uuid)
1287 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001288 params![
1289 id,
1290 KeyType::Super,
1291 domain.0,
1292 namespace,
1293 alias,
1294 KeyLifeCycle::Live,
1295 km_uuid,
1296 ],
1297 )
1298 })
1299 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001300
Janis Danisevskis66784c42021-01-27 08:40:25 -08001301 let (blob, metadata) =
1302 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001303 Self::set_blob_internal(
1304 &tx,
1305 id,
1306 SubComponentType::KEY_BLOB,
1307 Some(&blob),
1308 Some(&metadata),
1309 )
Paul Crowley7a658392021-03-18 17:08:20 -07001310 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001311 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001312 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001313 KeyEntry {
1314 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001315 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001316 pure_cert: false,
1317 ..Default::default()
1318 },
1319 )
1320 }
1321 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001322 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001323 })
1324 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001325 }
1326
Janis Danisevskis66784c42021-01-27 08:40:25 -08001327 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1328 /// waiting for the database file to become available. This makes it
1329 /// impossible to successfully recover from a locked database when the
1330 /// transaction holding the device busy is in the same process on a
1331 /// different connection. As a result the busy handler has to time out and
1332 /// fail in order to make progress.
1333 ///
1334 /// Instead, we set the busy handler to None (return immediately). And catch
1335 /// Busy and Locked errors (the latter occur on in memory databases with
1336 /// shared cache, e.g., the per-boot database.) and restart the transaction
1337 /// after a grace period of half a millisecond.
1338 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001339 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001340 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1341 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001342 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1343 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001344 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001345 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001346 loop {
1347 match self
1348 .conn
1349 .transaction_with_behavior(behavior)
1350 .context("In with_transaction.")
1351 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1352 .and_then(|(result, tx)| {
1353 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1354 Ok(result)
1355 }) {
1356 Ok(result) => break Ok(result),
1357 Err(e) => {
1358 if Self::is_locked_error(&e) {
1359 std::thread::sleep(std::time::Duration::from_micros(500));
1360 continue;
1361 } else {
1362 return Err(e).context("In with_transaction.");
1363 }
1364 }
1365 }
1366 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001367 .map(|(need_gc, result)| {
1368 if need_gc {
1369 if let Some(ref gc) = self.gc {
1370 gc.notify_gc();
1371 }
1372 }
1373 result
1374 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001375 }
1376
1377 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001378 matches!(
1379 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1380 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1381 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1382 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001383 }
1384
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001385 /// Creates a new key entry and allocates a new randomized id for the new key.
1386 /// The key id gets associated with a domain and namespace but not with an alias.
1387 /// To complete key generation `rebind_alias` should be called after all of the
1388 /// key artifacts, i.e., blobs and parameters have been associated with the new
1389 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1390 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001391 pub fn create_key_entry(
1392 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001393 domain: &Domain,
1394 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001395 km_uuid: &Uuid,
1396 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001397 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001398 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001399 })
1400 .context("In create_key_entry.")
1401 }
1402
1403 fn create_key_entry_internal(
1404 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001405 domain: &Domain,
1406 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001407 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001408 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001409 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001410 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001411 _ => {
1412 return Err(KsError::sys())
1413 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1414 }
1415 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001416 Ok(KEY_ID_LOCK.get(
1417 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001418 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001419 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001420 (id, key_type, domain, namespace, alias, state, km_uuid)
1421 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001422 params![
1423 id,
1424 KeyType::Client,
1425 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001426 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001427 KeyLifeCycle::Existing,
1428 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001429 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001430 )
1431 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001432 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001433 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001434 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001435
Max Bires2b2e6562020-09-22 11:22:36 -07001436 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1437 /// The key id gets associated with a domain and namespace later but not with an alias. The
1438 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1439 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1440 /// a key.
1441 pub fn create_attestation_key_entry(
1442 &mut self,
1443 maced_public_key: &[u8],
1444 raw_public_key: &[u8],
1445 private_key: &[u8],
1446 km_uuid: &Uuid,
1447 ) -> Result<()> {
1448 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1449 let key_id = KEY_ID_LOCK.get(
1450 Self::insert_with_retry(|id| {
1451 tx.execute(
1452 "INSERT into persistent.keyentry
1453 (id, key_type, domain, namespace, alias, state, km_uuid)
1454 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1455 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1456 )
1457 })
1458 .context("In create_key_entry")?,
1459 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001460 Self::set_blob_internal(
1461 &tx,
1462 key_id.0,
1463 SubComponentType::KEY_BLOB,
1464 Some(private_key),
1465 None,
1466 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001467 let mut metadata = KeyMetaData::new();
1468 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1469 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1470 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001471 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001472 })
1473 .context("In create_attestation_key_entry")
1474 }
1475
Janis Danisevskis377d1002021-01-27 19:07:48 -08001476 /// Set a new blob and associates it with the given key id. Each blob
1477 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001478 /// Each key can have one of each sub component type associated. If more
1479 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001480 /// will get garbage collected.
1481 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1482 /// removed by setting blob to None.
1483 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001484 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001485 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001486 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001487 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001488 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001489 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001490 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001491 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001492 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001493 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001494 }
1495
Janis Danisevskiseed69842021-02-18 20:04:10 -08001496 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1497 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1498 /// We use this to insert key blobs into the database which can then be garbage collected
1499 /// lazily by the key garbage collector.
1500 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
1501 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1502 Self::set_blob_internal(
1503 &tx,
1504 Self::UNASSIGNED_KEY_ID,
1505 SubComponentType::KEY_BLOB,
1506 Some(blob),
1507 Some(blob_metadata),
1508 )
1509 .need_gc()
1510 })
1511 .context("In set_deleted_blob.")
1512 }
1513
Janis Danisevskis377d1002021-01-27 19:07:48 -08001514 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001515 tx: &Transaction,
1516 key_id: i64,
1517 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001518 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001519 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001520 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001521 match (blob, sc_type) {
1522 (Some(blob), _) => {
1523 tx.execute(
1524 "INSERT INTO persistent.blobentry
1525 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1526 params![sc_type, key_id, blob],
1527 )
1528 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001529 if let Some(blob_metadata) = blob_metadata {
1530 let blob_id = tx
1531 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1532 row.get(0)
1533 })
1534 .context("In set_blob_internal: Failed to get new blob id.")?;
1535 blob_metadata
1536 .store_in_db(blob_id, tx)
1537 .context("In set_blob_internal: Trying to store blob metadata.")?;
1538 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001539 }
1540 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1541 tx.execute(
1542 "DELETE FROM persistent.blobentry
1543 WHERE subcomponent_type = ? AND keyentryid = ?;",
1544 params![sc_type, key_id],
1545 )
1546 .context("In set_blob_internal: Failed to delete blob.")?;
1547 }
1548 (None, _) => {
1549 return Err(KsError::sys())
1550 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1551 }
1552 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001553 Ok(())
1554 }
1555
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001556 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1557 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001558 #[cfg(test)]
1559 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001560 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001561 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001562 })
1563 .context("In insert_keyparameter.")
1564 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001565
Janis Danisevskis66784c42021-01-27 08:40:25 -08001566 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001567 tx: &Transaction,
1568 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001569 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001570 ) -> Result<()> {
1571 let mut stmt = tx
1572 .prepare(
1573 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1574 VALUES (?, ?, ?, ?);",
1575 )
1576 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1577
Janis Danisevskis66784c42021-01-27 08:40:25 -08001578 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001579 stmt.insert(params![
1580 key_id.0,
1581 p.get_tag().0,
1582 p.key_parameter_value(),
1583 p.security_level().0
1584 ])
1585 .with_context(|| {
1586 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1587 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001588 }
1589 Ok(())
1590 }
1591
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001592 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001593 #[cfg(test)]
1594 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001595 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001596 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001597 })
1598 .context("In insert_key_metadata.")
1599 }
1600
Max Bires2b2e6562020-09-22 11:22:36 -07001601 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1602 /// on the public key.
1603 pub fn store_signed_attestation_certificate_chain(
1604 &mut self,
1605 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001606 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001607 cert_chain: &[u8],
1608 expiration_date: i64,
1609 km_uuid: &Uuid,
1610 ) -> Result<()> {
1611 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1612 let mut stmt = tx
1613 .prepare(
1614 "SELECT keyentryid
1615 FROM persistent.keymetadata
1616 WHERE tag = ? AND data = ? AND keyentryid IN
1617 (SELECT id
1618 FROM persistent.keyentry
1619 WHERE
1620 alias IS NULL AND
1621 domain IS NULL AND
1622 namespace IS NULL AND
1623 key_type = ? AND
1624 km_uuid = ?);",
1625 )
1626 .context("Failed to store attestation certificate chain.")?;
1627 let mut rows = stmt
1628 .query(params![
1629 KeyMetaData::AttestationRawPubKey,
1630 raw_public_key,
1631 KeyType::Attestation,
1632 km_uuid
1633 ])
1634 .context("Failed to fetch keyid")?;
1635 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1636 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1637 .get(0)
1638 .context("Failed to unpack id.")
1639 })
1640 .context("Failed to get key_id.")?;
1641 let num_updated = tx
1642 .execute(
1643 "UPDATE persistent.keyentry
1644 SET alias = ?
1645 WHERE id = ?;",
1646 params!["signed", key_id],
1647 )
1648 .context("Failed to update alias.")?;
1649 if num_updated != 1 {
1650 return Err(KsError::sys()).context("Alias not updated for the key.");
1651 }
1652 let mut metadata = KeyMetaData::new();
1653 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1654 expiration_date,
1655 )));
1656 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001657 Self::set_blob_internal(
1658 &tx,
1659 key_id,
1660 SubComponentType::CERT_CHAIN,
1661 Some(cert_chain),
1662 None,
1663 )
1664 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001665 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1666 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001667 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001668 })
1669 .context("In store_signed_attestation_certificate_chain: ")
1670 }
1671
1672 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1673 /// currently have a key assigned to it.
1674 pub fn assign_attestation_key(
1675 &mut self,
1676 domain: Domain,
1677 namespace: i64,
1678 km_uuid: &Uuid,
1679 ) -> Result<()> {
1680 match domain {
1681 Domain::APP | Domain::SELINUX => {}
1682 _ => {
1683 return Err(KsError::sys()).context(format!(
1684 concat!(
1685 "In assign_attestation_key: Domain {:?} ",
1686 "must be either App or SELinux.",
1687 ),
1688 domain
1689 ));
1690 }
1691 }
1692 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1693 let result = tx
1694 .execute(
1695 "UPDATE persistent.keyentry
1696 SET domain=?1, namespace=?2
1697 WHERE
1698 id =
1699 (SELECT MIN(id)
1700 FROM persistent.keyentry
1701 WHERE ALIAS IS NOT NULL
1702 AND domain IS NULL
1703 AND key_type IS ?3
1704 AND state IS ?4
1705 AND km_uuid IS ?5)
1706 AND
1707 (SELECT COUNT(*)
1708 FROM persistent.keyentry
1709 WHERE domain=?1
1710 AND namespace=?2
1711 AND key_type IS ?3
1712 AND state IS ?4
1713 AND km_uuid IS ?5) = 0;",
1714 params![
1715 domain.0 as u32,
1716 namespace,
1717 KeyType::Attestation,
1718 KeyLifeCycle::Live,
1719 km_uuid,
1720 ],
1721 )
1722 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001723 if result == 0 {
1724 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1725 } else if result > 1 {
1726 return Err(KsError::sys())
1727 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001728 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001729 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001730 })
1731 .context("In assign_attestation_key: ")
1732 }
1733
1734 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1735 /// provisioning server, or the maximum number available if there are not num_keys number of
1736 /// entries in the table.
1737 pub fn fetch_unsigned_attestation_keys(
1738 &mut self,
1739 num_keys: i32,
1740 km_uuid: &Uuid,
1741 ) -> Result<Vec<Vec<u8>>> {
1742 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1743 let mut stmt = tx
1744 .prepare(
1745 "SELECT data
1746 FROM persistent.keymetadata
1747 WHERE tag = ? AND keyentryid IN
1748 (SELECT id
1749 FROM persistent.keyentry
1750 WHERE
1751 alias IS NULL AND
1752 domain IS NULL AND
1753 namespace IS NULL AND
1754 key_type = ? AND
1755 km_uuid = ?
1756 LIMIT ?);",
1757 )
1758 .context("Failed to prepare statement")?;
1759 let rows = stmt
1760 .query_map(
1761 params![
1762 KeyMetaData::AttestationMacedPublicKey,
1763 KeyType::Attestation,
1764 km_uuid,
1765 num_keys
1766 ],
1767 |row| Ok(row.get(0)?),
1768 )?
1769 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1770 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001771 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001772 })
1773 .context("In fetch_unsigned_attestation_keys")
1774 }
1775
1776 /// Removes any keys that have expired as of the current time. Returns the number of keys
1777 /// marked unreferenced that are bound to be garbage collected.
1778 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
1779 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1780 let mut stmt = tx
1781 .prepare(
1782 "SELECT keyentryid, data
1783 FROM persistent.keymetadata
1784 WHERE tag = ? AND keyentryid IN
1785 (SELECT id
1786 FROM persistent.keyentry
1787 WHERE key_type = ?);",
1788 )
1789 .context("Failed to prepare query")?;
1790 let key_ids_to_check = stmt
1791 .query_map(
1792 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1793 |row| Ok((row.get(0)?, row.get(1)?)),
1794 )?
1795 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1796 .context("Failed to get date metadata")?;
1797 let curr_time = DateTime::from_millis_epoch(
1798 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1799 );
1800 let mut num_deleted = 0;
1801 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1802 if Self::mark_unreferenced(&tx, id)? {
1803 num_deleted += 1;
1804 }
1805 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001806 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001807 })
1808 .context("In delete_expired_attestation_keys: ")
1809 }
1810
Max Bires60d7ed12021-03-05 15:59:22 -08001811 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1812 /// they are in. This is useful primarily as a testing mechanism.
1813 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
1814 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1815 let mut stmt = tx
1816 .prepare(
1817 "SELECT id FROM persistent.keyentry
1818 WHERE key_type IS ?;",
1819 )
1820 .context("Failed to prepare statement")?;
1821 let keys_to_delete = stmt
1822 .query_map(params![KeyType::Attestation], |row| Ok(row.get(0)?))?
1823 .collect::<rusqlite::Result<Vec<i64>>>()
1824 .context("Failed to execute statement")?;
1825 let num_deleted = keys_to_delete
1826 .iter()
1827 .map(|id| Self::mark_unreferenced(&tx, *id))
1828 .collect::<Result<Vec<bool>>>()
1829 .context("Failed to execute mark_unreferenced on a keyid")?
1830 .into_iter()
1831 .filter(|result| *result)
1832 .count() as i64;
1833 Ok(num_deleted).do_gc(num_deleted != 0)
1834 })
1835 .context("In delete_all_attestation_keys: ")
1836 }
1837
Max Bires2b2e6562020-09-22 11:22:36 -07001838 /// Counts the number of keys that will expire by the provided epoch date and the number of
1839 /// keys not currently assigned to a domain.
1840 pub fn get_attestation_pool_status(
1841 &mut self,
1842 date: i64,
1843 km_uuid: &Uuid,
1844 ) -> Result<AttestationPoolStatus> {
1845 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1846 let mut stmt = tx.prepare(
1847 "SELECT data
1848 FROM persistent.keymetadata
1849 WHERE tag = ? AND keyentryid IN
1850 (SELECT id
1851 FROM persistent.keyentry
1852 WHERE alias IS NOT NULL
1853 AND key_type = ?
1854 AND km_uuid = ?
1855 AND state = ?);",
1856 )?;
1857 let times = stmt
1858 .query_map(
1859 params![
1860 KeyMetaData::AttestationExpirationDate,
1861 KeyType::Attestation,
1862 km_uuid,
1863 KeyLifeCycle::Live
1864 ],
1865 |row| Ok(row.get(0)?),
1866 )?
1867 .collect::<rusqlite::Result<Vec<DateTime>>>()
1868 .context("Failed to execute metadata statement")?;
1869 let expiring =
1870 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1871 as i32;
1872 stmt = tx.prepare(
1873 "SELECT alias, domain
1874 FROM persistent.keyentry
1875 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1876 )?;
1877 let rows = stmt
1878 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1879 Ok((row.get(0)?, row.get(1)?))
1880 })?
1881 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1882 .context("Failed to execute keyentry statement")?;
1883 let mut unassigned = 0i32;
1884 let mut attested = 0i32;
1885 let total = rows.len() as i32;
1886 for (alias, domain) in rows {
1887 match (alias, domain) {
1888 (Some(_alias), None) => {
1889 attested += 1;
1890 unassigned += 1;
1891 }
1892 (Some(_alias), Some(_domain)) => {
1893 attested += 1;
1894 }
1895 _ => {}
1896 }
1897 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001898 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001899 })
1900 .context("In get_attestation_pool_status: ")
1901 }
1902
1903 /// Fetches the private key and corresponding certificate chain assigned to a
1904 /// domain/namespace pair. Will either return nothing if the domain/namespace is
1905 /// not assigned, or one CertificateChain.
1906 pub fn retrieve_attestation_key_and_cert_chain(
1907 &mut self,
1908 domain: Domain,
1909 namespace: i64,
1910 km_uuid: &Uuid,
1911 ) -> Result<Option<CertificateChain>> {
1912 match domain {
1913 Domain::APP | Domain::SELINUX => {}
1914 _ => {
1915 return Err(KsError::sys())
1916 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1917 }
1918 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001919 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1920 let mut stmt = tx.prepare(
1921 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07001922 FROM persistent.blobentry
1923 WHERE keyentryid IN
1924 (SELECT id
1925 FROM persistent.keyentry
1926 WHERE key_type = ?
1927 AND domain = ?
1928 AND namespace = ?
1929 AND state = ?
1930 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001931 )?;
1932 let rows = stmt
1933 .query_map(
1934 params![
1935 KeyType::Attestation,
1936 domain.0 as u32,
1937 namespace,
1938 KeyLifeCycle::Live,
1939 km_uuid
1940 ],
1941 |row| Ok((row.get(0)?, row.get(1)?)),
1942 )?
1943 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08001944 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001945 if rows.is_empty() {
1946 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08001947 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001948 return Err(KsError::sys()).context(format!(
1949 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08001950 "Expected to get a single attestation",
1951 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
1952 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001953 rows.len()
1954 ));
Max Bires2b2e6562020-09-22 11:22:36 -07001955 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001956 let mut km_blob: Vec<u8> = Vec::new();
1957 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08001958 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001959 for row in rows {
1960 let sub_type: SubComponentType = row.0;
1961 match sub_type {
1962 SubComponentType::KEY_BLOB => {
1963 km_blob = row.1;
1964 }
1965 SubComponentType::CERT_CHAIN => {
1966 cert_chain_blob = row.1;
1967 }
Max Biresb2e1d032021-02-08 21:35:05 -08001968 SubComponentType::CERT => {
1969 batch_cert_blob = row.1;
1970 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001971 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
1972 }
1973 }
1974 Ok(Some(CertificateChain {
1975 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08001976 batch_cert: batch_cert_blob,
1977 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001978 }))
1979 .no_gc()
1980 })
Max Biresb2e1d032021-02-08 21:35:05 -08001981 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07001982 }
1983
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001984 /// Updates the alias column of the given key id `newid` with the given alias,
1985 /// and atomically, removes the alias, domain, and namespace from another row
1986 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001987 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1988 /// collector.
1989 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001990 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001991 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001992 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001993 domain: &Domain,
1994 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001995 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001996 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001997 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001998 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001999 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002000 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002001 domain
2002 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002003 }
2004 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002005 let updated = tx
2006 .execute(
2007 "UPDATE persistent.keyentry
2008 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002009 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002010 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2011 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002012 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002013 let result = tx
2014 .execute(
2015 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002016 SET alias = ?, state = ?
2017 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2018 params![
2019 alias,
2020 KeyLifeCycle::Live,
2021 newid.0,
2022 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002023 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002024 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002025 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002026 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002027 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002028 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002029 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002030 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002031 result
2032 ));
2033 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002034 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002035 }
2036
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002037 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2038 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2039 pub fn migrate_key_namespace(
2040 &mut self,
2041 key_id_guard: KeyIdGuard,
2042 destination: &KeyDescriptor,
2043 caller_uid: u32,
2044 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2045 ) -> Result<()> {
2046 let destination = match destination.domain {
2047 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2048 Domain::SELINUX => (*destination).clone(),
2049 domain => {
2050 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2051 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2052 }
2053 };
2054
2055 // Security critical: Must return immediately on failure. Do not remove the '?';
2056 check_permission(&destination)
2057 .context("In migrate_key_namespace: Trying to check permission.")?;
2058
2059 let alias = destination
2060 .alias
2061 .as_ref()
2062 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2063 .context("In migrate_key_namespace: Alias must be specified.")?;
2064
2065 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2066 // Query the destination location. If there is a key, the migration request fails.
2067 if tx
2068 .query_row(
2069 "SELECT id FROM persistent.keyentry
2070 WHERE alias = ? AND domain = ? AND namespace = ?;",
2071 params![alias, destination.domain.0, destination.nspace],
2072 |_| Ok(()),
2073 )
2074 .optional()
2075 .context("Failed to query destination.")?
2076 .is_some()
2077 {
2078 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2079 .context("Target already exists.");
2080 }
2081
2082 let updated = tx
2083 .execute(
2084 "UPDATE persistent.keyentry
2085 SET alias = ?, domain = ?, namespace = ?
2086 WHERE id = ?;",
2087 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2088 )
2089 .context("Failed to update key entry.")?;
2090
2091 if updated != 1 {
2092 return Err(KsError::sys())
2093 .context(format!("Update succeeded, but {} rows were updated.", updated));
2094 }
2095 Ok(()).no_gc()
2096 })
2097 .context("In migrate_key_namespace:")
2098 }
2099
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002100 /// Store a new key in a single transaction.
2101 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2102 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002103 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2104 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002105 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002106 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002107 key: &KeyDescriptor,
2108 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002109 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002110 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002111 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002112 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002113 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002114 let (alias, domain, namespace) = match key {
2115 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2116 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2117 (alias, key.domain, nspace)
2118 }
2119 _ => {
2120 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2121 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2122 }
2123 };
2124 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002125 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002126 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002127 let (blob, blob_metadata) = *blob_info;
2128 Self::set_blob_internal(
2129 tx,
2130 key_id.id(),
2131 SubComponentType::KEY_BLOB,
2132 Some(blob),
2133 Some(&blob_metadata),
2134 )
2135 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002136 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002137 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002138 .context("Trying to insert the certificate.")?;
2139 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002140 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002141 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002142 tx,
2143 key_id.id(),
2144 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002145 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002146 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002147 )
2148 .context("Trying to insert the certificate chain.")?;
2149 }
2150 Self::insert_keyparameter_internal(tx, &key_id, params)
2151 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002152 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002153 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002154 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002155 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002156 })
2157 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002158 }
2159
Janis Danisevskis377d1002021-01-27 19:07:48 -08002160 /// Store a new certificate
2161 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2162 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002163 pub fn store_new_certificate(
2164 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002165 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002166 cert: &[u8],
2167 km_uuid: &Uuid,
2168 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002169 let (alias, domain, namespace) = match key {
2170 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2171 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2172 (alias, key.domain, nspace)
2173 }
2174 _ => {
2175 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2176 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2177 )
2178 }
2179 };
2180 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002181 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002182 .context("Trying to create new key entry.")?;
2183
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002184 Self::set_blob_internal(
2185 tx,
2186 key_id.id(),
2187 SubComponentType::CERT_CHAIN,
2188 Some(cert),
2189 None,
2190 )
2191 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002192
2193 let mut metadata = KeyMetaData::new();
2194 metadata.add(KeyMetaEntry::CreationDate(
2195 DateTime::now().context("Trying to make creation time.")?,
2196 ));
2197
2198 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2199
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002200 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002201 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002202 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002203 })
2204 .context("In store_new_certificate.")
2205 }
2206
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002207 // Helper function loading the key_id given the key descriptor
2208 // tuple comprising domain, namespace, and alias.
2209 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002210 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002211 let alias = key
2212 .alias
2213 .as_ref()
2214 .map_or_else(|| Err(KsError::sys()), Ok)
2215 .context("In load_key_entry_id: Alias must be specified.")?;
2216 let mut stmt = tx
2217 .prepare(
2218 "SELECT id FROM persistent.keyentry
2219 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002220 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002221 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002222 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002223 AND alias = ?
2224 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002225 )
2226 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2227 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002228 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002229 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002230 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002231 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002232 .get(0)
2233 .context("Failed to unpack id.")
2234 })
2235 .context("In load_key_entry_id.")
2236 }
2237
2238 /// This helper function completes the access tuple of a key, which is required
2239 /// to perform access control. The strategy depends on the `domain` field in the
2240 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002241 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002242 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002243 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002244 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002245 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002246 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002247 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002248 /// `namespace`.
2249 /// In each case the information returned is sufficient to perform the access
2250 /// check and the key id can be used to load further key artifacts.
2251 fn load_access_tuple(
2252 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002253 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002254 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002255 caller_uid: u32,
2256 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2257 match key.domain {
2258 // Domain App or SELinux. In this case we load the key_id from
2259 // the keyentry database for further loading of key components.
2260 // We already have the full access tuple to perform access control.
2261 // The only distinction is that we use the caller_uid instead
2262 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002263 // Domain::APP.
2264 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002265 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002266 if access_key.domain == Domain::APP {
2267 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002268 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002269 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002270 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002271
2272 Ok((key_id, access_key, None))
2273 }
2274
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002275 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002276 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002277 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002278 let mut stmt = tx
2279 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002280 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002281 WHERE grantee = ? AND id = ?;",
2282 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002283 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002284 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002285 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002286 .context("Domain:Grant: query failed.")?;
2287 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002288 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002289 let r =
2290 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002291 Ok((
2292 r.get(0).context("Failed to unpack key_id.")?,
2293 r.get(1).context("Failed to unpack access_vector.")?,
2294 ))
2295 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002296 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002297 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002298 }
2299
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002300 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002301 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002302 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002303 let (domain, namespace): (Domain, i64) = {
2304 let mut stmt = tx
2305 .prepare(
2306 "SELECT domain, namespace FROM persistent.keyentry
2307 WHERE
2308 id = ?
2309 AND state = ?;",
2310 )
2311 .context("Domain::KEY_ID: prepare statement failed")?;
2312 let mut rows = stmt
2313 .query(params![key.nspace, KeyLifeCycle::Live])
2314 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002315 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002316 let r =
2317 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002318 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002319 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002320 r.get(1).context("Failed to unpack namespace.")?,
2321 ))
2322 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002323 .context("Domain::KEY_ID.")?
2324 };
2325
2326 // We may use a key by id after loading it by grant.
2327 // In this case we have to check if the caller has a grant for this particular
2328 // key. We can skip this if we already know that the caller is the owner.
2329 // But we cannot know this if domain is anything but App. E.g. in the case
2330 // of Domain::SELINUX we have to speculatively check for grants because we have to
2331 // consult the SEPolicy before we know if the caller is the owner.
2332 let access_vector: Option<KeyPermSet> =
2333 if domain != Domain::APP || namespace != caller_uid as i64 {
2334 let access_vector: Option<i32> = tx
2335 .query_row(
2336 "SELECT access_vector FROM persistent.grant
2337 WHERE grantee = ? AND keyentryid = ?;",
2338 params![caller_uid as i64, key.nspace],
2339 |row| row.get(0),
2340 )
2341 .optional()
2342 .context("Domain::KEY_ID: query grant failed.")?;
2343 access_vector.map(|p| p.into())
2344 } else {
2345 None
2346 };
2347
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002348 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002349 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002350 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002351 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002352
Janis Danisevskis45760022021-01-19 16:34:10 -08002353 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002354 }
2355 _ => Err(anyhow!(KsError::sys())),
2356 }
2357 }
2358
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002359 fn load_blob_components(
2360 key_id: i64,
2361 load_bits: KeyEntryLoadBits,
2362 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002363 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002364 let mut stmt = tx
2365 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002366 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002367 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2368 )
2369 .context("In load_blob_components: prepare statement failed.")?;
2370
2371 let mut rows =
2372 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2373
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002374 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002375 let mut cert_blob: Option<Vec<u8>> = None;
2376 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002377 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002378 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002379 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002380 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002381 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002382 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2383 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002384 key_blob = Some((
2385 row.get(0).context("Failed to extract key blob id.")?,
2386 row.get(2).context("Failed to extract key blob.")?,
2387 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002388 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002389 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002390 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002391 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002392 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002393 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002394 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002395 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002396 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002397 (SubComponentType::CERT, _, _)
2398 | (SubComponentType::CERT_CHAIN, _, _)
2399 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002400 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2401 }
2402 Ok(())
2403 })
2404 .context("In load_blob_components.")?;
2405
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002406 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2407 Ok(Some((
2408 blob,
2409 BlobMetaData::load_from_db(blob_id, tx)
2410 .context("In load_blob_components: Trying to load blob_metadata.")?,
2411 )))
2412 })?;
2413
2414 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002415 }
2416
2417 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2418 let mut stmt = tx
2419 .prepare(
2420 "SELECT tag, data, security_level from persistent.keyparameter
2421 WHERE keyentryid = ?;",
2422 )
2423 .context("In load_key_parameters: prepare statement failed.")?;
2424
2425 let mut parameters: Vec<KeyParameter> = Vec::new();
2426
2427 let mut rows =
2428 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002429 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002430 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2431 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002432 parameters.push(
2433 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2434 .context("Failed to read KeyParameter.")?,
2435 );
2436 Ok(())
2437 })
2438 .context("In load_key_parameters.")?;
2439
2440 Ok(parameters)
2441 }
2442
Qi Wub9433b52020-12-01 14:52:46 +08002443 /// Decrements the usage count of a limited use key. This function first checks whether the
2444 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2445 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2446 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002447 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002448 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2449 let limit: Option<i32> = tx
2450 .query_row(
2451 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2452 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2453 |row| row.get(0),
2454 )
2455 .optional()
2456 .context("Trying to load usage count")?;
2457
2458 let limit = limit
2459 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2460 .context("The Key no longer exists. Key is exhausted.")?;
2461
2462 tx.execute(
2463 "UPDATE persistent.keyparameter
2464 SET data = data - 1
2465 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2466 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2467 )
2468 .context("Failed to update key usage count.")?;
2469
2470 match limit {
2471 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002472 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002473 .context("Trying to mark limited use key for deletion."),
2474 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002475 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002476 }
2477 })
2478 .context("In check_and_update_key_usage_count.")
2479 }
2480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002481 /// Load a key entry by the given key descriptor.
2482 /// It uses the `check_permission` callback to verify if the access is allowed
2483 /// given the key access tuple read from the database using `load_access_tuple`.
2484 /// With `load_bits` the caller may specify which blobs shall be loaded from
2485 /// the blob database.
2486 pub fn load_key_entry(
2487 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002488 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002489 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002490 load_bits: KeyEntryLoadBits,
2491 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002492 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2493 ) -> Result<(KeyIdGuard, KeyEntry)> {
2494 loop {
2495 match self.load_key_entry_internal(
2496 key,
2497 key_type,
2498 load_bits,
2499 caller_uid,
2500 &check_permission,
2501 ) {
2502 Ok(result) => break Ok(result),
2503 Err(e) => {
2504 if Self::is_locked_error(&e) {
2505 std::thread::sleep(std::time::Duration::from_micros(500));
2506 continue;
2507 } else {
2508 return Err(e).context("In load_key_entry.");
2509 }
2510 }
2511 }
2512 }
2513 }
2514
2515 fn load_key_entry_internal(
2516 &mut self,
2517 key: &KeyDescriptor,
2518 key_type: KeyType,
2519 load_bits: KeyEntryLoadBits,
2520 caller_uid: u32,
2521 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002522 ) -> Result<(KeyIdGuard, KeyEntry)> {
2523 // KEY ID LOCK 1/2
2524 // If we got a key descriptor with a key id we can get the lock right away.
2525 // Otherwise we have to defer it until we know the key id.
2526 let key_id_guard = match key.domain {
2527 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2528 _ => None,
2529 };
2530
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002531 let tx = self
2532 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002533 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002534 .context("In load_key_entry: Failed to initialize transaction.")?;
2535
2536 // Load the key_id and complete the access control tuple.
2537 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002538 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2539 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002540
2541 // Perform access control. It is vital that we return here if the permission is denied.
2542 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002543 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002544
Janis Danisevskisaec14592020-11-12 09:41:49 -08002545 // KEY ID LOCK 2/2
2546 // If we did not get a key id lock by now, it was because we got a key descriptor
2547 // without a key id. At this point we got the key id, so we can try and get a lock.
2548 // However, we cannot block here, because we are in the middle of the transaction.
2549 // So first we try to get the lock non blocking. If that fails, we roll back the
2550 // transaction and block until we get the lock. After we successfully got the lock,
2551 // we start a new transaction and load the access tuple again.
2552 //
2553 // We don't need to perform access control again, because we already established
2554 // that the caller had access to the given key. But we need to make sure that the
2555 // key id still exists. So we have to load the key entry by key id this time.
2556 let (key_id_guard, tx) = match key_id_guard {
2557 None => match KEY_ID_LOCK.try_get(key_id) {
2558 None => {
2559 // Roll back the transaction.
2560 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002561
Janis Danisevskisaec14592020-11-12 09:41:49 -08002562 // Block until we have a key id lock.
2563 let key_id_guard = KEY_ID_LOCK.get(key_id);
2564
2565 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002566 let tx = self
2567 .conn
2568 .unchecked_transaction()
2569 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002570
2571 Self::load_access_tuple(
2572 &tx,
2573 // This time we have to load the key by the retrieved key id, because the
2574 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002575 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002576 domain: Domain::KEY_ID,
2577 nspace: key_id,
2578 ..Default::default()
2579 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002580 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002581 caller_uid,
2582 )
2583 .context("In load_key_entry. (deferred key lock)")?;
2584 (key_id_guard, tx)
2585 }
2586 Some(l) => (l, tx),
2587 },
2588 Some(key_id_guard) => (key_id_guard, tx),
2589 };
2590
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002591 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2592 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002593
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002594 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2595
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002596 Ok((key_id_guard, key_entry))
2597 }
2598
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002599 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002600 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002601 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2602 .context("Trying to delete keyentry.")?;
2603 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2604 .context("Trying to delete keymetadata.")?;
2605 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2606 .context("Trying to delete keyparameters.")?;
2607 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2608 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002609 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002610 }
2611
2612 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002613 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002614 pub fn unbind_key(
2615 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002616 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002617 key_type: KeyType,
2618 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002619 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002620 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002621 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2622 let (key_id, access_key_descriptor, access_vector) =
2623 Self::load_access_tuple(tx, key, key_type, caller_uid)
2624 .context("Trying to get access tuple.")?;
2625
2626 // Perform access control. It is vital that we return here if the permission is denied.
2627 // So do not touch that '?' at the end.
2628 check_permission(&access_key_descriptor, access_vector)
2629 .context("While checking permission.")?;
2630
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002631 Self::mark_unreferenced(tx, key_id)
2632 .map(|need_gc| (need_gc, ()))
2633 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002634 })
2635 .context("In unbind_key.")
2636 }
2637
Max Bires8e93d2b2021-01-14 13:17:59 -08002638 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2639 tx.query_row(
2640 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2641 params![key_id],
2642 |row| row.get(0),
2643 )
2644 .context("In get_key_km_uuid.")
2645 }
2646
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002647 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2648 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2649 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
2650 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2651 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2652 .context("In unbind_keys_for_namespace.");
2653 }
2654 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2655 tx.execute(
2656 "DELETE FROM persistent.keymetadata
2657 WHERE keyentryid IN (
2658 SELECT id FROM persistent.keyentry
2659 WHERE domain = ? AND namespace = ?
2660 );",
2661 params![domain.0, namespace],
2662 )
2663 .context("Trying to delete keymetadata.")?;
2664 tx.execute(
2665 "DELETE FROM persistent.keyparameter
2666 WHERE keyentryid IN (
2667 SELECT id FROM persistent.keyentry
2668 WHERE domain = ? AND namespace = ?
2669 );",
2670 params![domain.0, namespace],
2671 )
2672 .context("Trying to delete keyparameters.")?;
2673 tx.execute(
2674 "DELETE FROM persistent.grant
2675 WHERE keyentryid IN (
2676 SELECT id FROM persistent.keyentry
2677 WHERE domain = ? AND namespace = ?
2678 );",
2679 params![domain.0, namespace],
2680 )
2681 .context("Trying to delete grants.")?;
2682 tx.execute(
2683 "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;",
2684 params![domain.0, namespace],
2685 )
2686 .context("Trying to delete keyentry.")?;
2687 Ok(()).need_gc()
2688 })
2689 .context("In unbind_keys_for_namespace")
2690 }
2691
Hasini Gunasingheda895552021-01-27 19:34:37 +00002692 /// Delete the keys created on behalf of the user, denoted by the user id.
2693 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2694 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2695 /// The caller of this function should notify the gc if the returned value is true.
2696 pub fn unbind_keys_for_user(
2697 &mut self,
2698 user_id: u32,
2699 keep_non_super_encrypted_keys: bool,
2700 ) -> Result<()> {
2701 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2702 let mut stmt = tx
2703 .prepare(&format!(
2704 "SELECT id from persistent.keyentry
2705 WHERE (
2706 key_type = ?
2707 AND domain = ?
2708 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2709 AND state = ?
2710 ) OR (
2711 key_type = ?
2712 AND namespace = ?
2713 AND alias = ?
2714 AND state = ?
2715 );",
2716 aid_user_offset = AID_USER_OFFSET
2717 ))
2718 .context(concat!(
2719 "In unbind_keys_for_user. ",
2720 "Failed to prepare the query to find the keys created by apps."
2721 ))?;
2722
2723 let mut rows = stmt
2724 .query(params![
2725 // WHERE client key:
2726 KeyType::Client,
2727 Domain::APP.0 as u32,
2728 user_id,
2729 KeyLifeCycle::Live,
2730 // OR super key:
2731 KeyType::Super,
2732 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002733 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002734 KeyLifeCycle::Live
2735 ])
2736 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2737
2738 let mut key_ids: Vec<i64> = Vec::new();
2739 db_utils::with_rows_extract_all(&mut rows, |row| {
2740 key_ids
2741 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2742 Ok(())
2743 })
2744 .context("In unbind_keys_for_user.")?;
2745
2746 let mut notify_gc = false;
2747 for key_id in key_ids {
2748 if keep_non_super_encrypted_keys {
2749 // Load metadata and filter out non-super-encrypted keys.
2750 if let (_, Some((_, blob_metadata)), _, _) =
2751 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2752 .context("In unbind_keys_for_user: Trying to load blob info.")?
2753 {
2754 if blob_metadata.encrypted_by().is_none() {
2755 continue;
2756 }
2757 }
2758 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002759 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002760 .context("In unbind_keys_for_user.")?
2761 || notify_gc;
2762 }
2763 Ok(()).do_gc(notify_gc)
2764 })
2765 .context("In unbind_keys_for_user.")
2766 }
2767
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002768 fn load_key_components(
2769 tx: &Transaction,
2770 load_bits: KeyEntryLoadBits,
2771 key_id: i64,
2772 ) -> Result<KeyEntry> {
2773 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2774
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002775 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002776 Self::load_blob_components(key_id, load_bits, &tx)
2777 .context("In load_key_components.")?;
2778
Max Bires8e93d2b2021-01-14 13:17:59 -08002779 let parameters = Self::load_key_parameters(key_id, &tx)
2780 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002781
Max Bires8e93d2b2021-01-14 13:17:59 -08002782 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2783 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002784
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002785 Ok(KeyEntry {
2786 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002787 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002788 cert: cert_blob,
2789 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002790 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002791 parameters,
2792 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002793 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002794 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002795 }
2796
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002797 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2798 /// The key descriptors will have the domain, nspace, and alias field set.
2799 /// Domain must be APP or SELINUX, the caller must make sure of that.
2800 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002801 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2802 let mut stmt = tx
2803 .prepare(
2804 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002805 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002806 )
2807 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002808
Janis Danisevskis66784c42021-01-27 08:40:25 -08002809 let mut rows = stmt
2810 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2811 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002812
Janis Danisevskis66784c42021-01-27 08:40:25 -08002813 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2814 db_utils::with_rows_extract_all(&mut rows, |row| {
2815 descriptors.push(KeyDescriptor {
2816 domain,
2817 nspace: namespace,
2818 alias: Some(row.get(0).context("Trying to extract alias.")?),
2819 blob: None,
2820 });
2821 Ok(())
2822 })
2823 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002824 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002825 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002826 }
2827
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002828 /// Adds a grant to the grant table.
2829 /// Like `load_key_entry` this function loads the access tuple before
2830 /// it uses the callback for a permission check. Upon success,
2831 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2832 /// grant table. The new row will have a randomized id, which is used as
2833 /// grant id in the namespace field of the resulting KeyDescriptor.
2834 pub fn grant(
2835 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002836 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002837 caller_uid: u32,
2838 grantee_uid: u32,
2839 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002840 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002841 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002842 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2843 // Load the key_id and complete the access control tuple.
2844 // We ignore the access vector here because grants cannot be granted.
2845 // The access vector returned here expresses the permissions the
2846 // grantee has if key.domain == Domain::GRANT. But this vector
2847 // cannot include the grant permission by design, so there is no way the
2848 // subsequent permission check can pass.
2849 // We could check key.domain == Domain::GRANT and fail early.
2850 // But even if we load the access tuple by grant here, the permission
2851 // check denies the attempt to create a grant by grant descriptor.
2852 let (key_id, access_key_descriptor, _) =
2853 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2854 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002855
Janis Danisevskis66784c42021-01-27 08:40:25 -08002856 // Perform access control. It is vital that we return here if the permission
2857 // was denied. So do not touch that '?' at the end of the line.
2858 // This permission check checks if the caller has the grant permission
2859 // for the given key and in addition to all of the permissions
2860 // expressed in `access_vector`.
2861 check_permission(&access_key_descriptor, &access_vector)
2862 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002863
Janis Danisevskis66784c42021-01-27 08:40:25 -08002864 let grant_id = if let Some(grant_id) = tx
2865 .query_row(
2866 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002867 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002868 params![key_id, grantee_uid],
2869 |row| row.get(0),
2870 )
2871 .optional()
2872 .context("In grant: Failed get optional existing grant id.")?
2873 {
2874 tx.execute(
2875 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002876 SET access_vector = ?
2877 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002878 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002879 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002880 .context("In grant: Failed to update existing grant.")?;
2881 grant_id
2882 } else {
2883 Self::insert_with_retry(|id| {
2884 tx.execute(
2885 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2886 VALUES (?, ?, ?, ?);",
2887 params![id, grantee_uid, key_id, i32::from(access_vector)],
2888 )
2889 })
2890 .context("In grant")?
2891 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002892
Janis Danisevskis66784c42021-01-27 08:40:25 -08002893 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002894 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002895 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002896 }
2897
2898 /// This function checks permissions like `grant` and `load_key_entry`
2899 /// before removing a grant from the grant table.
2900 pub fn ungrant(
2901 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002902 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002903 caller_uid: u32,
2904 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002905 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002906 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002907 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2908 // Load the key_id and complete the access control tuple.
2909 // We ignore the access vector here because grants cannot be granted.
2910 let (key_id, access_key_descriptor, _) =
2911 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2912 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002913
Janis Danisevskis66784c42021-01-27 08:40:25 -08002914 // Perform access control. We must return here if the permission
2915 // was denied. So do not touch the '?' at the end of this line.
2916 check_permission(&access_key_descriptor)
2917 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002918
Janis Danisevskis66784c42021-01-27 08:40:25 -08002919 tx.execute(
2920 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002921 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002922 params![key_id, grantee_uid],
2923 )
2924 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002925
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002926 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002927 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002928 }
2929
Joel Galenson845f74b2020-09-09 14:11:55 -07002930 // Generates a random id and passes it to the given function, which will
2931 // try to insert it into a database. If that insertion fails, retry;
2932 // otherwise return the id.
2933 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2934 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002935 let newid: i64 = match random() {
2936 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2937 i => i,
2938 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002939 match inserter(newid) {
2940 // If the id already existed, try again.
2941 Err(rusqlite::Error::SqliteFailure(
2942 libsqlite3_sys::Error {
2943 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2944 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2945 },
2946 _,
2947 )) => (),
2948 Err(e) => {
2949 return Err(e).context("In insert_with_retry: failed to insert into database.")
2950 }
2951 _ => return Ok(newid),
2952 }
2953 }
2954 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002955
2956 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
2957 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002958 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2959 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002960 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
2961 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
2962 params![
2963 auth_token.challenge,
2964 auth_token.userId,
2965 auth_token.authenticatorId,
2966 auth_token.authenticatorType.0 as i32,
2967 auth_token.timestamp.milliSeconds as i64,
2968 auth_token.mac,
2969 MonotonicRawTime::now(),
2970 ],
2971 )
2972 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002973 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002974 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002975 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002976
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002977 /// Find the newest auth token matching the given predicate.
2978 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002979 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002980 p: F,
2981 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
2982 where
2983 F: Fn(&AuthTokenEntry) -> bool,
2984 {
2985 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2986 let mut stmt = tx
2987 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
2988 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002989
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002990 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002991
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002992 while let Some(row) = rows.next().context("Failed to get next row.")? {
2993 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002994 HardwareAuthToken {
2995 challenge: row.get(1)?,
2996 userId: row.get(2)?,
2997 authenticatorId: row.get(3)?,
2998 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2999 timestamp: Timestamp { milliSeconds: row.get(5)? },
3000 mac: row.get(6)?,
3001 },
3002 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003003 );
3004 if p(&entry) {
3005 return Ok(Some((
3006 entry,
3007 Self::get_last_off_body(tx)
3008 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003009 )))
3010 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003011 }
3012 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003013 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003014 })
3015 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003016 }
3017
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003018 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003019 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
3020 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3021 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003022 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3023 params!["last_off_body", last_off_body],
3024 )
3025 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003026 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003027 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003028 }
3029
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003030 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003031 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
3032 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3033 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003034 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3035 params![last_off_body, "last_off_body"],
3036 )
3037 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003038 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003039 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003040 }
3041
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003042 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003043 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003044 tx.query_row(
3045 "SELECT value from perboot.metadata WHERE key = ?;",
3046 params!["last_off_body"],
3047 |row| Ok(row.get(0)?),
3048 )
3049 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003050 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003051}
3052
3053#[cfg(test)]
3054mod tests {
3055
3056 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003057 use crate::key_parameter::{
3058 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3059 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3060 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003061 use crate::key_perm_set;
3062 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003063 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003064 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003065 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3066 HardwareAuthToken::HardwareAuthToken,
3067 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003068 };
3069 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003070 Timestamp::Timestamp,
3071 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003072 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003073 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003074 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003075 use std::sync::atomic::{AtomicU8, Ordering};
3076 use std::sync::Arc;
3077 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003078 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003079 #[cfg(disabled)]
3080 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003081
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003082 fn new_test_db() -> Result<KeystoreDB> {
3083 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3084
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003085 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003086 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003087 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003088 })?;
3089 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003090 }
3091
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003092 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3093 where
3094 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3095 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003096 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003097
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003098 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003099 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003100
3101 KeystoreDB::new(path, Some(gc))
3102 }
3103
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003104 fn rebind_alias(
3105 db: &mut KeystoreDB,
3106 newid: &KeyIdGuard,
3107 alias: &str,
3108 domain: Domain,
3109 namespace: i64,
3110 ) -> Result<bool> {
3111 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003112 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003113 })
3114 .context("In rebind_alias.")
3115 }
3116
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003117 #[test]
3118 fn datetime() -> Result<()> {
3119 let conn = Connection::open_in_memory()?;
3120 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3121 let now = SystemTime::now();
3122 let duration = Duration::from_secs(1000);
3123 let then = now.checked_sub(duration).unwrap();
3124 let soon = now.checked_add(duration).unwrap();
3125 conn.execute(
3126 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3127 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3128 )?;
3129 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3130 let mut rows = stmt.query(NO_PARAMS)?;
3131 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3132 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3133 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3134 assert!(rows.next()?.is_none());
3135 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3136 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3137 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3138 Ok(())
3139 }
3140
Joel Galenson0891bc12020-07-20 10:37:03 -07003141 // Ensure that we're using the "injected" random function, not the real one.
3142 #[test]
3143 fn test_mocked_random() {
3144 let rand1 = random();
3145 let rand2 = random();
3146 let rand3 = random();
3147 if rand1 == rand2 {
3148 assert_eq!(rand2 + 1, rand3);
3149 } else {
3150 assert_eq!(rand1 + 1, rand2);
3151 assert_eq!(rand2, rand3);
3152 }
3153 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003154
Joel Galenson26f4d012020-07-17 14:57:21 -07003155 // Test that we have the correct tables.
3156 #[test]
3157 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003158 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003159 let tables = db
3160 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003161 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003162 .query_map(params![], |row| row.get(0))?
3163 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003164 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003165 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003166 assert_eq!(tables[1], "blobmetadata");
3167 assert_eq!(tables[2], "grant");
3168 assert_eq!(tables[3], "keyentry");
3169 assert_eq!(tables[4], "keymetadata");
3170 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003171 let tables = db
3172 .conn
3173 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3174 .query_map(params![], |row| row.get(0))?
3175 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003176
3177 assert_eq!(tables.len(), 2);
3178 assert_eq!(tables[0], "authtoken");
3179 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003180 Ok(())
3181 }
3182
3183 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003184 fn test_auth_token_table_invariant() -> Result<()> {
3185 let mut db = new_test_db()?;
3186 let auth_token1 = HardwareAuthToken {
3187 challenge: i64::MAX,
3188 userId: 200,
3189 authenticatorId: 200,
3190 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3191 timestamp: Timestamp { milliSeconds: 500 },
3192 mac: String::from("mac").into_bytes(),
3193 };
3194 db.insert_auth_token(&auth_token1)?;
3195 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3196 assert_eq!(auth_tokens_returned.len(), 1);
3197
3198 // insert another auth token with the same values for the columns in the UNIQUE constraint
3199 // of the auth token table and different value for timestamp
3200 let auth_token2 = HardwareAuthToken {
3201 challenge: i64::MAX,
3202 userId: 200,
3203 authenticatorId: 200,
3204 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3205 timestamp: Timestamp { milliSeconds: 600 },
3206 mac: String::from("mac").into_bytes(),
3207 };
3208
3209 db.insert_auth_token(&auth_token2)?;
3210 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3211 assert_eq!(auth_tokens_returned.len(), 1);
3212
3213 if let Some(auth_token) = auth_tokens_returned.pop() {
3214 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3215 }
3216
3217 // insert another auth token with the different values for the columns in the UNIQUE
3218 // constraint of the auth token table
3219 let auth_token3 = HardwareAuthToken {
3220 challenge: i64::MAX,
3221 userId: 201,
3222 authenticatorId: 200,
3223 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3224 timestamp: Timestamp { milliSeconds: 600 },
3225 mac: String::from("mac").into_bytes(),
3226 };
3227
3228 db.insert_auth_token(&auth_token3)?;
3229 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3230 assert_eq!(auth_tokens_returned.len(), 2);
3231
3232 Ok(())
3233 }
3234
3235 // utility function for test_auth_token_table_invariant()
3236 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3237 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3238
3239 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3240 .query_map(NO_PARAMS, |row| {
3241 Ok(AuthTokenEntry::new(
3242 HardwareAuthToken {
3243 challenge: row.get(1)?,
3244 userId: row.get(2)?,
3245 authenticatorId: row.get(3)?,
3246 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3247 timestamp: Timestamp { milliSeconds: row.get(5)? },
3248 mac: row.get(6)?,
3249 },
3250 row.get(7)?,
3251 ))
3252 })?
3253 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3254 Ok(auth_token_entries)
3255 }
3256
3257 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003258 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003259 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003260 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003261
Janis Danisevskis66784c42021-01-27 08:40:25 -08003262 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003263 let entries = get_keyentry(&db)?;
3264 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003265
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003266 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003267
3268 let entries_new = get_keyentry(&db)?;
3269 assert_eq!(entries, entries_new);
3270 Ok(())
3271 }
3272
3273 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003274 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003275 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3276 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003277 }
3278
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003279 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003280
Janis Danisevskis66784c42021-01-27 08:40:25 -08003281 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3282 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003283
3284 let entries = get_keyentry(&db)?;
3285 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003286 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3287 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003288
3289 // Test that we must pass in a valid Domain.
3290 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003291 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003292 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003293 );
3294 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003295 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003296 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003297 );
3298 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003299 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003300 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003301 );
3302
3303 Ok(())
3304 }
3305
Joel Galenson33c04ad2020-08-03 11:04:38 -07003306 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003307 fn test_add_unsigned_key() -> Result<()> {
3308 let mut db = new_test_db()?;
3309 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3310 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3311 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3312 db.create_attestation_key_entry(
3313 &public_key,
3314 &raw_public_key,
3315 &private_key,
3316 &KEYSTORE_UUID,
3317 )?;
3318 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3319 assert_eq!(keys.len(), 1);
3320 assert_eq!(keys[0], public_key);
3321 Ok(())
3322 }
3323
3324 #[test]
3325 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3326 let mut db = new_test_db()?;
3327 let expiration_date: i64 = 20;
3328 let namespace: i64 = 30;
3329 let base_byte: u8 = 1;
3330 let loaded_values =
3331 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3332 let chain =
3333 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3334 assert_eq!(true, chain.is_some());
3335 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003336 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003337 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3338 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003339 Ok(())
3340 }
3341
3342 #[test]
3343 fn test_get_attestation_pool_status() -> Result<()> {
3344 let mut db = new_test_db()?;
3345 let namespace: i64 = 30;
3346 load_attestation_key_pool(
3347 &mut db, 10, /* expiration */
3348 namespace, 0x01, /* base_byte */
3349 )?;
3350 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3351 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3352 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3353 assert_eq!(status.expiring, 0);
3354 assert_eq!(status.attested, 3);
3355 assert_eq!(status.unassigned, 0);
3356 assert_eq!(status.total, 3);
3357 assert_eq!(
3358 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3359 1
3360 );
3361 assert_eq!(
3362 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3363 2
3364 );
3365 assert_eq!(
3366 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3367 3
3368 );
3369 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3370 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3371 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3372 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003373 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003374 db.create_attestation_key_entry(
3375 &public_key,
3376 &raw_public_key,
3377 &private_key,
3378 &KEYSTORE_UUID,
3379 )?;
3380 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3381 assert_eq!(status.attested, 3);
3382 assert_eq!(status.unassigned, 0);
3383 assert_eq!(status.total, 4);
3384 db.store_signed_attestation_certificate_chain(
3385 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003386 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003387 &cert_chain,
3388 20,
3389 &KEYSTORE_UUID,
3390 )?;
3391 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3392 assert_eq!(status.attested, 4);
3393 assert_eq!(status.unassigned, 1);
3394 assert_eq!(status.total, 4);
3395 Ok(())
3396 }
3397
3398 #[test]
3399 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003400 let temp_dir =
3401 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3402 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003403 let expiration_date: i64 =
3404 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3405 let namespace: i64 = 30;
3406 let namespace_del1: i64 = 45;
3407 let namespace_del2: i64 = 60;
3408 let entry_values = load_attestation_key_pool(
3409 &mut db,
3410 expiration_date,
3411 namespace,
3412 0x01, /* base_byte */
3413 )?;
3414 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3415 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003416
3417 let blob_entry_row_count: u32 = db
3418 .conn
3419 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3420 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003421 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3422 // one key, one certificate chain, and one certificate.
3423 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003424
Max Bires2b2e6562020-09-22 11:22:36 -07003425 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3426
3427 let mut cert_chain =
3428 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003429 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003430 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003431 assert_eq!(entry_values.batch_cert, value.batch_cert);
3432 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003433 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003434
3435 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3436 Domain::APP,
3437 namespace_del1,
3438 &KEYSTORE_UUID,
3439 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003440 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003441 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3442 Domain::APP,
3443 namespace_del2,
3444 &KEYSTORE_UUID,
3445 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003446 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003447
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003448 // Give the garbage collector half a second to catch up.
3449 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003450
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003451 let blob_entry_row_count: u32 = db
3452 .conn
3453 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3454 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003455 // There shound be 3 blob entries left, because we deleted two of the attestation
3456 // key entries with three blobs each.
3457 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003458
Max Bires2b2e6562020-09-22 11:22:36 -07003459 Ok(())
3460 }
3461
3462 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003463 fn test_delete_all_attestation_keys() -> Result<()> {
3464 let mut db = new_test_db()?;
3465 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3466 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3467 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3468 let result = db.delete_all_attestation_keys()?;
3469
3470 // Give the garbage collector half a second to catch up.
3471 std::thread::sleep(Duration::from_millis(500));
3472
3473 // Attestation keys should be deleted, and the regular key should remain.
3474 assert_eq!(result, 2);
3475
3476 Ok(())
3477 }
3478
3479 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003480 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003481 fn extractor(
3482 ke: &KeyEntryRow,
3483 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3484 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003485 }
3486
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003487 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003488 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3489 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003490 let entries = get_keyentry(&db)?;
3491 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003492 assert_eq!(
3493 extractor(&entries[0]),
3494 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3495 );
3496 assert_eq!(
3497 extractor(&entries[1]),
3498 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3499 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003500
3501 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003502 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003503 let entries = get_keyentry(&db)?;
3504 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003505 assert_eq!(
3506 extractor(&entries[0]),
3507 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3508 );
3509 assert_eq!(
3510 extractor(&entries[1]),
3511 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3512 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003513
3514 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003515 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003516 let entries = get_keyentry(&db)?;
3517 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003518 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3519 assert_eq!(
3520 extractor(&entries[1]),
3521 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3522 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003523
3524 // Test that we must pass in a valid Domain.
3525 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003526 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003527 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003528 );
3529 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003530 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003531 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003532 );
3533 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003534 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003535 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003536 );
3537
3538 // Test that we correctly handle setting an alias for something that does not exist.
3539 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003540 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003541 "Expected to update a single entry but instead updated 0",
3542 );
3543 // Test that we correctly abort the transaction in this case.
3544 let entries = get_keyentry(&db)?;
3545 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003546 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3547 assert_eq!(
3548 extractor(&entries[1]),
3549 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3550 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003551
3552 Ok(())
3553 }
3554
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003555 #[test]
3556 fn test_grant_ungrant() -> Result<()> {
3557 const CALLER_UID: u32 = 15;
3558 const GRANTEE_UID: u32 = 12;
3559 const SELINUX_NAMESPACE: i64 = 7;
3560
3561 let mut db = new_test_db()?;
3562 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003563 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3564 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3565 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003566 )?;
3567 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003568 domain: super::Domain::APP,
3569 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003570 alias: Some("key".to_string()),
3571 blob: None,
3572 };
3573 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3574 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3575
3576 // Reset totally predictable random number generator in case we
3577 // are not the first test running on this thread.
3578 reset_random();
3579 let next_random = 0i64;
3580
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003581 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003582 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003583 assert_eq!(*a, PVEC1);
3584 assert_eq!(
3585 *k,
3586 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003587 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003588 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003589 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003590 alias: Some("key".to_string()),
3591 blob: None,
3592 }
3593 );
3594 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003595 })
3596 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003597
3598 assert_eq!(
3599 app_granted_key,
3600 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003601 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003602 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003603 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003604 alias: None,
3605 blob: None,
3606 }
3607 );
3608
3609 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003610 domain: super::Domain::SELINUX,
3611 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003612 alias: Some("yek".to_string()),
3613 blob: None,
3614 };
3615
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003616 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003617 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003618 assert_eq!(*a, PVEC1);
3619 assert_eq!(
3620 *k,
3621 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003622 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003623 // namespace must be the supplied SELinux
3624 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003625 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003626 alias: Some("yek".to_string()),
3627 blob: None,
3628 }
3629 );
3630 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003631 })
3632 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003633
3634 assert_eq!(
3635 selinux_granted_key,
3636 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003637 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003638 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003639 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003640 alias: None,
3641 blob: None,
3642 }
3643 );
3644
3645 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003646 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003647 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003648 assert_eq!(*a, PVEC2);
3649 assert_eq!(
3650 *k,
3651 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003652 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003653 // namespace must be the supplied SELinux
3654 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003655 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003656 alias: Some("yek".to_string()),
3657 blob: None,
3658 }
3659 );
3660 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003661 })
3662 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003663
3664 assert_eq!(
3665 selinux_granted_key,
3666 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003667 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003668 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003669 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003670 alias: None,
3671 blob: None,
3672 }
3673 );
3674
3675 {
3676 // Limiting scope of stmt, because it borrows db.
3677 let mut stmt = db
3678 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003679 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003680 let mut rows =
3681 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3682 Ok((
3683 row.get(0)?,
3684 row.get(1)?,
3685 row.get(2)?,
3686 KeyPermSet::from(row.get::<_, i32>(3)?),
3687 ))
3688 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003689
3690 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003691 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003692 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003693 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003694 assert!(rows.next().is_none());
3695 }
3696
3697 debug_dump_keyentry_table(&mut db)?;
3698 println!("app_key {:?}", app_key);
3699 println!("selinux_key {:?}", selinux_key);
3700
Janis Danisevskis66784c42021-01-27 08:40:25 -08003701 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3702 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003703
3704 Ok(())
3705 }
3706
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003707 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003708 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3709 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3710
3711 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003712 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003713 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003714 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003715 let mut blob_metadata = BlobMetaData::new();
3716 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3717 db.set_blob(
3718 &key_id,
3719 SubComponentType::KEY_BLOB,
3720 Some(TEST_KEY_BLOB),
3721 Some(&blob_metadata),
3722 )?;
3723 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3724 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003725 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003726
3727 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003728 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003729 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003730 )?;
3731 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003732 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3733 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003734 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003735 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003736 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003737 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003738 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003739 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003740 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003741
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003742 drop(rows);
3743 drop(stmt);
3744
3745 assert_eq!(
3746 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3747 BlobMetaData::load_from_db(id, tx).no_gc()
3748 })
3749 .expect("Should find blob metadata."),
3750 blob_metadata
3751 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003752 Ok(())
3753 }
3754
3755 static TEST_ALIAS: &str = "my super duper key";
3756
3757 #[test]
3758 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3759 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003760 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003761 .context("test_insert_and_load_full_keyentry_domain_app")?
3762 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003763 let (_key_guard, key_entry) = db
3764 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003765 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003766 domain: Domain::APP,
3767 nspace: 0,
3768 alias: Some(TEST_ALIAS.to_string()),
3769 blob: None,
3770 },
3771 KeyType::Client,
3772 KeyEntryLoadBits::BOTH,
3773 1,
3774 |_k, _av| Ok(()),
3775 )
3776 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003777 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003778
3779 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003780 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003781 domain: Domain::APP,
3782 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003783 alias: Some(TEST_ALIAS.to_string()),
3784 blob: None,
3785 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003786 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003787 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003788 |_, _| Ok(()),
3789 )
3790 .unwrap();
3791
3792 assert_eq!(
3793 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3794 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003795 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003796 domain: Domain::APP,
3797 nspace: 0,
3798 alias: Some(TEST_ALIAS.to_string()),
3799 blob: None,
3800 },
3801 KeyType::Client,
3802 KeyEntryLoadBits::NONE,
3803 1,
3804 |_k, _av| Ok(()),
3805 )
3806 .unwrap_err()
3807 .root_cause()
3808 .downcast_ref::<KsError>()
3809 );
3810
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003811 Ok(())
3812 }
3813
3814 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003815 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3816 let mut db = new_test_db()?;
3817
3818 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003819 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003820 domain: Domain::APP,
3821 nspace: 1,
3822 alias: Some(TEST_ALIAS.to_string()),
3823 blob: None,
3824 },
3825 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003826 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003827 )
3828 .expect("Trying to insert cert.");
3829
3830 let (_key_guard, mut key_entry) = db
3831 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003832 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003833 domain: Domain::APP,
3834 nspace: 1,
3835 alias: Some(TEST_ALIAS.to_string()),
3836 blob: None,
3837 },
3838 KeyType::Client,
3839 KeyEntryLoadBits::PUBLIC,
3840 1,
3841 |_k, _av| Ok(()),
3842 )
3843 .expect("Trying to read certificate entry.");
3844
3845 assert!(key_entry.pure_cert());
3846 assert!(key_entry.cert().is_none());
3847 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3848
3849 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003850 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003851 domain: Domain::APP,
3852 nspace: 1,
3853 alias: Some(TEST_ALIAS.to_string()),
3854 blob: None,
3855 },
3856 KeyType::Client,
3857 1,
3858 |_, _| Ok(()),
3859 )
3860 .unwrap();
3861
3862 assert_eq!(
3863 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3864 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003865 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003866 domain: Domain::APP,
3867 nspace: 1,
3868 alias: Some(TEST_ALIAS.to_string()),
3869 blob: None,
3870 },
3871 KeyType::Client,
3872 KeyEntryLoadBits::NONE,
3873 1,
3874 |_k, _av| Ok(()),
3875 )
3876 .unwrap_err()
3877 .root_cause()
3878 .downcast_ref::<KsError>()
3879 );
3880
3881 Ok(())
3882 }
3883
3884 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003885 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3886 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003887 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003888 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3889 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003890 let (_key_guard, key_entry) = db
3891 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003892 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003893 domain: Domain::SELINUX,
3894 nspace: 1,
3895 alias: Some(TEST_ALIAS.to_string()),
3896 blob: None,
3897 },
3898 KeyType::Client,
3899 KeyEntryLoadBits::BOTH,
3900 1,
3901 |_k, _av| Ok(()),
3902 )
3903 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003904 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003905
3906 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003907 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003908 domain: Domain::SELINUX,
3909 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003910 alias: Some(TEST_ALIAS.to_string()),
3911 blob: None,
3912 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003913 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003914 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003915 |_, _| Ok(()),
3916 )
3917 .unwrap();
3918
3919 assert_eq!(
3920 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3921 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003922 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003923 domain: Domain::SELINUX,
3924 nspace: 1,
3925 alias: Some(TEST_ALIAS.to_string()),
3926 blob: None,
3927 },
3928 KeyType::Client,
3929 KeyEntryLoadBits::NONE,
3930 1,
3931 |_k, _av| Ok(()),
3932 )
3933 .unwrap_err()
3934 .root_cause()
3935 .downcast_ref::<KsError>()
3936 );
3937
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003938 Ok(())
3939 }
3940
3941 #[test]
3942 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3943 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003944 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003945 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3946 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003947 let (_, key_entry) = db
3948 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003949 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003950 KeyType::Client,
3951 KeyEntryLoadBits::BOTH,
3952 1,
3953 |_k, _av| Ok(()),
3954 )
3955 .unwrap();
3956
Qi Wub9433b52020-12-01 14:52:46 +08003957 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003958
3959 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003960 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003961 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003962 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003963 |_, _| Ok(()),
3964 )
3965 .unwrap();
3966
3967 assert_eq!(
3968 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3969 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003970 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003971 KeyType::Client,
3972 KeyEntryLoadBits::NONE,
3973 1,
3974 |_k, _av| Ok(()),
3975 )
3976 .unwrap_err()
3977 .root_cause()
3978 .downcast_ref::<KsError>()
3979 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003980
3981 Ok(())
3982 }
3983
3984 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003985 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3986 let mut db = new_test_db()?;
3987 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3988 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3989 .0;
3990 // Update the usage count of the limited use key.
3991 db.check_and_update_key_usage_count(key_id)?;
3992
3993 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003994 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003995 KeyType::Client,
3996 KeyEntryLoadBits::BOTH,
3997 1,
3998 |_k, _av| Ok(()),
3999 )?;
4000
4001 // The usage count is decremented now.
4002 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4003
4004 Ok(())
4005 }
4006
4007 #[test]
4008 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4009 let mut db = new_test_db()?;
4010 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4011 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4012 .0;
4013 // Update the usage count of the limited use key.
4014 db.check_and_update_key_usage_count(key_id).expect(concat!(
4015 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4016 "This should succeed."
4017 ));
4018
4019 // Try to update the exhausted limited use key.
4020 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4021 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4022 "This should fail."
4023 ));
4024 assert_eq!(
4025 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4026 e.root_cause().downcast_ref::<KsError>().unwrap()
4027 );
4028
4029 Ok(())
4030 }
4031
4032 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004033 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4034 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004035 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004036 .context("test_insert_and_load_full_keyentry_from_grant")?
4037 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004038
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004039 let granted_key = db
4040 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004041 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004042 domain: Domain::APP,
4043 nspace: 0,
4044 alias: Some(TEST_ALIAS.to_string()),
4045 blob: None,
4046 },
4047 1,
4048 2,
4049 key_perm_set![KeyPerm::use_()],
4050 |_k, _av| Ok(()),
4051 )
4052 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004053
4054 debug_dump_grant_table(&mut db)?;
4055
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004056 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004057 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4058 assert_eq!(Domain::GRANT, k.domain);
4059 assert!(av.unwrap().includes(KeyPerm::use_()));
4060 Ok(())
4061 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004062 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004063
Qi Wub9433b52020-12-01 14:52:46 +08004064 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004065
Janis Danisevskis66784c42021-01-27 08:40:25 -08004066 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004067
4068 assert_eq!(
4069 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4070 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004071 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004072 KeyType::Client,
4073 KeyEntryLoadBits::NONE,
4074 2,
4075 |_k, _av| Ok(()),
4076 )
4077 .unwrap_err()
4078 .root_cause()
4079 .downcast_ref::<KsError>()
4080 );
4081
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004082 Ok(())
4083 }
4084
Janis Danisevskis45760022021-01-19 16:34:10 -08004085 // This test attempts to load a key by key id while the caller is not the owner
4086 // but a grant exists for the given key and the caller.
4087 #[test]
4088 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4089 let mut db = new_test_db()?;
4090 const OWNER_UID: u32 = 1u32;
4091 const GRANTEE_UID: u32 = 2u32;
4092 const SOMEONE_ELSE_UID: u32 = 3u32;
4093 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4094 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4095 .0;
4096
4097 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004098 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004099 domain: Domain::APP,
4100 nspace: 0,
4101 alias: Some(TEST_ALIAS.to_string()),
4102 blob: None,
4103 },
4104 OWNER_UID,
4105 GRANTEE_UID,
4106 key_perm_set![KeyPerm::use_()],
4107 |_k, _av| Ok(()),
4108 )
4109 .unwrap();
4110
4111 debug_dump_grant_table(&mut db)?;
4112
4113 let id_descriptor =
4114 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4115
4116 let (_, key_entry) = db
4117 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004118 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004119 KeyType::Client,
4120 KeyEntryLoadBits::BOTH,
4121 GRANTEE_UID,
4122 |k, av| {
4123 assert_eq!(Domain::APP, k.domain);
4124 assert_eq!(OWNER_UID as i64, k.nspace);
4125 assert!(av.unwrap().includes(KeyPerm::use_()));
4126 Ok(())
4127 },
4128 )
4129 .unwrap();
4130
4131 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4132
4133 let (_, key_entry) = db
4134 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004135 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004136 KeyType::Client,
4137 KeyEntryLoadBits::BOTH,
4138 SOMEONE_ELSE_UID,
4139 |k, av| {
4140 assert_eq!(Domain::APP, k.domain);
4141 assert_eq!(OWNER_UID as i64, k.nspace);
4142 assert!(av.is_none());
4143 Ok(())
4144 },
4145 )
4146 .unwrap();
4147
4148 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4149
Janis Danisevskis66784c42021-01-27 08:40:25 -08004150 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004151
4152 assert_eq!(
4153 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4154 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004155 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004156 KeyType::Client,
4157 KeyEntryLoadBits::NONE,
4158 GRANTEE_UID,
4159 |_k, _av| Ok(()),
4160 )
4161 .unwrap_err()
4162 .root_cause()
4163 .downcast_ref::<KsError>()
4164 );
4165
4166 Ok(())
4167 }
4168
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004169 // Creates a key migrates it to a different location and then tries to access it by the old
4170 // and new location.
4171 #[test]
4172 fn test_migrate_key_app_to_app() -> Result<()> {
4173 let mut db = new_test_db()?;
4174 const SOURCE_UID: u32 = 1u32;
4175 const DESTINATION_UID: u32 = 2u32;
4176 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4177 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4178 let key_id_guard =
4179 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4180 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4181
4182 let source_descriptor: KeyDescriptor = KeyDescriptor {
4183 domain: Domain::APP,
4184 nspace: -1,
4185 alias: Some(SOURCE_ALIAS.to_string()),
4186 blob: None,
4187 };
4188
4189 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4190 domain: Domain::APP,
4191 nspace: -1,
4192 alias: Some(DESTINATION_ALIAS.to_string()),
4193 blob: None,
4194 };
4195
4196 let key_id = key_id_guard.id();
4197
4198 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4199 Ok(())
4200 })
4201 .unwrap();
4202
4203 let (_, key_entry) = db
4204 .load_key_entry(
4205 &destination_descriptor,
4206 KeyType::Client,
4207 KeyEntryLoadBits::BOTH,
4208 DESTINATION_UID,
4209 |k, av| {
4210 assert_eq!(Domain::APP, k.domain);
4211 assert_eq!(DESTINATION_UID as i64, k.nspace);
4212 assert!(av.is_none());
4213 Ok(())
4214 },
4215 )
4216 .unwrap();
4217
4218 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4219
4220 assert_eq!(
4221 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4222 db.load_key_entry(
4223 &source_descriptor,
4224 KeyType::Client,
4225 KeyEntryLoadBits::NONE,
4226 SOURCE_UID,
4227 |_k, _av| Ok(()),
4228 )
4229 .unwrap_err()
4230 .root_cause()
4231 .downcast_ref::<KsError>()
4232 );
4233
4234 Ok(())
4235 }
4236
4237 // Creates a key migrates it to a different location and then tries to access it by the old
4238 // and new location.
4239 #[test]
4240 fn test_migrate_key_app_to_selinux() -> Result<()> {
4241 let mut db = new_test_db()?;
4242 const SOURCE_UID: u32 = 1u32;
4243 const DESTINATION_UID: u32 = 2u32;
4244 const DESTINATION_NAMESPACE: i64 = 1000i64;
4245 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4246 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4247 let key_id_guard =
4248 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4249 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4250
4251 let source_descriptor: KeyDescriptor = KeyDescriptor {
4252 domain: Domain::APP,
4253 nspace: -1,
4254 alias: Some(SOURCE_ALIAS.to_string()),
4255 blob: None,
4256 };
4257
4258 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4259 domain: Domain::SELINUX,
4260 nspace: DESTINATION_NAMESPACE,
4261 alias: Some(DESTINATION_ALIAS.to_string()),
4262 blob: None,
4263 };
4264
4265 let key_id = key_id_guard.id();
4266
4267 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4268 Ok(())
4269 })
4270 .unwrap();
4271
4272 let (_, key_entry) = db
4273 .load_key_entry(
4274 &destination_descriptor,
4275 KeyType::Client,
4276 KeyEntryLoadBits::BOTH,
4277 DESTINATION_UID,
4278 |k, av| {
4279 assert_eq!(Domain::SELINUX, k.domain);
4280 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4281 assert!(av.is_none());
4282 Ok(())
4283 },
4284 )
4285 .unwrap();
4286
4287 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4288
4289 assert_eq!(
4290 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4291 db.load_key_entry(
4292 &source_descriptor,
4293 KeyType::Client,
4294 KeyEntryLoadBits::NONE,
4295 SOURCE_UID,
4296 |_k, _av| Ok(()),
4297 )
4298 .unwrap_err()
4299 .root_cause()
4300 .downcast_ref::<KsError>()
4301 );
4302
4303 Ok(())
4304 }
4305
4306 // Creates two keys and tries to migrate the first to the location of the second which
4307 // is expected to fail.
4308 #[test]
4309 fn test_migrate_key_destination_occupied() -> Result<()> {
4310 let mut db = new_test_db()?;
4311 const SOURCE_UID: u32 = 1u32;
4312 const DESTINATION_UID: u32 = 2u32;
4313 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4314 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4315 let key_id_guard =
4316 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4317 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4318 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4319 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4320
4321 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4322 domain: Domain::APP,
4323 nspace: -1,
4324 alias: Some(DESTINATION_ALIAS.to_string()),
4325 blob: None,
4326 };
4327
4328 assert_eq!(
4329 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4330 db.migrate_key_namespace(
4331 key_id_guard,
4332 &destination_descriptor,
4333 DESTINATION_UID,
4334 |_k| Ok(())
4335 )
4336 .unwrap_err()
4337 .root_cause()
4338 .downcast_ref::<KsError>()
4339 );
4340
4341 Ok(())
4342 }
4343
Janis Danisevskisaec14592020-11-12 09:41:49 -08004344 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4345
Janis Danisevskisaec14592020-11-12 09:41:49 -08004346 #[test]
4347 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4348 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004349 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4350 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004351 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004352 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004353 .context("test_insert_and_load_full_keyentry_domain_app")?
4354 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004355 let (_key_guard, key_entry) = db
4356 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004357 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004358 domain: Domain::APP,
4359 nspace: 0,
4360 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4361 blob: None,
4362 },
4363 KeyType::Client,
4364 KeyEntryLoadBits::BOTH,
4365 33,
4366 |_k, _av| Ok(()),
4367 )
4368 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004369 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004370 let state = Arc::new(AtomicU8::new(1));
4371 let state2 = state.clone();
4372
4373 // Spawning a second thread that attempts to acquire the key id lock
4374 // for the same key as the primary thread. The primary thread then
4375 // waits, thereby forcing the secondary thread into the second stage
4376 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4377 // The test succeeds if the secondary thread observes the transition
4378 // of `state` from 1 to 2, despite having a whole second to overtake
4379 // the primary thread.
4380 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004381 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004382 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004383 assert!(db
4384 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004385 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004386 domain: Domain::APP,
4387 nspace: 0,
4388 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4389 blob: None,
4390 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004391 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004392 KeyEntryLoadBits::BOTH,
4393 33,
4394 |_k, _av| Ok(()),
4395 )
4396 .is_ok());
4397 // We should only see a 2 here because we can only return
4398 // from load_key_entry when the `_key_guard` expires,
4399 // which happens at the end of the scope.
4400 assert_eq!(2, state2.load(Ordering::Relaxed));
4401 });
4402
4403 thread::sleep(std::time::Duration::from_millis(1000));
4404
4405 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4406
4407 // Return the handle from this scope so we can join with the
4408 // secondary thread after the key id lock has expired.
4409 handle
4410 // This is where the `_key_guard` goes out of scope,
4411 // which is the reason for concurrent load_key_entry on the same key
4412 // to unblock.
4413 };
4414 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4415 // main test thread. We will not see failing asserts in secondary threads otherwise.
4416 handle.join().unwrap();
4417 Ok(())
4418 }
4419
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004420 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004421 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004422 let temp_dir =
4423 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4424
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004425 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4426 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004427
4428 let _tx1 = db1
4429 .conn
4430 .transaction_with_behavior(TransactionBehavior::Immediate)
4431 .expect("Failed to create first transaction.");
4432
4433 let error = db2
4434 .conn
4435 .transaction_with_behavior(TransactionBehavior::Immediate)
4436 .context("Transaction begin failed.")
4437 .expect_err("This should fail.");
4438 let root_cause = error.root_cause();
4439 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4440 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4441 {
4442 return;
4443 }
4444 panic!(
4445 "Unexpected error {:?} \n{:?} \n{:?}",
4446 error,
4447 root_cause,
4448 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4449 )
4450 }
4451
4452 #[cfg(disabled)]
4453 #[test]
4454 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4455 let temp_dir = Arc::new(
4456 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4457 .expect("Failed to create temp dir."),
4458 );
4459
4460 let test_begin = Instant::now();
4461
4462 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4463 const KEY_COUNT: u32 = 500u32;
4464 const OPEN_DB_COUNT: u32 = 50u32;
4465
4466 let mut actual_key_count = KEY_COUNT;
4467 // First insert KEY_COUNT keys.
4468 for count in 0..KEY_COUNT {
4469 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4470 actual_key_count = count;
4471 break;
4472 }
4473 let alias = format!("test_alias_{}", count);
4474 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4475 .expect("Failed to make key entry.");
4476 }
4477
4478 // Insert more keys from a different thread and into a different namespace.
4479 let temp_dir1 = temp_dir.clone();
4480 let handle1 = thread::spawn(move || {
4481 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4482
4483 for count in 0..actual_key_count {
4484 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4485 return;
4486 }
4487 let alias = format!("test_alias_{}", count);
4488 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4489 .expect("Failed to make key entry.");
4490 }
4491
4492 // then unbind them again.
4493 for count in 0..actual_key_count {
4494 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4495 return;
4496 }
4497 let key = KeyDescriptor {
4498 domain: Domain::APP,
4499 nspace: -1,
4500 alias: Some(format!("test_alias_{}", count)),
4501 blob: None,
4502 };
4503 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4504 }
4505 });
4506
4507 // And start unbinding the first set of keys.
4508 let temp_dir2 = temp_dir.clone();
4509 let handle2 = thread::spawn(move || {
4510 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4511
4512 for count in 0..actual_key_count {
4513 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4514 return;
4515 }
4516 let key = KeyDescriptor {
4517 domain: Domain::APP,
4518 nspace: -1,
4519 alias: Some(format!("test_alias_{}", count)),
4520 blob: None,
4521 };
4522 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4523 }
4524 });
4525
4526 let stop_deleting = Arc::new(AtomicU8::new(0));
4527 let stop_deleting2 = stop_deleting.clone();
4528
4529 // And delete anything that is unreferenced keys.
4530 let temp_dir3 = temp_dir.clone();
4531 let handle3 = thread::spawn(move || {
4532 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4533
4534 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4535 while let Some((key_guard, _key)) =
4536 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4537 {
4538 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4539 return;
4540 }
4541 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4542 }
4543 std::thread::sleep(std::time::Duration::from_millis(100));
4544 }
4545 });
4546
4547 // While a lot of inserting and deleting is going on we have to open database connections
4548 // successfully and use them.
4549 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4550 // out of scope.
4551 #[allow(clippy::redundant_clone)]
4552 let temp_dir4 = temp_dir.clone();
4553 let handle4 = thread::spawn(move || {
4554 for count in 0..OPEN_DB_COUNT {
4555 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4556 return;
4557 }
4558 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4559
4560 let alias = format!("test_alias_{}", count);
4561 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4562 .expect("Failed to make key entry.");
4563 let key = KeyDescriptor {
4564 domain: Domain::APP,
4565 nspace: -1,
4566 alias: Some(alias),
4567 blob: None,
4568 };
4569 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4570 }
4571 });
4572
4573 handle1.join().expect("Thread 1 panicked.");
4574 handle2.join().expect("Thread 2 panicked.");
4575 handle4.join().expect("Thread 4 panicked.");
4576
4577 stop_deleting.store(1, Ordering::Relaxed);
4578 handle3.join().expect("Thread 3 panicked.");
4579
4580 Ok(())
4581 }
4582
4583 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004584 fn list() -> Result<()> {
4585 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004586 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004587 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4588 (Domain::APP, 1, "test1"),
4589 (Domain::APP, 1, "test2"),
4590 (Domain::APP, 1, "test3"),
4591 (Domain::APP, 1, "test4"),
4592 (Domain::APP, 1, "test5"),
4593 (Domain::APP, 1, "test6"),
4594 (Domain::APP, 1, "test7"),
4595 (Domain::APP, 2, "test1"),
4596 (Domain::APP, 2, "test2"),
4597 (Domain::APP, 2, "test3"),
4598 (Domain::APP, 2, "test4"),
4599 (Domain::APP, 2, "test5"),
4600 (Domain::APP, 2, "test6"),
4601 (Domain::APP, 2, "test8"),
4602 (Domain::SELINUX, 100, "test1"),
4603 (Domain::SELINUX, 100, "test2"),
4604 (Domain::SELINUX, 100, "test3"),
4605 (Domain::SELINUX, 100, "test4"),
4606 (Domain::SELINUX, 100, "test5"),
4607 (Domain::SELINUX, 100, "test6"),
4608 (Domain::SELINUX, 100, "test9"),
4609 ];
4610
4611 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4612 .iter()
4613 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004614 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4615 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004616 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4617 });
4618 (entry.id(), *ns)
4619 })
4620 .collect();
4621
4622 for (domain, namespace) in
4623 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4624 {
4625 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4626 .iter()
4627 .filter_map(|(domain, ns, alias)| match ns {
4628 ns if *ns == *namespace => Some(KeyDescriptor {
4629 domain: *domain,
4630 nspace: *ns,
4631 alias: Some(alias.to_string()),
4632 blob: None,
4633 }),
4634 _ => None,
4635 })
4636 .collect();
4637 list_o_descriptors.sort();
4638 let mut list_result = db.list(*domain, *namespace)?;
4639 list_result.sort();
4640 assert_eq!(list_o_descriptors, list_result);
4641
4642 let mut list_o_ids: Vec<i64> = list_o_descriptors
4643 .into_iter()
4644 .map(|d| {
4645 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004646 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004647 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004648 KeyType::Client,
4649 KeyEntryLoadBits::NONE,
4650 *namespace as u32,
4651 |_, _| Ok(()),
4652 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004653 .unwrap();
4654 entry.id()
4655 })
4656 .collect();
4657 list_o_ids.sort_unstable();
4658 let mut loaded_entries: Vec<i64> = list_o_keys
4659 .iter()
4660 .filter_map(|(id, ns)| match ns {
4661 ns if *ns == *namespace => Some(*id),
4662 _ => None,
4663 })
4664 .collect();
4665 loaded_entries.sort_unstable();
4666 assert_eq!(list_o_ids, loaded_entries);
4667 }
4668 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4669
4670 Ok(())
4671 }
4672
Joel Galenson0891bc12020-07-20 10:37:03 -07004673 // Helpers
4674
4675 // Checks that the given result is an error containing the given string.
4676 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4677 let error_str = format!(
4678 "{:#?}",
4679 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4680 );
4681 assert!(
4682 error_str.contains(target),
4683 "The string \"{}\" should contain \"{}\"",
4684 error_str,
4685 target
4686 );
4687 }
4688
Joel Galenson2aab4432020-07-22 15:27:57 -07004689 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004690 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004691 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004692 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004693 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004694 namespace: Option<i64>,
4695 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004696 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004697 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004698 }
4699
4700 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4701 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004702 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004703 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004704 Ok(KeyEntryRow {
4705 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004706 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004707 domain: match row.get(2)? {
4708 Some(i) => Some(Domain(i)),
4709 None => None,
4710 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004711 namespace: row.get(3)?,
4712 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004713 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004714 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004715 })
4716 })?
4717 .map(|r| r.context("Could not read keyentry row."))
4718 .collect::<Result<Vec<_>>>()
4719 }
4720
Max Biresb2e1d032021-02-08 21:35:05 -08004721 struct RemoteProvValues {
4722 cert_chain: Vec<u8>,
4723 priv_key: Vec<u8>,
4724 batch_cert: Vec<u8>,
4725 }
4726
Max Bires2b2e6562020-09-22 11:22:36 -07004727 fn load_attestation_key_pool(
4728 db: &mut KeystoreDB,
4729 expiration_date: i64,
4730 namespace: i64,
4731 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004732 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004733 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4734 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4735 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4736 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004737 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004738 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4739 db.store_signed_attestation_certificate_chain(
4740 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004741 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004742 &cert_chain,
4743 expiration_date,
4744 &KEYSTORE_UUID,
4745 )?;
4746 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004747 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004748 }
4749
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004750 // Note: The parameters and SecurityLevel associations are nonsensical. This
4751 // collection is only used to check if the parameters are preserved as expected by the
4752 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004753 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4754 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004755 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4756 KeyParameter::new(
4757 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4758 SecurityLevel::TRUSTED_ENVIRONMENT,
4759 ),
4760 KeyParameter::new(
4761 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4762 SecurityLevel::TRUSTED_ENVIRONMENT,
4763 ),
4764 KeyParameter::new(
4765 KeyParameterValue::Algorithm(Algorithm::RSA),
4766 SecurityLevel::TRUSTED_ENVIRONMENT,
4767 ),
4768 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4769 KeyParameter::new(
4770 KeyParameterValue::BlockMode(BlockMode::ECB),
4771 SecurityLevel::TRUSTED_ENVIRONMENT,
4772 ),
4773 KeyParameter::new(
4774 KeyParameterValue::BlockMode(BlockMode::GCM),
4775 SecurityLevel::TRUSTED_ENVIRONMENT,
4776 ),
4777 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4778 KeyParameter::new(
4779 KeyParameterValue::Digest(Digest::MD5),
4780 SecurityLevel::TRUSTED_ENVIRONMENT,
4781 ),
4782 KeyParameter::new(
4783 KeyParameterValue::Digest(Digest::SHA_2_224),
4784 SecurityLevel::TRUSTED_ENVIRONMENT,
4785 ),
4786 KeyParameter::new(
4787 KeyParameterValue::Digest(Digest::SHA_2_256),
4788 SecurityLevel::STRONGBOX,
4789 ),
4790 KeyParameter::new(
4791 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4792 SecurityLevel::TRUSTED_ENVIRONMENT,
4793 ),
4794 KeyParameter::new(
4795 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4796 SecurityLevel::TRUSTED_ENVIRONMENT,
4797 ),
4798 KeyParameter::new(
4799 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4800 SecurityLevel::STRONGBOX,
4801 ),
4802 KeyParameter::new(
4803 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4804 SecurityLevel::TRUSTED_ENVIRONMENT,
4805 ),
4806 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4807 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4808 KeyParameter::new(
4809 KeyParameterValue::EcCurve(EcCurve::P_224),
4810 SecurityLevel::TRUSTED_ENVIRONMENT,
4811 ),
4812 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4813 KeyParameter::new(
4814 KeyParameterValue::EcCurve(EcCurve::P_384),
4815 SecurityLevel::TRUSTED_ENVIRONMENT,
4816 ),
4817 KeyParameter::new(
4818 KeyParameterValue::EcCurve(EcCurve::P_521),
4819 SecurityLevel::TRUSTED_ENVIRONMENT,
4820 ),
4821 KeyParameter::new(
4822 KeyParameterValue::RSAPublicExponent(3),
4823 SecurityLevel::TRUSTED_ENVIRONMENT,
4824 ),
4825 KeyParameter::new(
4826 KeyParameterValue::IncludeUniqueID,
4827 SecurityLevel::TRUSTED_ENVIRONMENT,
4828 ),
4829 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4830 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4831 KeyParameter::new(
4832 KeyParameterValue::ActiveDateTime(1234567890),
4833 SecurityLevel::STRONGBOX,
4834 ),
4835 KeyParameter::new(
4836 KeyParameterValue::OriginationExpireDateTime(1234567890),
4837 SecurityLevel::TRUSTED_ENVIRONMENT,
4838 ),
4839 KeyParameter::new(
4840 KeyParameterValue::UsageExpireDateTime(1234567890),
4841 SecurityLevel::TRUSTED_ENVIRONMENT,
4842 ),
4843 KeyParameter::new(
4844 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4845 SecurityLevel::TRUSTED_ENVIRONMENT,
4846 ),
4847 KeyParameter::new(
4848 KeyParameterValue::MaxUsesPerBoot(1234567890),
4849 SecurityLevel::TRUSTED_ENVIRONMENT,
4850 ),
4851 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4852 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4853 KeyParameter::new(
4854 KeyParameterValue::NoAuthRequired,
4855 SecurityLevel::TRUSTED_ENVIRONMENT,
4856 ),
4857 KeyParameter::new(
4858 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4859 SecurityLevel::TRUSTED_ENVIRONMENT,
4860 ),
4861 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4862 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4863 KeyParameter::new(
4864 KeyParameterValue::TrustedUserPresenceRequired,
4865 SecurityLevel::TRUSTED_ENVIRONMENT,
4866 ),
4867 KeyParameter::new(
4868 KeyParameterValue::TrustedConfirmationRequired,
4869 SecurityLevel::TRUSTED_ENVIRONMENT,
4870 ),
4871 KeyParameter::new(
4872 KeyParameterValue::UnlockedDeviceRequired,
4873 SecurityLevel::TRUSTED_ENVIRONMENT,
4874 ),
4875 KeyParameter::new(
4876 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4877 SecurityLevel::SOFTWARE,
4878 ),
4879 KeyParameter::new(
4880 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4881 SecurityLevel::SOFTWARE,
4882 ),
4883 KeyParameter::new(
4884 KeyParameterValue::CreationDateTime(12345677890),
4885 SecurityLevel::SOFTWARE,
4886 ),
4887 KeyParameter::new(
4888 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4889 SecurityLevel::TRUSTED_ENVIRONMENT,
4890 ),
4891 KeyParameter::new(
4892 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4893 SecurityLevel::TRUSTED_ENVIRONMENT,
4894 ),
4895 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4896 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4897 KeyParameter::new(
4898 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4899 SecurityLevel::SOFTWARE,
4900 ),
4901 KeyParameter::new(
4902 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4903 SecurityLevel::TRUSTED_ENVIRONMENT,
4904 ),
4905 KeyParameter::new(
4906 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4907 SecurityLevel::TRUSTED_ENVIRONMENT,
4908 ),
4909 KeyParameter::new(
4910 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4911 SecurityLevel::TRUSTED_ENVIRONMENT,
4912 ),
4913 KeyParameter::new(
4914 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4915 SecurityLevel::TRUSTED_ENVIRONMENT,
4916 ),
4917 KeyParameter::new(
4918 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4919 SecurityLevel::TRUSTED_ENVIRONMENT,
4920 ),
4921 KeyParameter::new(
4922 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4923 SecurityLevel::TRUSTED_ENVIRONMENT,
4924 ),
4925 KeyParameter::new(
4926 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4927 SecurityLevel::TRUSTED_ENVIRONMENT,
4928 ),
4929 KeyParameter::new(
4930 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4931 SecurityLevel::TRUSTED_ENVIRONMENT,
4932 ),
4933 KeyParameter::new(
4934 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4935 SecurityLevel::TRUSTED_ENVIRONMENT,
4936 ),
4937 KeyParameter::new(
4938 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4939 SecurityLevel::TRUSTED_ENVIRONMENT,
4940 ),
4941 KeyParameter::new(
4942 KeyParameterValue::VendorPatchLevel(3),
4943 SecurityLevel::TRUSTED_ENVIRONMENT,
4944 ),
4945 KeyParameter::new(
4946 KeyParameterValue::BootPatchLevel(4),
4947 SecurityLevel::TRUSTED_ENVIRONMENT,
4948 ),
4949 KeyParameter::new(
4950 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4951 SecurityLevel::TRUSTED_ENVIRONMENT,
4952 ),
4953 KeyParameter::new(
4954 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4955 SecurityLevel::TRUSTED_ENVIRONMENT,
4956 ),
4957 KeyParameter::new(
4958 KeyParameterValue::MacLength(256),
4959 SecurityLevel::TRUSTED_ENVIRONMENT,
4960 ),
4961 KeyParameter::new(
4962 KeyParameterValue::ResetSinceIdRotation,
4963 SecurityLevel::TRUSTED_ENVIRONMENT,
4964 ),
4965 KeyParameter::new(
4966 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4967 SecurityLevel::TRUSTED_ENVIRONMENT,
4968 ),
Qi Wub9433b52020-12-01 14:52:46 +08004969 ];
4970 if let Some(value) = max_usage_count {
4971 params.push(KeyParameter::new(
4972 KeyParameterValue::UsageCountLimit(value),
4973 SecurityLevel::SOFTWARE,
4974 ));
4975 }
4976 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004977 }
4978
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004979 fn make_test_key_entry(
4980 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004981 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004982 namespace: i64,
4983 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004984 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004985 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004986 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004987 let mut blob_metadata = BlobMetaData::new();
4988 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4989 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4990 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4991 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4992 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4993
4994 db.set_blob(
4995 &key_id,
4996 SubComponentType::KEY_BLOB,
4997 Some(TEST_KEY_BLOB),
4998 Some(&blob_metadata),
4999 )?;
5000 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5001 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005002
5003 let params = make_test_params(max_usage_count);
5004 db.insert_keyparameter(&key_id, &params)?;
5005
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005006 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005007 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005008 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005009 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005010 Ok(key_id)
5011 }
5012
Qi Wub9433b52020-12-01 14:52:46 +08005013 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5014 let params = make_test_params(max_usage_count);
5015
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005016 let mut blob_metadata = BlobMetaData::new();
5017 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5018 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5019 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5020 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5021 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5022
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005023 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005024 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005025
5026 KeyEntry {
5027 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005028 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005029 cert: Some(TEST_CERT_BLOB.to_vec()),
5030 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005031 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005032 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005033 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005034 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005035 }
5036 }
5037
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005038 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005039 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005040 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005041 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005042 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005043 NO_PARAMS,
5044 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005045 Ok((
5046 row.get(0)?,
5047 row.get(1)?,
5048 row.get(2)?,
5049 row.get(3)?,
5050 row.get(4)?,
5051 row.get(5)?,
5052 row.get(6)?,
5053 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005054 },
5055 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005056
5057 println!("Key entry table rows:");
5058 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005059 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005060 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005061 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5062 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005063 );
5064 }
5065 Ok(())
5066 }
5067
5068 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005069 let mut stmt = db
5070 .conn
5071 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005072 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5073 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5074 })?;
5075
5076 println!("Grant table rows:");
5077 for r in rows {
5078 let (id, gt, ki, av) = r.unwrap();
5079 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5080 }
5081 Ok(())
5082 }
5083
Joel Galenson0891bc12020-07-20 10:37:03 -07005084 // Use a custom random number generator that repeats each number once.
5085 // This allows us to test repeated elements.
5086
5087 thread_local! {
5088 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5089 }
5090
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005091 fn reset_random() {
5092 RANDOM_COUNTER.with(|counter| {
5093 *counter.borrow_mut() = 0;
5094 })
5095 }
5096
Joel Galenson0891bc12020-07-20 10:37:03 -07005097 pub fn random() -> i64 {
5098 RANDOM_COUNTER.with(|counter| {
5099 let result = *counter.borrow() / 2;
5100 *counter.borrow_mut() += 1;
5101 result
5102 })
5103 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005104
5105 #[test]
5106 fn test_last_off_body() -> Result<()> {
5107 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005108 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005109 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5110 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5111 tx.commit()?;
5112 let one_second = Duration::from_secs(1);
5113 thread::sleep(one_second);
5114 db.update_last_off_body(MonotonicRawTime::now())?;
5115 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5116 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5117 tx2.commit()?;
5118 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5119 Ok(())
5120 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005121
5122 #[test]
5123 fn test_unbind_keys_for_user() -> Result<()> {
5124 let mut db = new_test_db()?;
5125 db.unbind_keys_for_user(1, false)?;
5126
5127 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5128 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5129 db.unbind_keys_for_user(2, false)?;
5130
5131 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5132 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5133
5134 db.unbind_keys_for_user(1, true)?;
5135 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5136
5137 Ok(())
5138 }
5139
5140 #[test]
5141 fn test_store_super_key() -> Result<()> {
5142 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005143 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005144 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005145 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005146 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005147 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005148
5149 let (encrypted_super_key, metadata) =
5150 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005151 db.store_super_key(
5152 1,
5153 &USER_SUPER_KEY,
5154 &encrypted_super_key,
5155 &metadata,
5156 &KeyMetaData::new(),
5157 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005158
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005159 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005160 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005161
Paul Crowley7a658392021-03-18 17:08:20 -07005162 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005163 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5164 USER_SUPER_KEY.algorithm,
5165 key_entry,
5166 &pw,
5167 None,
5168 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005169
Paul Crowley7a658392021-03-18 17:08:20 -07005170 let decrypted_secret_bytes =
5171 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5172 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005173 Ok(())
5174 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005175}