blob: 830926d81f2bb1780f18874a8f9b3b14fd7e4fb5 [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;
Janis Danisevskis850d4862021-05-05 08:41:14 -070049use crate::utils::{get_current_time_in_seconds, watchdog as wd, 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};
Seth Moore78c091f2021-04-09 21:38:30 +000075use statslog_rust::keystore2_storage_stats::{
76 Keystore2StorageStats, StorageType as StatsdStorageType,
77};
Max Bires2b2e6562020-09-22 11:22:36 -070078
79use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080080use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000081use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070082#[cfg(not(test))]
83use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070084use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080085 params,
86 types::FromSql,
87 types::FromSqlResult,
88 types::ToSqlOutput,
89 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080090 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070091};
Max Bires2b2e6562020-09-22 11:22:36 -070092
Janis Danisevskisaec14592020-11-12 09:41:49 -080093use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080095 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070096 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080097 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080098};
Max Bires2b2e6562020-09-22 11:22:36 -070099
Joel Galenson0891bc12020-07-20 10:37:03 -0700100#[cfg(test)]
101use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -0700102
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800103impl_metadata!(
104 /// A set of metadata for key entries.
105 #[derive(Debug, Default, Eq, PartialEq)]
106 pub struct KeyMetaData;
107 /// A metadata entry for key entries.
108 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
109 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800110 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800111 CreationDate(DateTime) with accessor creation_date,
112 /// Expiration date for attestation keys.
113 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700114 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
115 /// provisioning
116 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
117 /// Vector representing the raw public key so results from the server can be matched
118 /// to the right entry
119 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700120 /// SEC1 public key for ECDH encryption
121 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800122 // --- ADD NEW META DATA FIELDS HERE ---
123 // For backwards compatibility add new entries only to
124 // end of this list and above this comment.
125 };
126);
127
128impl KeyMetaData {
129 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
130 let mut stmt = tx
131 .prepare(
132 "SELECT tag, data from persistent.keymetadata
133 WHERE keyentryid = ?;",
134 )
135 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
136
137 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
138
139 let mut rows =
140 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
141 db_utils::with_rows_extract_all(&mut rows, |row| {
142 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
143 metadata.insert(
144 db_tag,
145 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
146 .context("Failed to read KeyMetaEntry.")?,
147 );
148 Ok(())
149 })
150 .context("In KeyMetaData::load_from_db.")?;
151
152 Ok(Self { data: metadata })
153 }
154
155 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
156 let mut stmt = tx
157 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000158 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800159 VALUES (?, ?, ?);",
160 )
161 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
162
163 let iter = self.data.iter();
164 for (tag, entry) in iter {
165 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
166 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
167 })?;
168 }
169 Ok(())
170 }
171}
172
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800173impl_metadata!(
174 /// A set of metadata for key blobs.
175 #[derive(Debug, Default, Eq, PartialEq)]
176 pub struct BlobMetaData;
177 /// A metadata entry for key blobs.
178 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
179 pub enum BlobMetaEntry {
180 /// If present, indicates that the blob is encrypted with another key or a key derived
181 /// from a password.
182 EncryptedBy(EncryptedBy) with accessor encrypted_by,
183 /// If the blob is password encrypted this field is set to the
184 /// salt used for the key derivation.
185 Salt(Vec<u8>) with accessor salt,
186 /// If the blob is encrypted, this field is set to the initialization vector.
187 Iv(Vec<u8>) with accessor iv,
188 /// If the blob is encrypted, this field holds the AEAD TAG.
189 AeadTag(Vec<u8>) with accessor aead_tag,
190 /// The uuid of the owning KeyMint instance.
191 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700192 /// If the key is ECDH encrypted, this is the ephemeral public key
193 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000194 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
195 /// of that key
196 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800197 // --- ADD NEW META DATA FIELDS HERE ---
198 // For backwards compatibility add new entries only to
199 // end of this list and above this comment.
200 };
201);
202
203impl BlobMetaData {
204 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
205 let mut stmt = tx
206 .prepare(
207 "SELECT tag, data from persistent.blobmetadata
208 WHERE blobentryid = ?;",
209 )
210 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
211
212 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
213
214 let mut rows =
215 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
216 db_utils::with_rows_extract_all(&mut rows, |row| {
217 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
218 metadata.insert(
219 db_tag,
220 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
221 .context("Failed to read BlobMetaEntry.")?,
222 );
223 Ok(())
224 })
225 .context("In BlobMetaData::load_from_db.")?;
226
227 Ok(Self { data: metadata })
228 }
229
230 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
231 let mut stmt = tx
232 .prepare(
233 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
234 VALUES (?, ?, ?);",
235 )
236 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
237
238 let iter = self.data.iter();
239 for (tag, entry) in iter {
240 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
241 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
242 })?;
243 }
244 Ok(())
245 }
246}
247
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800248/// Indicates the type of the keyentry.
249#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
250pub enum KeyType {
251 /// This is a client key type. These keys are created or imported through the Keystore 2.0
252 /// AIDL interface android.system.keystore2.
253 Client,
254 /// This is a super key type. These keys are created by keystore itself and used to encrypt
255 /// other key blobs to provide LSKF binding.
256 Super,
257 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
258 Attestation,
259}
260
261impl ToSql for KeyType {
262 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
263 Ok(ToSqlOutput::Owned(Value::Integer(match self {
264 KeyType::Client => 0,
265 KeyType::Super => 1,
266 KeyType::Attestation => 2,
267 })))
268 }
269}
270
271impl FromSql for KeyType {
272 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
273 match i64::column_result(value)? {
274 0 => Ok(KeyType::Client),
275 1 => Ok(KeyType::Super),
276 2 => Ok(KeyType::Attestation),
277 v => Err(FromSqlError::OutOfRange(v)),
278 }
279 }
280}
281
Max Bires8e93d2b2021-01-14 13:17:59 -0800282/// Uuid representation that can be stored in the database.
283/// Right now it can only be initialized from SecurityLevel.
284/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
285#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
286pub struct Uuid([u8; 16]);
287
288impl Deref for Uuid {
289 type Target = [u8; 16];
290
291 fn deref(&self) -> &Self::Target {
292 &self.0
293 }
294}
295
296impl From<SecurityLevel> for Uuid {
297 fn from(sec_level: SecurityLevel) -> Self {
298 Self((sec_level.0 as u128).to_be_bytes())
299 }
300}
301
302impl ToSql for Uuid {
303 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
304 self.0.to_sql()
305 }
306}
307
308impl FromSql for Uuid {
309 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
310 let blob = Vec::<u8>::column_result(value)?;
311 if blob.len() != 16 {
312 return Err(FromSqlError::OutOfRange(blob.len() as i64));
313 }
314 let mut arr = [0u8; 16];
315 arr.copy_from_slice(&blob);
316 Ok(Self(arr))
317 }
318}
319
320/// Key entries that are not associated with any KeyMint instance, such as pure certificate
321/// entries are associated with this UUID.
322pub static KEYSTORE_UUID: Uuid = Uuid([
323 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
324]);
325
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800326/// Indicates how the sensitive part of this key blob is encrypted.
327#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
328pub enum EncryptedBy {
329 /// The keyblob is encrypted by a user password.
330 /// In the database this variant is represented as NULL.
331 Password,
332 /// The keyblob is encrypted by another key with wrapped key id.
333 /// In the database this variant is represented as non NULL value
334 /// that is convertible to i64, typically NUMERIC.
335 KeyId(i64),
336}
337
338impl ToSql for EncryptedBy {
339 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
340 match self {
341 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
342 Self::KeyId(id) => id.to_sql(),
343 }
344 }
345}
346
347impl FromSql for EncryptedBy {
348 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
349 match value {
350 ValueRef::Null => Ok(Self::Password),
351 _ => Ok(Self::KeyId(i64::column_result(value)?)),
352 }
353 }
354}
355
356/// A database representation of wall clock time. DateTime stores unix epoch time as
357/// i64 in milliseconds.
358#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
359pub struct DateTime(i64);
360
361/// Error type returned when creating DateTime or converting it from and to
362/// SystemTime.
363#[derive(thiserror::Error, Debug)]
364pub enum DateTimeError {
365 /// This is returned when SystemTime and Duration computations fail.
366 #[error(transparent)]
367 SystemTimeError(#[from] SystemTimeError),
368
369 /// This is returned when type conversions fail.
370 #[error(transparent)]
371 TypeConversion(#[from] std::num::TryFromIntError),
372
373 /// This is returned when checked time arithmetic failed.
374 #[error("Time arithmetic failed.")]
375 TimeArithmetic,
376}
377
378impl DateTime {
379 /// Constructs a new DateTime object denoting the current time. This may fail during
380 /// conversion to unix epoch time and during conversion to the internal i64 representation.
381 pub fn now() -> Result<Self, DateTimeError> {
382 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
383 }
384
385 /// Constructs a new DateTime object from milliseconds.
386 pub fn from_millis_epoch(millis: i64) -> Self {
387 Self(millis)
388 }
389
390 /// Returns unix epoch time in milliseconds.
391 pub fn to_millis_epoch(&self) -> i64 {
392 self.0
393 }
394
395 /// Returns unix epoch time in seconds.
396 pub fn to_secs_epoch(&self) -> i64 {
397 self.0 / 1000
398 }
399}
400
401impl ToSql for DateTime {
402 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
403 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
404 }
405}
406
407impl FromSql for DateTime {
408 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
409 Ok(Self(i64::column_result(value)?))
410 }
411}
412
413impl TryInto<SystemTime> for DateTime {
414 type Error = DateTimeError;
415
416 fn try_into(self) -> Result<SystemTime, Self::Error> {
417 // We want to construct a SystemTime representation equivalent to self, denoting
418 // a point in time THEN, but we cannot set the time directly. We can only construct
419 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
420 // and between EPOCH and THEN. With this common reference we can construct the
421 // duration between NOW and THEN which we can add to our SystemTime representation
422 // of NOW to get a SystemTime representation of THEN.
423 // Durations can only be positive, thus the if statement below.
424 let now = SystemTime::now();
425 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
426 let then_epoch = Duration::from_millis(self.0.try_into()?);
427 Ok(if now_epoch > then_epoch {
428 // then = now - (now_epoch - then_epoch)
429 now_epoch
430 .checked_sub(then_epoch)
431 .and_then(|d| now.checked_sub(d))
432 .ok_or(DateTimeError::TimeArithmetic)?
433 } else {
434 // then = now + (then_epoch - now_epoch)
435 then_epoch
436 .checked_sub(now_epoch)
437 .and_then(|d| now.checked_add(d))
438 .ok_or(DateTimeError::TimeArithmetic)?
439 })
440 }
441}
442
443impl TryFrom<SystemTime> for DateTime {
444 type Error = DateTimeError;
445
446 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
447 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
448 }
449}
450
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800451#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
452enum KeyLifeCycle {
453 /// Existing keys have a key ID but are not fully populated yet.
454 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
455 /// them to Unreferenced for garbage collection.
456 Existing,
457 /// A live key is fully populated and usable by clients.
458 Live,
459 /// An unreferenced key is scheduled for garbage collection.
460 Unreferenced,
461}
462
463impl ToSql for KeyLifeCycle {
464 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
465 match self {
466 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
467 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
468 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
469 }
470 }
471}
472
473impl FromSql for KeyLifeCycle {
474 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
475 match i64::column_result(value)? {
476 0 => Ok(KeyLifeCycle::Existing),
477 1 => Ok(KeyLifeCycle::Live),
478 2 => Ok(KeyLifeCycle::Unreferenced),
479 v => Err(FromSqlError::OutOfRange(v)),
480 }
481 }
482}
483
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700484/// Keys have a KeyMint blob component and optional public certificate and
485/// certificate chain components.
486/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
487/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800488#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700489pub struct KeyEntryLoadBits(u32);
490
491impl KeyEntryLoadBits {
492 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
493 pub const NONE: KeyEntryLoadBits = Self(0);
494 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
495 pub const KM: KeyEntryLoadBits = Self(1);
496 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
497 pub const PUBLIC: KeyEntryLoadBits = Self(2);
498 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
499 pub const BOTH: KeyEntryLoadBits = Self(3);
500
501 /// Returns true if this object indicates that the public components shall be loaded.
502 pub const fn load_public(&self) -> bool {
503 self.0 & Self::PUBLIC.0 != 0
504 }
505
506 /// Returns true if the object indicates that the KeyMint component shall be loaded.
507 pub const fn load_km(&self) -> bool {
508 self.0 & Self::KM.0 != 0
509 }
510}
511
Janis Danisevskisaec14592020-11-12 09:41:49 -0800512lazy_static! {
513 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
514}
515
516struct KeyIdLockDb {
517 locked_keys: Mutex<HashSet<i64>>,
518 cond_var: Condvar,
519}
520
521/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
522/// from the database a second time. Most functions manipulating the key blob database
523/// require a KeyIdGuard.
524#[derive(Debug)]
525pub struct KeyIdGuard(i64);
526
527impl KeyIdLockDb {
528 fn new() -> Self {
529 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
530 }
531
532 /// This function blocks until an exclusive lock for the given key entry id can
533 /// be acquired. It returns a guard object, that represents the lifecycle of the
534 /// acquired lock.
535 pub fn get(&self, key_id: i64) -> KeyIdGuard {
536 let mut locked_keys = self.locked_keys.lock().unwrap();
537 while locked_keys.contains(&key_id) {
538 locked_keys = self.cond_var.wait(locked_keys).unwrap();
539 }
540 locked_keys.insert(key_id);
541 KeyIdGuard(key_id)
542 }
543
544 /// This function attempts to acquire an exclusive lock on a given key id. If the
545 /// given key id is already taken the function returns None immediately. If a lock
546 /// can be acquired this function returns a guard object, that represents the
547 /// lifecycle of the acquired lock.
548 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
549 let mut locked_keys = self.locked_keys.lock().unwrap();
550 if locked_keys.insert(key_id) {
551 Some(KeyIdGuard(key_id))
552 } else {
553 None
554 }
555 }
556}
557
558impl KeyIdGuard {
559 /// Get the numeric key id of the locked key.
560 pub fn id(&self) -> i64 {
561 self.0
562 }
563}
564
565impl Drop for KeyIdGuard {
566 fn drop(&mut self) {
567 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
568 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800569 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800570 KEY_ID_LOCK.cond_var.notify_all();
571 }
572}
573
Max Bires8e93d2b2021-01-14 13:17:59 -0800574/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700575#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800576pub struct CertificateInfo {
577 cert: Option<Vec<u8>>,
578 cert_chain: Option<Vec<u8>>,
579}
580
581impl CertificateInfo {
582 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
583 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
584 Self { cert, cert_chain }
585 }
586
587 /// Take the cert
588 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
589 self.cert.take()
590 }
591
592 /// Take the cert chain
593 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
594 self.cert_chain.take()
595 }
596}
597
Max Bires2b2e6562020-09-22 11:22:36 -0700598/// This type represents a certificate chain with a private key corresponding to the leaf
599/// 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 -0700600pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800601 /// A KM key blob
602 pub private_key: ZVec,
603 /// A batch cert for private_key
604 pub batch_cert: Vec<u8>,
605 /// A full certificate chain from root signing authority to private_key, including batch_cert
606 /// for convenience.
607 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700608}
609
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700610/// This type represents a Keystore 2.0 key entry.
611/// An entry has a unique `id` by which it can be found in the database.
612/// It has a security level field, key parameters, and three optional fields
613/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800614#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615pub struct KeyEntry {
616 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800617 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700618 cert: Option<Vec<u8>>,
619 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800620 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700621 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800622 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800623 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700624}
625
626impl KeyEntry {
627 /// Returns the unique id of the Key entry.
628 pub fn id(&self) -> i64 {
629 self.id
630 }
631 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
633 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700634 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800635 /// Extracts the Optional KeyMint blob including its metadata.
636 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
637 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700638 }
639 /// Exposes the optional public certificate.
640 pub fn cert(&self) -> &Option<Vec<u8>> {
641 &self.cert
642 }
643 /// Extracts the optional public certificate.
644 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
645 self.cert.take()
646 }
647 /// Exposes the optional public certificate chain.
648 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
649 &self.cert_chain
650 }
651 /// Extracts the optional public certificate_chain.
652 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
653 self.cert_chain.take()
654 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800655 /// Returns the uuid of the owning KeyMint instance.
656 pub fn km_uuid(&self) -> &Uuid {
657 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700658 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700659 /// Exposes the key parameters of this key entry.
660 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
661 &self.parameters
662 }
663 /// Consumes this key entry and extracts the keyparameters from it.
664 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
665 self.parameters
666 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800667 /// Exposes the key metadata of this key entry.
668 pub fn metadata(&self) -> &KeyMetaData {
669 &self.metadata
670 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800671 /// This returns true if the entry is a pure certificate entry with no
672 /// private key component.
673 pub fn pure_cert(&self) -> bool {
674 self.pure_cert
675 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000676 /// Consumes this key entry and extracts the keyparameters and metadata from it.
677 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
678 (self.parameters, self.metadata)
679 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700680}
681
682/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800683#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700684pub struct SubComponentType(u32);
685impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800686 /// Persistent identifier for a key blob.
687 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700688 /// Persistent identifier for a certificate blob.
689 pub const CERT: SubComponentType = Self(1);
690 /// Persistent identifier for a certificate chain blob.
691 pub const CERT_CHAIN: SubComponentType = Self(2);
692}
693
694impl ToSql for SubComponentType {
695 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
696 self.0.to_sql()
697 }
698}
699
700impl FromSql for SubComponentType {
701 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
702 Ok(Self(u32::column_result(value)?))
703 }
704}
705
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800706/// This trait is private to the database module. It is used to convey whether or not the garbage
707/// collector shall be invoked after a database access. All closures passed to
708/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
709/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
710/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
711/// `.need_gc()`.
712trait DoGc<T> {
713 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
714
715 fn no_gc(self) -> Result<(bool, T)>;
716
717 fn need_gc(self) -> Result<(bool, T)>;
718}
719
720impl<T> DoGc<T> for Result<T> {
721 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
722 self.map(|r| (need_gc, r))
723 }
724
725 fn no_gc(self) -> Result<(bool, T)> {
726 self.do_gc(false)
727 }
728
729 fn need_gc(self) -> Result<(bool, T)> {
730 self.do_gc(true)
731 }
732}
733
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700734/// KeystoreDB wraps a connection to an SQLite database and tracks its
735/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700736pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700737 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700738 gc: Option<Arc<Gc>>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700739}
740
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000741/// Database representation of the monotonic time retrieved from the system call clock_gettime with
742/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
743#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
744pub struct MonotonicRawTime(i64);
745
746impl MonotonicRawTime {
747 /// Constructs a new MonotonicRawTime
748 pub fn now() -> Self {
749 Self(get_current_time_in_seconds())
750 }
751
David Drysdale0e45a612021-02-25 17:24:36 +0000752 /// Constructs a new MonotonicRawTime from a given number of seconds.
753 pub fn from_secs(val: i64) -> Self {
754 Self(val)
755 }
756
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000757 /// Returns the integer value of MonotonicRawTime as i64
758 pub fn seconds(&self) -> i64 {
759 self.0
760 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800761
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000762 /// Returns the value of MonotonicRawTime in milli seconds as i64
763 pub fn milli_seconds(&self) -> i64 {
764 self.0 * 1000
765 }
766
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800767 /// Like i64::checked_sub.
768 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
769 self.0.checked_sub(other.0).map(Self)
770 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000771}
772
773impl ToSql for MonotonicRawTime {
774 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
775 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
776 }
777}
778
779impl FromSql for MonotonicRawTime {
780 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
781 Ok(Self(i64::column_result(value)?))
782 }
783}
784
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000785/// This struct encapsulates the information to be stored in the database about the auth tokens
786/// received by keystore.
787pub struct AuthTokenEntry {
788 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000789 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000790}
791
792impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000793 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000794 AuthTokenEntry { auth_token, time_received }
795 }
796
797 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000799 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800800 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
801 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000802 })
803 }
804
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000805 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800806 pub fn auth_token(&self) -> &HardwareAuthToken {
807 &self.auth_token
808 }
809
810 /// Returns the auth token wrapped by the AuthTokenEntry
811 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000812 self.auth_token
813 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800814
815 /// Returns the time that this auth token was received.
816 pub fn time_received(&self) -> MonotonicRawTime {
817 self.time_received
818 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000819
820 /// Returns the challenge value of the auth token.
821 pub fn challenge(&self) -> i64 {
822 self.auth_token.challenge
823 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000824}
825
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800826/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
827/// This object does not allow access to the database connection. But it keeps a database
828/// connection alive in order to keep the in memory per boot database alive.
829pub struct PerBootDbKeepAlive(Connection);
830
Joel Galenson26f4d012020-07-17 14:57:21 -0700831impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800832 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800833 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
834
Seth Moore78c091f2021-04-09 21:38:30 +0000835 /// Name of the file that holds the cross-boot persistent database.
836 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
837
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800838 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
839 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
840 let conn = Connection::open_in_memory()
841 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
842
843 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
844 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
845 Ok(PerBootDbKeepAlive(conn))
846 }
847
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700848 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800849 /// files persistent.sqlite and perboot.sqlite in the given directory.
850 /// It also attempts to initialize all of the tables.
851 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700852 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700853 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700854 let _wp = wd::watch_millis("KeystoreDB::new", 500);
855
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800856 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800857 let mut persistent_path = db_root.to_path_buf();
Seth Moore78c091f2021-04-09 21:38:30 +0000858 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700859
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800860 // Now convert them to strings prefixed with "file:"
861 let mut persistent_path_str = "file:".to_owned();
862 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800863
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800864 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800865
Janis Danisevskis66784c42021-01-27 08:40:25 -0800866 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
867 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
868
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800869 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800871 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800872 })?;
873 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700874 }
875
Janis Danisevskis66784c42021-01-27 08:40:25 -0800876 fn init_tables(tx: &Transaction) -> Result<()> {
877 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700878 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700879 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800880 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700881 domain INTEGER,
882 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800883 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800884 state INTEGER,
885 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700886 NO_PARAMS,
887 )
888 .context("Failed to initialize \"keyentry\" table.")?;
889
Janis Danisevskis66784c42021-01-27 08:40:25 -0800890 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800891 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
892 ON keyentry(id);",
893 NO_PARAMS,
894 )
895 .context("Failed to create index keyentry_id_index.")?;
896
897 tx.execute(
898 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
899 ON keyentry(domain, namespace, alias);",
900 NO_PARAMS,
901 )
902 .context("Failed to create index keyentry_domain_namespace_index.")?;
903
904 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700905 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
906 id INTEGER PRIMARY KEY,
907 subcomponent_type INTEGER,
908 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800909 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700910 NO_PARAMS,
911 )
912 .context("Failed to initialize \"blobentry\" table.")?;
913
Janis Danisevskis66784c42021-01-27 08:40:25 -0800914 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800915 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
916 ON blobentry(keyentryid);",
917 NO_PARAMS,
918 )
919 .context("Failed to create index blobentry_keyentryid_index.")?;
920
921 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800922 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
923 id INTEGER PRIMARY KEY,
924 blobentryid INTEGER,
925 tag INTEGER,
926 data ANY,
927 UNIQUE (blobentryid, tag));",
928 NO_PARAMS,
929 )
930 .context("Failed to initialize \"blobmetadata\" table.")?;
931
932 tx.execute(
933 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
934 ON blobmetadata(blobentryid);",
935 NO_PARAMS,
936 )
937 .context("Failed to create index blobmetadata_blobentryid_index.")?;
938
939 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700940 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000941 keyentryid INTEGER,
942 tag INTEGER,
943 data ANY,
944 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700945 NO_PARAMS,
946 )
947 .context("Failed to initialize \"keyparameter\" table.")?;
948
Janis Danisevskis66784c42021-01-27 08:40:25 -0800949 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800950 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
951 ON keyparameter(keyentryid);",
952 NO_PARAMS,
953 )
954 .context("Failed to create index keyparameter_keyentryid_index.")?;
955
956 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800957 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
958 keyentryid INTEGER,
959 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000960 data ANY,
961 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800962 NO_PARAMS,
963 )
964 .context("Failed to initialize \"keymetadata\" table.")?;
965
Janis Danisevskis66784c42021-01-27 08:40:25 -0800966 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800967 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
968 ON keymetadata(keyentryid);",
969 NO_PARAMS,
970 )
971 .context("Failed to create index keymetadata_keyentryid_index.")?;
972
973 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800974 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700975 id INTEGER UNIQUE,
976 grantee INTEGER,
977 keyentryid INTEGER,
978 access_vector INTEGER);",
979 NO_PARAMS,
980 )
981 .context("Failed to initialize \"grant\" table.")?;
982
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000983 //TODO: only drop the following two perboot tables if this is the first start up
984 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800985 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000986 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800987 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000988 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
989 id INTEGER PRIMARY KEY,
990 challenge INTEGER,
991 user_id INTEGER,
992 auth_id INTEGER,
993 authenticator_type INTEGER,
994 timestamp INTEGER,
995 mac BLOB,
996 time_received INTEGER,
997 UNIQUE(user_id, auth_id, authenticator_type));",
998 NO_PARAMS,
999 )
1000 .context("Failed to initialize \"authtoken\" table.")?;
1001
Janis Danisevskis66784c42021-01-27 08:40:25 -08001002 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001003 // .context("Failed to drop perboot.metadata table")?;
1004 // metadata table stores certain miscellaneous information required for keystore functioning
1005 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001006 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00001007 "CREATE TABLE IF NOT EXISTS perboot.metadata (
1008 key TEXT,
1009 value BLOB,
1010 UNIQUE(key));",
1011 NO_PARAMS,
1012 )
1013 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -07001014 Ok(())
1015 }
1016
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001017 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
1018 let conn =
1019 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1020
Janis Danisevskis66784c42021-01-27 08:40:25 -08001021 loop {
1022 if let Err(e) = conn
1023 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1024 .context("Failed to attach database persistent.")
1025 {
1026 if Self::is_locked_error(&e) {
1027 std::thread::sleep(std::time::Duration::from_micros(500));
1028 continue;
1029 } else {
1030 return Err(e);
1031 }
1032 }
1033 break;
1034 }
1035 loop {
1036 if let Err(e) = conn
1037 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1038 .context("Failed to attach database perboot.")
1039 {
1040 if Self::is_locked_error(&e) {
1041 std::thread::sleep(std::time::Duration::from_micros(500));
1042 continue;
1043 } else {
1044 return Err(e);
1045 }
1046 }
1047 break;
1048 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001049
1050 Ok(conn)
1051 }
1052
Seth Moore78c091f2021-04-09 21:38:30 +00001053 fn do_table_size_query(
1054 &mut self,
1055 storage_type: StatsdStorageType,
1056 query: &str,
1057 params: &[&str],
1058 ) -> Result<Keystore2StorageStats> {
1059 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
1060 tx.query_row(query, params, |row| Ok((row.get(0)?, row.get(1)?)))
1061 .with_context(|| {
1062 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1063 })
1064 .no_gc()
1065 })?;
1066 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1067 }
1068
1069 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1070 self.do_table_size_query(
1071 StatsdStorageType::Database,
1072 "SELECT page_count * page_size, freelist_count * page_size
1073 FROM pragma_page_count('persistent'),
1074 pragma_page_size('persistent'),
1075 persistent.pragma_freelist_count();",
1076 &[],
1077 )
1078 }
1079
1080 fn get_table_size(
1081 &mut self,
1082 storage_type: StatsdStorageType,
1083 schema: &str,
1084 table: &str,
1085 ) -> Result<Keystore2StorageStats> {
1086 self.do_table_size_query(
1087 storage_type,
1088 "SELECT pgsize,unused FROM dbstat(?1)
1089 WHERE name=?2 AND aggregate=TRUE;",
1090 &[schema, table],
1091 )
1092 }
1093
1094 /// Fetches a storage statisitics atom for a given storage type. For storage
1095 /// types that map to a table, information about the table's storage is
1096 /// returned. Requests for storage types that are not DB tables return None.
1097 pub fn get_storage_stat(
1098 &mut self,
1099 storage_type: StatsdStorageType,
1100 ) -> Result<Keystore2StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001101 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1102
Seth Moore78c091f2021-04-09 21:38:30 +00001103 match storage_type {
1104 StatsdStorageType::Database => self.get_total_size(),
1105 StatsdStorageType::KeyEntry => {
1106 self.get_table_size(storage_type, "persistent", "keyentry")
1107 }
1108 StatsdStorageType::KeyEntryIdIndex => {
1109 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1110 }
1111 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1112 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1113 }
1114 StatsdStorageType::BlobEntry => {
1115 self.get_table_size(storage_type, "persistent", "blobentry")
1116 }
1117 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1118 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1119 }
1120 StatsdStorageType::KeyParameter => {
1121 self.get_table_size(storage_type, "persistent", "keyparameter")
1122 }
1123 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1124 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1125 }
1126 StatsdStorageType::KeyMetadata => {
1127 self.get_table_size(storage_type, "persistent", "keymetadata")
1128 }
1129 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1130 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1131 }
1132 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1133 StatsdStorageType::AuthToken => {
1134 self.get_table_size(storage_type, "perboot", "authtoken")
1135 }
1136 StatsdStorageType::BlobMetadata => {
1137 self.get_table_size(storage_type, "persistent", "blobmetadata")
1138 }
1139 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1140 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1141 }
1142 _ => Err(anyhow::Error::msg(format!(
1143 "Unsupported storage type: {}",
1144 storage_type as i32
1145 ))),
1146 }
1147 }
1148
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001149 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001150 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1151 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001152 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1153 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001155 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001156 blob_ids_to_delete: &[i64],
1157 max_blobs: usize,
1158 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001159 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001160 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001161 // Delete the given blobs.
1162 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001163 tx.execute(
1164 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001166 )
1167 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001168 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1169 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001170 }
Janis Danisevskis3395f862021-05-06 10:54:17 -07001171 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1172 let result: Vec<(i64, Vec<u8>)> = {
1173 let mut stmt = tx
1174 .prepare(
1175 "SELECT id, blob FROM persistent.blobentry
1176 WHERE subcomponent_type = ?
1177 AND (
1178 id NOT IN (
1179 SELECT MAX(id) FROM persistent.blobentry
1180 WHERE subcomponent_type = ?
1181 GROUP BY keyentryid, subcomponent_type
1182 )
1183 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1184 ) LIMIT ?;",
1185 )
1186 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001187
Janis Danisevskis3395f862021-05-06 10:54:17 -07001188 let rows = stmt
1189 .query_map(
1190 params![
1191 SubComponentType::KEY_BLOB,
1192 SubComponentType::KEY_BLOB,
1193 max_blobs as i64,
1194 ],
1195 |row| Ok((row.get(0)?, row.get(1)?)),
1196 )
1197 .context("Trying to query superseded blob.")?;
1198
1199 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1200 .context("Trying to extract superseded blobs.")?
1201 };
1202
1203 let result = result
1204 .into_iter()
1205 .map(|(blob_id, blob)| {
1206 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1207 })
1208 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1209 .context("Trying to load blob metadata.")?;
1210 if !result.is_empty() {
1211 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001212 }
1213
1214 // We did not find any superseded key blob, so let's remove other superseded blob in
1215 // one transaction.
1216 tx.execute(
1217 "DELETE FROM persistent.blobentry
1218 WHERE NOT subcomponent_type = ?
1219 AND (
1220 id NOT IN (
1221 SELECT MAX(id) FROM persistent.blobentry
1222 WHERE NOT subcomponent_type = ?
1223 GROUP BY keyentryid, subcomponent_type
1224 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1225 );",
1226 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1227 )
1228 .context("Trying to purge superseded blobs.")?;
1229
Janis Danisevskis3395f862021-05-06 10:54:17 -07001230 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001231 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001232 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001233 }
1234
1235 /// This maintenance function should be called only once before the database is used for the
1236 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1237 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1238 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1239 /// Keystore crashed at some point during key generation. Callers may want to log such
1240 /// occurrences.
1241 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1242 /// it to `KeyLifeCycle::Live` may have grants.
1243 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001244 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1245
Janis Danisevskis66784c42021-01-27 08:40:25 -08001246 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1247 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001248 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1249 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1250 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001251 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001252 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001253 })
1254 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001255 }
1256
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001257 /// Checks if a key exists with given key type and key descriptor properties.
1258 pub fn key_exists(
1259 &mut self,
1260 domain: Domain,
1261 nspace: i64,
1262 alias: &str,
1263 key_type: KeyType,
1264 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001265 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1266
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001267 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1268 let key_descriptor =
1269 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1270 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1271 match result {
1272 Ok(_) => Ok(true),
1273 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1274 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1275 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1276 },
1277 }
1278 .no_gc()
1279 })
1280 .context("In key_exists.")
1281 }
1282
Hasini Gunasingheda895552021-01-27 19:34:37 +00001283 /// Stores a super key in the database.
1284 pub fn store_super_key(
1285 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001286 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001287 key_type: &SuperKeyType,
1288 blob: &[u8],
1289 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001290 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001291 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001292 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1293
Hasini Gunasingheda895552021-01-27 19:34:37 +00001294 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1295 let key_id = Self::insert_with_retry(|id| {
1296 tx.execute(
1297 "INSERT into persistent.keyentry
1298 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001299 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001300 params![
1301 id,
1302 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001303 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001304 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001305 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001306 KeyLifeCycle::Live,
1307 &KEYSTORE_UUID,
1308 ],
1309 )
1310 })
1311 .context("Failed to insert into keyentry table.")?;
1312
Paul Crowley8d5b2532021-03-19 10:53:07 -07001313 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1314
Hasini Gunasingheda895552021-01-27 19:34:37 +00001315 Self::set_blob_internal(
1316 &tx,
1317 key_id,
1318 SubComponentType::KEY_BLOB,
1319 Some(blob),
1320 Some(blob_metadata),
1321 )
1322 .context("Failed to store key blob.")?;
1323
1324 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1325 .context("Trying to load key components.")
1326 .no_gc()
1327 })
1328 .context("In store_super_key.")
1329 }
1330
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001331 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001332 pub fn load_super_key(
1333 &mut self,
1334 key_type: &SuperKeyType,
1335 user_id: u32,
1336 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001337 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1338
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001339 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1340 let key_descriptor = KeyDescriptor {
1341 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001342 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001343 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001344 blob: None,
1345 };
1346 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1347 match id {
1348 Ok(id) => {
1349 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1350 .context("In load_super_key. Failed to load key entry.")?;
1351 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1352 }
1353 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1354 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1355 _ => Err(error).context("In load_super_key."),
1356 },
1357 }
1358 .no_gc()
1359 })
1360 .context("In load_super_key.")
1361 }
1362
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001363 /// Atomically loads a key entry and associated metadata or creates it using the
1364 /// callback create_new_key callback. The callback is called during a database
1365 /// transaction. This means that implementers should be mindful about using
1366 /// blocking operations such as IPC or grabbing mutexes.
1367 pub fn get_or_create_key_with<F>(
1368 &mut self,
1369 domain: Domain,
1370 namespace: i64,
1371 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001372 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001373 create_new_key: F,
1374 ) -> Result<(KeyIdGuard, KeyEntry)>
1375 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001376 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001377 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001378 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1379
Janis Danisevskis66784c42021-01-27 08:40:25 -08001380 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1381 let id = {
1382 let mut stmt = tx
1383 .prepare(
1384 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001385 WHERE
1386 key_type = ?
1387 AND domain = ?
1388 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001389 AND alias = ?
1390 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001391 )
1392 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1393 let mut rows = stmt
1394 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1395 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001396
Janis Danisevskis66784c42021-01-27 08:40:25 -08001397 db_utils::with_rows_extract_one(&mut rows, |row| {
1398 Ok(match row {
1399 Some(r) => r.get(0).context("Failed to unpack id.")?,
1400 None => None,
1401 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001402 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001403 .context("In get_or_create_key_with.")?
1404 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001405
Janis Danisevskis66784c42021-01-27 08:40:25 -08001406 let (id, entry) = match id {
1407 Some(id) => (
1408 id,
1409 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1410 .context("In get_or_create_key_with.")?,
1411 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001412
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 None => {
1414 let id = Self::insert_with_retry(|id| {
1415 tx.execute(
1416 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001417 (id, key_type, domain, namespace, alias, state, km_uuid)
1418 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 params![
1420 id,
1421 KeyType::Super,
1422 domain.0,
1423 namespace,
1424 alias,
1425 KeyLifeCycle::Live,
1426 km_uuid,
1427 ],
1428 )
1429 })
1430 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001431
Janis Danisevskis66784c42021-01-27 08:40:25 -08001432 let (blob, metadata) =
1433 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001434 Self::set_blob_internal(
1435 &tx,
1436 id,
1437 SubComponentType::KEY_BLOB,
1438 Some(&blob),
1439 Some(&metadata),
1440 )
Paul Crowley7a658392021-03-18 17:08:20 -07001441 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001442 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001443 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001444 KeyEntry {
1445 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001446 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001447 pure_cert: false,
1448 ..Default::default()
1449 },
1450 )
1451 }
1452 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001453 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001454 })
1455 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001456 }
1457
Janis Danisevskis66784c42021-01-27 08:40:25 -08001458 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1459 /// waiting for the database file to become available. This makes it
1460 /// impossible to successfully recover from a locked database when the
1461 /// transaction holding the device busy is in the same process on a
1462 /// different connection. As a result the busy handler has to time out and
1463 /// fail in order to make progress.
1464 ///
1465 /// Instead, we set the busy handler to None (return immediately). And catch
1466 /// Busy and Locked errors (the latter occur on in memory databases with
1467 /// shared cache, e.g., the per-boot database.) and restart the transaction
1468 /// after a grace period of half a millisecond.
1469 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001470 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001471 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1472 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001473 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1474 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001475 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001476 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001477 loop {
1478 match self
1479 .conn
1480 .transaction_with_behavior(behavior)
1481 .context("In with_transaction.")
1482 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1483 .and_then(|(result, tx)| {
1484 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1485 Ok(result)
1486 }) {
1487 Ok(result) => break Ok(result),
1488 Err(e) => {
1489 if Self::is_locked_error(&e) {
1490 std::thread::sleep(std::time::Duration::from_micros(500));
1491 continue;
1492 } else {
1493 return Err(e).context("In with_transaction.");
1494 }
1495 }
1496 }
1497 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001498 .map(|(need_gc, result)| {
1499 if need_gc {
1500 if let Some(ref gc) = self.gc {
1501 gc.notify_gc();
1502 }
1503 }
1504 result
1505 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001506 }
1507
1508 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001509 matches!(
1510 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1511 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1512 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1513 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001514 }
1515
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001516 /// Creates a new key entry and allocates a new randomized id for the new key.
1517 /// The key id gets associated with a domain and namespace but not with an alias.
1518 /// To complete key generation `rebind_alias` should be called after all of the
1519 /// key artifacts, i.e., blobs and parameters have been associated with the new
1520 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1521 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001522 pub fn create_key_entry(
1523 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001524 domain: &Domain,
1525 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001526 km_uuid: &Uuid,
1527 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001528 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1529
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001530 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001531 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001532 })
1533 .context("In create_key_entry.")
1534 }
1535
1536 fn create_key_entry_internal(
1537 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001538 domain: &Domain,
1539 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001540 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001541 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001542 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001543 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001544 _ => {
1545 return Err(KsError::sys())
1546 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1547 }
1548 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001549 Ok(KEY_ID_LOCK.get(
1550 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001551 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001552 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001553 (id, key_type, domain, namespace, alias, state, km_uuid)
1554 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001555 params![
1556 id,
1557 KeyType::Client,
1558 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001559 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001560 KeyLifeCycle::Existing,
1561 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001562 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001563 )
1564 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001565 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001566 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001567 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001568
Max Bires2b2e6562020-09-22 11:22:36 -07001569 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1570 /// The key id gets associated with a domain and namespace later but not with an alias. The
1571 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1572 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1573 /// a key.
1574 pub fn create_attestation_key_entry(
1575 &mut self,
1576 maced_public_key: &[u8],
1577 raw_public_key: &[u8],
1578 private_key: &[u8],
1579 km_uuid: &Uuid,
1580 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001581 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1582
Max Bires2b2e6562020-09-22 11:22:36 -07001583 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1584 let key_id = KEY_ID_LOCK.get(
1585 Self::insert_with_retry(|id| {
1586 tx.execute(
1587 "INSERT into persistent.keyentry
1588 (id, key_type, domain, namespace, alias, state, km_uuid)
1589 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1590 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1591 )
1592 })
1593 .context("In create_key_entry")?,
1594 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001595 Self::set_blob_internal(
1596 &tx,
1597 key_id.0,
1598 SubComponentType::KEY_BLOB,
1599 Some(private_key),
1600 None,
1601 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001602 let mut metadata = KeyMetaData::new();
1603 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1604 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1605 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001606 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001607 })
1608 .context("In create_attestation_key_entry")
1609 }
1610
Janis Danisevskis377d1002021-01-27 19:07:48 -08001611 /// Set a new blob and associates it with the given key id. Each blob
1612 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001613 /// Each key can have one of each sub component type associated. If more
1614 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001615 /// will get garbage collected.
1616 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1617 /// removed by setting blob to None.
1618 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001619 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001620 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001621 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001622 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001623 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001624 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001625 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1626
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001627 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001628 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001629 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001630 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001631 }
1632
Janis Danisevskiseed69842021-02-18 20:04:10 -08001633 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1634 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1635 /// We use this to insert key blobs into the database which can then be garbage collected
1636 /// lazily by the key garbage collector.
1637 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001638 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1639
Janis Danisevskiseed69842021-02-18 20:04:10 -08001640 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1641 Self::set_blob_internal(
1642 &tx,
1643 Self::UNASSIGNED_KEY_ID,
1644 SubComponentType::KEY_BLOB,
1645 Some(blob),
1646 Some(blob_metadata),
1647 )
1648 .need_gc()
1649 })
1650 .context("In set_deleted_blob.")
1651 }
1652
Janis Danisevskis377d1002021-01-27 19:07:48 -08001653 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001654 tx: &Transaction,
1655 key_id: i64,
1656 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001657 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001658 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001659 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001660 match (blob, sc_type) {
1661 (Some(blob), _) => {
1662 tx.execute(
1663 "INSERT INTO persistent.blobentry
1664 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1665 params![sc_type, key_id, blob],
1666 )
1667 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001668 if let Some(blob_metadata) = blob_metadata {
1669 let blob_id = tx
1670 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1671 row.get(0)
1672 })
1673 .context("In set_blob_internal: Failed to get new blob id.")?;
1674 blob_metadata
1675 .store_in_db(blob_id, tx)
1676 .context("In set_blob_internal: Trying to store blob metadata.")?;
1677 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001678 }
1679 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1680 tx.execute(
1681 "DELETE FROM persistent.blobentry
1682 WHERE subcomponent_type = ? AND keyentryid = ?;",
1683 params![sc_type, key_id],
1684 )
1685 .context("In set_blob_internal: Failed to delete blob.")?;
1686 }
1687 (None, _) => {
1688 return Err(KsError::sys())
1689 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1690 }
1691 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001692 Ok(())
1693 }
1694
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001695 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1696 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001697 #[cfg(test)]
1698 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001699 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001700 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001701 })
1702 .context("In insert_keyparameter.")
1703 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001704
Janis Danisevskis66784c42021-01-27 08:40:25 -08001705 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001706 tx: &Transaction,
1707 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001708 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001709 ) -> Result<()> {
1710 let mut stmt = tx
1711 .prepare(
1712 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1713 VALUES (?, ?, ?, ?);",
1714 )
1715 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1716
Janis Danisevskis66784c42021-01-27 08:40:25 -08001717 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001718 stmt.insert(params![
1719 key_id.0,
1720 p.get_tag().0,
1721 p.key_parameter_value(),
1722 p.security_level().0
1723 ])
1724 .with_context(|| {
1725 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1726 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001727 }
1728 Ok(())
1729 }
1730
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001731 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001732 #[cfg(test)]
1733 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001734 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001735 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001736 })
1737 .context("In insert_key_metadata.")
1738 }
1739
Max Bires2b2e6562020-09-22 11:22:36 -07001740 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1741 /// on the public key.
1742 pub fn store_signed_attestation_certificate_chain(
1743 &mut self,
1744 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001745 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001746 cert_chain: &[u8],
1747 expiration_date: i64,
1748 km_uuid: &Uuid,
1749 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001750 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1751
Max Bires2b2e6562020-09-22 11:22:36 -07001752 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1753 let mut stmt = tx
1754 .prepare(
1755 "SELECT keyentryid
1756 FROM persistent.keymetadata
1757 WHERE tag = ? AND data = ? AND keyentryid IN
1758 (SELECT id
1759 FROM persistent.keyentry
1760 WHERE
1761 alias IS NULL AND
1762 domain IS NULL AND
1763 namespace IS NULL AND
1764 key_type = ? AND
1765 km_uuid = ?);",
1766 )
1767 .context("Failed to store attestation certificate chain.")?;
1768 let mut rows = stmt
1769 .query(params![
1770 KeyMetaData::AttestationRawPubKey,
1771 raw_public_key,
1772 KeyType::Attestation,
1773 km_uuid
1774 ])
1775 .context("Failed to fetch keyid")?;
1776 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1777 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1778 .get(0)
1779 .context("Failed to unpack id.")
1780 })
1781 .context("Failed to get key_id.")?;
1782 let num_updated = tx
1783 .execute(
1784 "UPDATE persistent.keyentry
1785 SET alias = ?
1786 WHERE id = ?;",
1787 params!["signed", key_id],
1788 )
1789 .context("Failed to update alias.")?;
1790 if num_updated != 1 {
1791 return Err(KsError::sys()).context("Alias not updated for the key.");
1792 }
1793 let mut metadata = KeyMetaData::new();
1794 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1795 expiration_date,
1796 )));
1797 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001798 Self::set_blob_internal(
1799 &tx,
1800 key_id,
1801 SubComponentType::CERT_CHAIN,
1802 Some(cert_chain),
1803 None,
1804 )
1805 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001806 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1807 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001808 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001809 })
1810 .context("In store_signed_attestation_certificate_chain: ")
1811 }
1812
1813 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1814 /// currently have a key assigned to it.
1815 pub fn assign_attestation_key(
1816 &mut self,
1817 domain: Domain,
1818 namespace: i64,
1819 km_uuid: &Uuid,
1820 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001821 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1822
Max Bires2b2e6562020-09-22 11:22:36 -07001823 match domain {
1824 Domain::APP | Domain::SELINUX => {}
1825 _ => {
1826 return Err(KsError::sys()).context(format!(
1827 concat!(
1828 "In assign_attestation_key: Domain {:?} ",
1829 "must be either App or SELinux.",
1830 ),
1831 domain
1832 ));
1833 }
1834 }
1835 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1836 let result = tx
1837 .execute(
1838 "UPDATE persistent.keyentry
1839 SET domain=?1, namespace=?2
1840 WHERE
1841 id =
1842 (SELECT MIN(id)
1843 FROM persistent.keyentry
1844 WHERE ALIAS IS NOT NULL
1845 AND domain IS NULL
1846 AND key_type IS ?3
1847 AND state IS ?4
1848 AND km_uuid IS ?5)
1849 AND
1850 (SELECT COUNT(*)
1851 FROM persistent.keyentry
1852 WHERE domain=?1
1853 AND namespace=?2
1854 AND key_type IS ?3
1855 AND state IS ?4
1856 AND km_uuid IS ?5) = 0;",
1857 params![
1858 domain.0 as u32,
1859 namespace,
1860 KeyType::Attestation,
1861 KeyLifeCycle::Live,
1862 km_uuid,
1863 ],
1864 )
1865 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001866 if result == 0 {
1867 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1868 } else if result > 1 {
1869 return Err(KsError::sys())
1870 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001871 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001872 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001873 })
1874 .context("In assign_attestation_key: ")
1875 }
1876
1877 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1878 /// provisioning server, or the maximum number available if there are not num_keys number of
1879 /// entries in the table.
1880 pub fn fetch_unsigned_attestation_keys(
1881 &mut self,
1882 num_keys: i32,
1883 km_uuid: &Uuid,
1884 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001885 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1886
Max Bires2b2e6562020-09-22 11:22:36 -07001887 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1888 let mut stmt = tx
1889 .prepare(
1890 "SELECT data
1891 FROM persistent.keymetadata
1892 WHERE tag = ? AND keyentryid IN
1893 (SELECT id
1894 FROM persistent.keyentry
1895 WHERE
1896 alias IS NULL AND
1897 domain IS NULL AND
1898 namespace IS NULL AND
1899 key_type = ? AND
1900 km_uuid = ?
1901 LIMIT ?);",
1902 )
1903 .context("Failed to prepare statement")?;
1904 let rows = stmt
1905 .query_map(
1906 params![
1907 KeyMetaData::AttestationMacedPublicKey,
1908 KeyType::Attestation,
1909 km_uuid,
1910 num_keys
1911 ],
1912 |row| Ok(row.get(0)?),
1913 )?
1914 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1915 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001916 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001917 })
1918 .context("In fetch_unsigned_attestation_keys")
1919 }
1920
1921 /// Removes any keys that have expired as of the current time. Returns the number of keys
1922 /// marked unreferenced that are bound to be garbage collected.
1923 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001924 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1925
Max Bires2b2e6562020-09-22 11:22:36 -07001926 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1927 let mut stmt = tx
1928 .prepare(
1929 "SELECT keyentryid, data
1930 FROM persistent.keymetadata
1931 WHERE tag = ? AND keyentryid IN
1932 (SELECT id
1933 FROM persistent.keyentry
1934 WHERE key_type = ?);",
1935 )
1936 .context("Failed to prepare query")?;
1937 let key_ids_to_check = stmt
1938 .query_map(
1939 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1940 |row| Ok((row.get(0)?, row.get(1)?)),
1941 )?
1942 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1943 .context("Failed to get date metadata")?;
1944 let curr_time = DateTime::from_millis_epoch(
1945 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1946 );
1947 let mut num_deleted = 0;
1948 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1949 if Self::mark_unreferenced(&tx, id)? {
1950 num_deleted += 1;
1951 }
1952 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001953 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001954 })
1955 .context("In delete_expired_attestation_keys: ")
1956 }
1957
Max Bires60d7ed12021-03-05 15:59:22 -08001958 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1959 /// they are in. This is useful primarily as a testing mechanism.
1960 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001961 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1962
Max Bires60d7ed12021-03-05 15:59:22 -08001963 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1964 let mut stmt = tx
1965 .prepare(
1966 "SELECT id FROM persistent.keyentry
1967 WHERE key_type IS ?;",
1968 )
1969 .context("Failed to prepare statement")?;
1970 let keys_to_delete = stmt
1971 .query_map(params![KeyType::Attestation], |row| Ok(row.get(0)?))?
1972 .collect::<rusqlite::Result<Vec<i64>>>()
1973 .context("Failed to execute statement")?;
1974 let num_deleted = keys_to_delete
1975 .iter()
1976 .map(|id| Self::mark_unreferenced(&tx, *id))
1977 .collect::<Result<Vec<bool>>>()
1978 .context("Failed to execute mark_unreferenced on a keyid")?
1979 .into_iter()
1980 .filter(|result| *result)
1981 .count() as i64;
1982 Ok(num_deleted).do_gc(num_deleted != 0)
1983 })
1984 .context("In delete_all_attestation_keys: ")
1985 }
1986
Max Bires2b2e6562020-09-22 11:22:36 -07001987 /// Counts the number of keys that will expire by the provided epoch date and the number of
1988 /// keys not currently assigned to a domain.
1989 pub fn get_attestation_pool_status(
1990 &mut self,
1991 date: i64,
1992 km_uuid: &Uuid,
1993 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001994 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1995
Max Bires2b2e6562020-09-22 11:22:36 -07001996 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1997 let mut stmt = tx.prepare(
1998 "SELECT data
1999 FROM persistent.keymetadata
2000 WHERE tag = ? AND keyentryid IN
2001 (SELECT id
2002 FROM persistent.keyentry
2003 WHERE alias IS NOT NULL
2004 AND key_type = ?
2005 AND km_uuid = ?
2006 AND state = ?);",
2007 )?;
2008 let times = stmt
2009 .query_map(
2010 params![
2011 KeyMetaData::AttestationExpirationDate,
2012 KeyType::Attestation,
2013 km_uuid,
2014 KeyLifeCycle::Live
2015 ],
2016 |row| Ok(row.get(0)?),
2017 )?
2018 .collect::<rusqlite::Result<Vec<DateTime>>>()
2019 .context("Failed to execute metadata statement")?;
2020 let expiring =
2021 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2022 as i32;
2023 stmt = tx.prepare(
2024 "SELECT alias, domain
2025 FROM persistent.keyentry
2026 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2027 )?;
2028 let rows = stmt
2029 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2030 Ok((row.get(0)?, row.get(1)?))
2031 })?
2032 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2033 .context("Failed to execute keyentry statement")?;
2034 let mut unassigned = 0i32;
2035 let mut attested = 0i32;
2036 let total = rows.len() as i32;
2037 for (alias, domain) in rows {
2038 match (alias, domain) {
2039 (Some(_alias), None) => {
2040 attested += 1;
2041 unassigned += 1;
2042 }
2043 (Some(_alias), Some(_domain)) => {
2044 attested += 1;
2045 }
2046 _ => {}
2047 }
2048 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002049 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002050 })
2051 .context("In get_attestation_pool_status: ")
2052 }
2053
2054 /// Fetches the private key and corresponding certificate chain assigned to a
2055 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2056 /// not assigned, or one CertificateChain.
2057 pub fn retrieve_attestation_key_and_cert_chain(
2058 &mut self,
2059 domain: Domain,
2060 namespace: i64,
2061 km_uuid: &Uuid,
2062 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002063 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2064
Max Bires2b2e6562020-09-22 11:22:36 -07002065 match domain {
2066 Domain::APP | Domain::SELINUX => {}
2067 _ => {
2068 return Err(KsError::sys())
2069 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2070 }
2071 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002072 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2073 let mut stmt = tx.prepare(
2074 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002075 FROM persistent.blobentry
2076 WHERE keyentryid IN
2077 (SELECT id
2078 FROM persistent.keyentry
2079 WHERE key_type = ?
2080 AND domain = ?
2081 AND namespace = ?
2082 AND state = ?
2083 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002084 )?;
2085 let rows = stmt
2086 .query_map(
2087 params![
2088 KeyType::Attestation,
2089 domain.0 as u32,
2090 namespace,
2091 KeyLifeCycle::Live,
2092 km_uuid
2093 ],
2094 |row| Ok((row.get(0)?, row.get(1)?)),
2095 )?
2096 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002097 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002098 if rows.is_empty() {
2099 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002100 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002101 return Err(KsError::sys()).context(format!(
2102 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002103 "Expected to get a single attestation",
2104 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2105 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002106 rows.len()
2107 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002108 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002109 let mut km_blob: Vec<u8> = Vec::new();
2110 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002111 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002112 for row in rows {
2113 let sub_type: SubComponentType = row.0;
2114 match sub_type {
2115 SubComponentType::KEY_BLOB => {
2116 km_blob = row.1;
2117 }
2118 SubComponentType::CERT_CHAIN => {
2119 cert_chain_blob = row.1;
2120 }
Max Biresb2e1d032021-02-08 21:35:05 -08002121 SubComponentType::CERT => {
2122 batch_cert_blob = row.1;
2123 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002124 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2125 }
2126 }
2127 Ok(Some(CertificateChain {
2128 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002129 batch_cert: batch_cert_blob,
2130 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002131 }))
2132 .no_gc()
2133 })
Max Biresb2e1d032021-02-08 21:35:05 -08002134 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002135 }
2136
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002137 /// Updates the alias column of the given key id `newid` with the given alias,
2138 /// and atomically, removes the alias, domain, and namespace from another row
2139 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002140 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2141 /// collector.
2142 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002143 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002144 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002145 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002146 domain: &Domain,
2147 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002148 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002149 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002150 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002151 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002152 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002153 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002154 domain
2155 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002156 }
2157 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002158 let updated = tx
2159 .execute(
2160 "UPDATE persistent.keyentry
2161 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07002162 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002163 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
2164 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002165 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002166 let result = tx
2167 .execute(
2168 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002169 SET alias = ?, state = ?
2170 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
2171 params![
2172 alias,
2173 KeyLifeCycle::Live,
2174 newid.0,
2175 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002176 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002177 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002178 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002179 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002180 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002181 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002182 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002183 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002184 result
2185 ));
2186 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002187 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002188 }
2189
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002190 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2191 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2192 pub fn migrate_key_namespace(
2193 &mut self,
2194 key_id_guard: KeyIdGuard,
2195 destination: &KeyDescriptor,
2196 caller_uid: u32,
2197 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2198 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002199 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2200
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002201 let destination = match destination.domain {
2202 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2203 Domain::SELINUX => (*destination).clone(),
2204 domain => {
2205 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2206 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2207 }
2208 };
2209
2210 // Security critical: Must return immediately on failure. Do not remove the '?';
2211 check_permission(&destination)
2212 .context("In migrate_key_namespace: Trying to check permission.")?;
2213
2214 let alias = destination
2215 .alias
2216 .as_ref()
2217 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2218 .context("In migrate_key_namespace: Alias must be specified.")?;
2219
2220 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2221 // Query the destination location. If there is a key, the migration request fails.
2222 if tx
2223 .query_row(
2224 "SELECT id FROM persistent.keyentry
2225 WHERE alias = ? AND domain = ? AND namespace = ?;",
2226 params![alias, destination.domain.0, destination.nspace],
2227 |_| Ok(()),
2228 )
2229 .optional()
2230 .context("Failed to query destination.")?
2231 .is_some()
2232 {
2233 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2234 .context("Target already exists.");
2235 }
2236
2237 let updated = tx
2238 .execute(
2239 "UPDATE persistent.keyentry
2240 SET alias = ?, domain = ?, namespace = ?
2241 WHERE id = ?;",
2242 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2243 )
2244 .context("Failed to update key entry.")?;
2245
2246 if updated != 1 {
2247 return Err(KsError::sys())
2248 .context(format!("Update succeeded, but {} rows were updated.", updated));
2249 }
2250 Ok(()).no_gc()
2251 })
2252 .context("In migrate_key_namespace:")
2253 }
2254
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002255 /// Store a new key in a single transaction.
2256 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2257 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002258 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2259 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002260 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002261 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002262 key: &KeyDescriptor,
2263 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002264 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002265 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002266 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002267 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002268 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002269 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2270
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 let (alias, domain, namespace) = match key {
2272 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2273 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2274 (alias, key.domain, nspace)
2275 }
2276 _ => {
2277 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2278 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2279 }
2280 };
2281 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002282 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002283 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002284 let (blob, blob_metadata) = *blob_info;
2285 Self::set_blob_internal(
2286 tx,
2287 key_id.id(),
2288 SubComponentType::KEY_BLOB,
2289 Some(blob),
2290 Some(&blob_metadata),
2291 )
2292 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002293 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002294 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002295 .context("Trying to insert the certificate.")?;
2296 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002297 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002298 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002299 tx,
2300 key_id.id(),
2301 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002302 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002303 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002304 )
2305 .context("Trying to insert the certificate chain.")?;
2306 }
2307 Self::insert_keyparameter_internal(tx, &key_id, params)
2308 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002309 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002310 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002311 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002312 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002313 })
2314 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002315 }
2316
Janis Danisevskis377d1002021-01-27 19:07:48 -08002317 /// Store a new certificate
2318 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2319 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002320 pub fn store_new_certificate(
2321 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002322 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002323 cert: &[u8],
2324 km_uuid: &Uuid,
2325 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002326 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2327
Janis Danisevskis377d1002021-01-27 19:07:48 -08002328 let (alias, domain, namespace) = match key {
2329 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2330 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2331 (alias, key.domain, nspace)
2332 }
2333 _ => {
2334 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2335 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2336 )
2337 }
2338 };
2339 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002340 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002341 .context("Trying to create new key entry.")?;
2342
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002343 Self::set_blob_internal(
2344 tx,
2345 key_id.id(),
2346 SubComponentType::CERT_CHAIN,
2347 Some(cert),
2348 None,
2349 )
2350 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002351
2352 let mut metadata = KeyMetaData::new();
2353 metadata.add(KeyMetaEntry::CreationDate(
2354 DateTime::now().context("Trying to make creation time.")?,
2355 ));
2356
2357 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2358
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002359 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002360 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002361 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002362 })
2363 .context("In store_new_certificate.")
2364 }
2365
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002366 // Helper function loading the key_id given the key descriptor
2367 // tuple comprising domain, namespace, and alias.
2368 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002369 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002370 let alias = key
2371 .alias
2372 .as_ref()
2373 .map_or_else(|| Err(KsError::sys()), Ok)
2374 .context("In load_key_entry_id: Alias must be specified.")?;
2375 let mut stmt = tx
2376 .prepare(
2377 "SELECT id FROM persistent.keyentry
2378 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002379 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002380 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002381 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002382 AND alias = ?
2383 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002384 )
2385 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2386 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002387 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002388 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002389 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002390 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002391 .get(0)
2392 .context("Failed to unpack id.")
2393 })
2394 .context("In load_key_entry_id.")
2395 }
2396
2397 /// This helper function completes the access tuple of a key, which is required
2398 /// to perform access control. The strategy depends on the `domain` field in the
2399 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002400 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002401 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002402 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002403 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002404 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002405 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002406 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002407 /// `namespace`.
2408 /// In each case the information returned is sufficient to perform the access
2409 /// check and the key id can be used to load further key artifacts.
2410 fn load_access_tuple(
2411 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002412 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002413 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002414 caller_uid: u32,
2415 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2416 match key.domain {
2417 // Domain App or SELinux. In this case we load the key_id from
2418 // the keyentry database for further loading of key components.
2419 // We already have the full access tuple to perform access control.
2420 // The only distinction is that we use the caller_uid instead
2421 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002422 // Domain::APP.
2423 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002424 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002425 if access_key.domain == Domain::APP {
2426 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002427 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002428 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002429 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002430
2431 Ok((key_id, access_key, None))
2432 }
2433
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002434 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002435 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002436 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002437 let mut stmt = tx
2438 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002439 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002440 WHERE grantee = ? AND id = ?;",
2441 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002442 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002443 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002444 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002445 .context("Domain:Grant: query failed.")?;
2446 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002447 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002448 let r =
2449 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002450 Ok((
2451 r.get(0).context("Failed to unpack key_id.")?,
2452 r.get(1).context("Failed to unpack access_vector.")?,
2453 ))
2454 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002455 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002456 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002457 }
2458
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002459 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002460 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002461 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002462 let (domain, namespace): (Domain, i64) = {
2463 let mut stmt = tx
2464 .prepare(
2465 "SELECT domain, namespace FROM persistent.keyentry
2466 WHERE
2467 id = ?
2468 AND state = ?;",
2469 )
2470 .context("Domain::KEY_ID: prepare statement failed")?;
2471 let mut rows = stmt
2472 .query(params![key.nspace, KeyLifeCycle::Live])
2473 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002474 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002475 let r =
2476 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002477 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002478 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002479 r.get(1).context("Failed to unpack namespace.")?,
2480 ))
2481 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002482 .context("Domain::KEY_ID.")?
2483 };
2484
2485 // We may use a key by id after loading it by grant.
2486 // In this case we have to check if the caller has a grant for this particular
2487 // key. We can skip this if we already know that the caller is the owner.
2488 // But we cannot know this if domain is anything but App. E.g. in the case
2489 // of Domain::SELINUX we have to speculatively check for grants because we have to
2490 // consult the SEPolicy before we know if the caller is the owner.
2491 let access_vector: Option<KeyPermSet> =
2492 if domain != Domain::APP || namespace != caller_uid as i64 {
2493 let access_vector: Option<i32> = tx
2494 .query_row(
2495 "SELECT access_vector FROM persistent.grant
2496 WHERE grantee = ? AND keyentryid = ?;",
2497 params![caller_uid as i64, key.nspace],
2498 |row| row.get(0),
2499 )
2500 .optional()
2501 .context("Domain::KEY_ID: query grant failed.")?;
2502 access_vector.map(|p| p.into())
2503 } else {
2504 None
2505 };
2506
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002507 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002508 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002509 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002510 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002511
Janis Danisevskis45760022021-01-19 16:34:10 -08002512 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002513 }
2514 _ => Err(anyhow!(KsError::sys())),
2515 }
2516 }
2517
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002518 fn load_blob_components(
2519 key_id: i64,
2520 load_bits: KeyEntryLoadBits,
2521 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002522 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002523 let mut stmt = tx
2524 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002525 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002526 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2527 )
2528 .context("In load_blob_components: prepare statement failed.")?;
2529
2530 let mut rows =
2531 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2532
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002533 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002534 let mut cert_blob: Option<Vec<u8>> = None;
2535 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002536 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002537 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002538 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002539 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002540 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002541 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2542 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002543 key_blob = Some((
2544 row.get(0).context("Failed to extract key blob id.")?,
2545 row.get(2).context("Failed to extract key blob.")?,
2546 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002547 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002548 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002549 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002550 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002551 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002552 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002553 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002554 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002555 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002556 (SubComponentType::CERT, _, _)
2557 | (SubComponentType::CERT_CHAIN, _, _)
2558 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002559 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2560 }
2561 Ok(())
2562 })
2563 .context("In load_blob_components.")?;
2564
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002565 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2566 Ok(Some((
2567 blob,
2568 BlobMetaData::load_from_db(blob_id, tx)
2569 .context("In load_blob_components: Trying to load blob_metadata.")?,
2570 )))
2571 })?;
2572
2573 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002574 }
2575
2576 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2577 let mut stmt = tx
2578 .prepare(
2579 "SELECT tag, data, security_level from persistent.keyparameter
2580 WHERE keyentryid = ?;",
2581 )
2582 .context("In load_key_parameters: prepare statement failed.")?;
2583
2584 let mut parameters: Vec<KeyParameter> = Vec::new();
2585
2586 let mut rows =
2587 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002588 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002589 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2590 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002591 parameters.push(
2592 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2593 .context("Failed to read KeyParameter.")?,
2594 );
2595 Ok(())
2596 })
2597 .context("In load_key_parameters.")?;
2598
2599 Ok(parameters)
2600 }
2601
Qi Wub9433b52020-12-01 14:52:46 +08002602 /// Decrements the usage count of a limited use key. This function first checks whether the
2603 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2604 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2605 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002606 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002607 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2608
Qi Wub9433b52020-12-01 14:52:46 +08002609 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2610 let limit: Option<i32> = tx
2611 .query_row(
2612 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2613 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2614 |row| row.get(0),
2615 )
2616 .optional()
2617 .context("Trying to load usage count")?;
2618
2619 let limit = limit
2620 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2621 .context("The Key no longer exists. Key is exhausted.")?;
2622
2623 tx.execute(
2624 "UPDATE persistent.keyparameter
2625 SET data = data - 1
2626 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2627 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2628 )
2629 .context("Failed to update key usage count.")?;
2630
2631 match limit {
2632 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002633 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002634 .context("Trying to mark limited use key for deletion."),
2635 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002636 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002637 }
2638 })
2639 .context("In check_and_update_key_usage_count.")
2640 }
2641
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002642 /// Load a key entry by the given key descriptor.
2643 /// It uses the `check_permission` callback to verify if the access is allowed
2644 /// given the key access tuple read from the database using `load_access_tuple`.
2645 /// With `load_bits` the caller may specify which blobs shall be loaded from
2646 /// the blob database.
2647 pub fn load_key_entry(
2648 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002649 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002650 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002651 load_bits: KeyEntryLoadBits,
2652 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002653 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2654 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002655 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2656
Janis Danisevskis66784c42021-01-27 08:40:25 -08002657 loop {
2658 match self.load_key_entry_internal(
2659 key,
2660 key_type,
2661 load_bits,
2662 caller_uid,
2663 &check_permission,
2664 ) {
2665 Ok(result) => break Ok(result),
2666 Err(e) => {
2667 if Self::is_locked_error(&e) {
2668 std::thread::sleep(std::time::Duration::from_micros(500));
2669 continue;
2670 } else {
2671 return Err(e).context("In load_key_entry.");
2672 }
2673 }
2674 }
2675 }
2676 }
2677
2678 fn load_key_entry_internal(
2679 &mut self,
2680 key: &KeyDescriptor,
2681 key_type: KeyType,
2682 load_bits: KeyEntryLoadBits,
2683 caller_uid: u32,
2684 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002685 ) -> Result<(KeyIdGuard, KeyEntry)> {
2686 // KEY ID LOCK 1/2
2687 // If we got a key descriptor with a key id we can get the lock right away.
2688 // Otherwise we have to defer it until we know the key id.
2689 let key_id_guard = match key.domain {
2690 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2691 _ => None,
2692 };
2693
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002694 let tx = self
2695 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002696 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002697 .context("In load_key_entry: Failed to initialize transaction.")?;
2698
2699 // Load the key_id and complete the access control tuple.
2700 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002701 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2702 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002703
2704 // Perform access control. It is vital that we return here if the permission is denied.
2705 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002706 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002707
Janis Danisevskisaec14592020-11-12 09:41:49 -08002708 // KEY ID LOCK 2/2
2709 // If we did not get a key id lock by now, it was because we got a key descriptor
2710 // without a key id. At this point we got the key id, so we can try and get a lock.
2711 // However, we cannot block here, because we are in the middle of the transaction.
2712 // So first we try to get the lock non blocking. If that fails, we roll back the
2713 // transaction and block until we get the lock. After we successfully got the lock,
2714 // we start a new transaction and load the access tuple again.
2715 //
2716 // We don't need to perform access control again, because we already established
2717 // that the caller had access to the given key. But we need to make sure that the
2718 // key id still exists. So we have to load the key entry by key id this time.
2719 let (key_id_guard, tx) = match key_id_guard {
2720 None => match KEY_ID_LOCK.try_get(key_id) {
2721 None => {
2722 // Roll back the transaction.
2723 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002724
Janis Danisevskisaec14592020-11-12 09:41:49 -08002725 // Block until we have a key id lock.
2726 let key_id_guard = KEY_ID_LOCK.get(key_id);
2727
2728 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002729 let tx = self
2730 .conn
2731 .unchecked_transaction()
2732 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002733
2734 Self::load_access_tuple(
2735 &tx,
2736 // This time we have to load the key by the retrieved key id, because the
2737 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002738 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002739 domain: Domain::KEY_ID,
2740 nspace: key_id,
2741 ..Default::default()
2742 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002743 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002744 caller_uid,
2745 )
2746 .context("In load_key_entry. (deferred key lock)")?;
2747 (key_id_guard, tx)
2748 }
2749 Some(l) => (l, tx),
2750 },
2751 Some(key_id_guard) => (key_id_guard, tx),
2752 };
2753
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002754 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2755 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002756
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002757 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2758
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002759 Ok((key_id_guard, key_entry))
2760 }
2761
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002762 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002763 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002764 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2765 .context("Trying to delete keyentry.")?;
2766 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2767 .context("Trying to delete keymetadata.")?;
2768 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2769 .context("Trying to delete keyparameters.")?;
2770 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2771 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002772 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002773 }
2774
2775 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002776 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002777 pub fn unbind_key(
2778 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002779 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002780 key_type: KeyType,
2781 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002782 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002783 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002784 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2785
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002786 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2787 let (key_id, access_key_descriptor, access_vector) =
2788 Self::load_access_tuple(tx, key, key_type, caller_uid)
2789 .context("Trying to get access tuple.")?;
2790
2791 // Perform access control. It is vital that we return here if the permission is denied.
2792 // So do not touch that '?' at the end.
2793 check_permission(&access_key_descriptor, access_vector)
2794 .context("While checking permission.")?;
2795
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002796 Self::mark_unreferenced(tx, key_id)
2797 .map(|need_gc| (need_gc, ()))
2798 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002799 })
2800 .context("In unbind_key.")
2801 }
2802
Max Bires8e93d2b2021-01-14 13:17:59 -08002803 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2804 tx.query_row(
2805 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2806 params![key_id],
2807 |row| row.get(0),
2808 )
2809 .context("In get_key_km_uuid.")
2810 }
2811
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002812 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2813 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2814 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002815 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2816
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002817 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2818 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2819 .context("In unbind_keys_for_namespace.");
2820 }
2821 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2822 tx.execute(
2823 "DELETE FROM persistent.keymetadata
2824 WHERE keyentryid IN (
2825 SELECT id FROM persistent.keyentry
2826 WHERE domain = ? AND namespace = ?
2827 );",
2828 params![domain.0, namespace],
2829 )
2830 .context("Trying to delete keymetadata.")?;
2831 tx.execute(
2832 "DELETE FROM persistent.keyparameter
2833 WHERE keyentryid IN (
2834 SELECT id FROM persistent.keyentry
2835 WHERE domain = ? AND namespace = ?
2836 );",
2837 params![domain.0, namespace],
2838 )
2839 .context("Trying to delete keyparameters.")?;
2840 tx.execute(
2841 "DELETE FROM persistent.grant
2842 WHERE keyentryid IN (
2843 SELECT id FROM persistent.keyentry
2844 WHERE domain = ? AND namespace = ?
2845 );",
2846 params![domain.0, namespace],
2847 )
2848 .context("Trying to delete grants.")?;
2849 tx.execute(
2850 "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;",
2851 params![domain.0, namespace],
2852 )
2853 .context("Trying to delete keyentry.")?;
2854 Ok(()).need_gc()
2855 })
2856 .context("In unbind_keys_for_namespace")
2857 }
2858
Hasini Gunasingheda895552021-01-27 19:34:37 +00002859 /// Delete the keys created on behalf of the user, denoted by the user id.
2860 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2861 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2862 /// The caller of this function should notify the gc if the returned value is true.
2863 pub fn unbind_keys_for_user(
2864 &mut self,
2865 user_id: u32,
2866 keep_non_super_encrypted_keys: bool,
2867 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002868 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2869
Hasini Gunasingheda895552021-01-27 19:34:37 +00002870 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2871 let mut stmt = tx
2872 .prepare(&format!(
2873 "SELECT id from persistent.keyentry
2874 WHERE (
2875 key_type = ?
2876 AND domain = ?
2877 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2878 AND state = ?
2879 ) OR (
2880 key_type = ?
2881 AND namespace = ?
2882 AND alias = ?
2883 AND state = ?
2884 );",
2885 aid_user_offset = AID_USER_OFFSET
2886 ))
2887 .context(concat!(
2888 "In unbind_keys_for_user. ",
2889 "Failed to prepare the query to find the keys created by apps."
2890 ))?;
2891
2892 let mut rows = stmt
2893 .query(params![
2894 // WHERE client key:
2895 KeyType::Client,
2896 Domain::APP.0 as u32,
2897 user_id,
2898 KeyLifeCycle::Live,
2899 // OR super key:
2900 KeyType::Super,
2901 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002902 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002903 KeyLifeCycle::Live
2904 ])
2905 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2906
2907 let mut key_ids: Vec<i64> = Vec::new();
2908 db_utils::with_rows_extract_all(&mut rows, |row| {
2909 key_ids
2910 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2911 Ok(())
2912 })
2913 .context("In unbind_keys_for_user.")?;
2914
2915 let mut notify_gc = false;
2916 for key_id in key_ids {
2917 if keep_non_super_encrypted_keys {
2918 // Load metadata and filter out non-super-encrypted keys.
2919 if let (_, Some((_, blob_metadata)), _, _) =
2920 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2921 .context("In unbind_keys_for_user: Trying to load blob info.")?
2922 {
2923 if blob_metadata.encrypted_by().is_none() {
2924 continue;
2925 }
2926 }
2927 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002928 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002929 .context("In unbind_keys_for_user.")?
2930 || notify_gc;
2931 }
2932 Ok(()).do_gc(notify_gc)
2933 })
2934 .context("In unbind_keys_for_user.")
2935 }
2936
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002937 fn load_key_components(
2938 tx: &Transaction,
2939 load_bits: KeyEntryLoadBits,
2940 key_id: i64,
2941 ) -> Result<KeyEntry> {
2942 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2943
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002944 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002945 Self::load_blob_components(key_id, load_bits, &tx)
2946 .context("In load_key_components.")?;
2947
Max Bires8e93d2b2021-01-14 13:17:59 -08002948 let parameters = Self::load_key_parameters(key_id, &tx)
2949 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002950
Max Bires8e93d2b2021-01-14 13:17:59 -08002951 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2952 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002953
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002954 Ok(KeyEntry {
2955 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002956 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002957 cert: cert_blob,
2958 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002959 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002960 parameters,
2961 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002962 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002963 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002964 }
2965
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002966 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2967 /// The key descriptors will have the domain, nspace, and alias field set.
2968 /// Domain must be APP or SELINUX, the caller must make sure of that.
2969 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002970 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2971
Janis Danisevskis66784c42021-01-27 08:40:25 -08002972 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2973 let mut stmt = tx
2974 .prepare(
2975 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002976 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002977 )
2978 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002979
Janis Danisevskis66784c42021-01-27 08:40:25 -08002980 let mut rows = stmt
2981 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2982 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002983
Janis Danisevskis66784c42021-01-27 08:40:25 -08002984 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2985 db_utils::with_rows_extract_all(&mut rows, |row| {
2986 descriptors.push(KeyDescriptor {
2987 domain,
2988 nspace: namespace,
2989 alias: Some(row.get(0).context("Trying to extract alias.")?),
2990 blob: None,
2991 });
2992 Ok(())
2993 })
2994 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002995 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002996 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002997 }
2998
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002999 /// Adds a grant to the grant table.
3000 /// Like `load_key_entry` this function loads the access tuple before
3001 /// it uses the callback for a permission check. Upon success,
3002 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3003 /// grant table. The new row will have a randomized id, which is used as
3004 /// grant id in the namespace field of the resulting KeyDescriptor.
3005 pub fn grant(
3006 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003007 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003008 caller_uid: u32,
3009 grantee_uid: u32,
3010 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003011 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003012 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003013 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3014
Janis Danisevskis66784c42021-01-27 08:40:25 -08003015 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3016 // Load the key_id and complete the access control tuple.
3017 // We ignore the access vector here because grants cannot be granted.
3018 // The access vector returned here expresses the permissions the
3019 // grantee has if key.domain == Domain::GRANT. But this vector
3020 // cannot include the grant permission by design, so there is no way the
3021 // subsequent permission check can pass.
3022 // We could check key.domain == Domain::GRANT and fail early.
3023 // But even if we load the access tuple by grant here, the permission
3024 // check denies the attempt to create a grant by grant descriptor.
3025 let (key_id, access_key_descriptor, _) =
3026 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3027 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003028
Janis Danisevskis66784c42021-01-27 08:40:25 -08003029 // Perform access control. It is vital that we return here if the permission
3030 // was denied. So do not touch that '?' at the end of the line.
3031 // This permission check checks if the caller has the grant permission
3032 // for the given key and in addition to all of the permissions
3033 // expressed in `access_vector`.
3034 check_permission(&access_key_descriptor, &access_vector)
3035 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003036
Janis Danisevskis66784c42021-01-27 08:40:25 -08003037 let grant_id = if let Some(grant_id) = tx
3038 .query_row(
3039 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003040 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003041 params![key_id, grantee_uid],
3042 |row| row.get(0),
3043 )
3044 .optional()
3045 .context("In grant: Failed get optional existing grant id.")?
3046 {
3047 tx.execute(
3048 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003049 SET access_vector = ?
3050 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003051 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003052 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003053 .context("In grant: Failed to update existing grant.")?;
3054 grant_id
3055 } else {
3056 Self::insert_with_retry(|id| {
3057 tx.execute(
3058 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3059 VALUES (?, ?, ?, ?);",
3060 params![id, grantee_uid, key_id, i32::from(access_vector)],
3061 )
3062 })
3063 .context("In grant")?
3064 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003065
Janis Danisevskis66784c42021-01-27 08:40:25 -08003066 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003067 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003068 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003069 }
3070
3071 /// This function checks permissions like `grant` and `load_key_entry`
3072 /// before removing a grant from the grant table.
3073 pub fn ungrant(
3074 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003075 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003076 caller_uid: u32,
3077 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003079 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003080 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3081
Janis Danisevskis66784c42021-01-27 08:40:25 -08003082 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3083 // Load the key_id and complete the access control tuple.
3084 // We ignore the access vector here because grants cannot be granted.
3085 let (key_id, access_key_descriptor, _) =
3086 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3087 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003088
Janis Danisevskis66784c42021-01-27 08:40:25 -08003089 // Perform access control. We must return here if the permission
3090 // was denied. So do not touch the '?' at the end of this line.
3091 check_permission(&access_key_descriptor)
3092 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003093
Janis Danisevskis66784c42021-01-27 08:40:25 -08003094 tx.execute(
3095 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003096 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003097 params![key_id, grantee_uid],
3098 )
3099 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003100
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003101 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003102 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003103 }
3104
Joel Galenson845f74b2020-09-09 14:11:55 -07003105 // Generates a random id and passes it to the given function, which will
3106 // try to insert it into a database. If that insertion fails, retry;
3107 // otherwise return the id.
3108 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3109 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003110 let newid: i64 = match random() {
3111 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3112 i => i,
3113 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003114 match inserter(newid) {
3115 // If the id already existed, try again.
3116 Err(rusqlite::Error::SqliteFailure(
3117 libsqlite3_sys::Error {
3118 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3119 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3120 },
3121 _,
3122 )) => (),
3123 Err(e) => {
3124 return Err(e).context("In insert_with_retry: failed to insert into database.")
3125 }
3126 _ => return Ok(newid),
3127 }
3128 }
3129 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003130
3131 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
3132 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003133 let _wp = wd::watch_millis("KeystoreDB::insert_auth_token", 500);
3134
Janis Danisevskis66784c42021-01-27 08:40:25 -08003135 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3136 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003137 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
3138 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
3139 params![
3140 auth_token.challenge,
3141 auth_token.userId,
3142 auth_token.authenticatorId,
3143 auth_token.authenticatorType.0 as i32,
3144 auth_token.timestamp.milliSeconds as i64,
3145 auth_token.mac,
3146 MonotonicRawTime::now(),
3147 ],
3148 )
3149 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003150 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003151 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003152 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003153
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003154 /// Find the newest auth token matching the given predicate.
3155 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003156 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003157 p: F,
3158 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
3159 where
3160 F: Fn(&AuthTokenEntry) -> bool,
3161 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003162 let _wp = wd::watch_millis("KeystoreDB::find_auth_token_entry", 500);
3163
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003164 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3165 let mut stmt = tx
3166 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
3167 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003168
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003169 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003170
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003171 while let Some(row) = rows.next().context("Failed to get next row.")? {
3172 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003173 HardwareAuthToken {
3174 challenge: row.get(1)?,
3175 userId: row.get(2)?,
3176 authenticatorId: row.get(3)?,
3177 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3178 timestamp: Timestamp { milliSeconds: row.get(5)? },
3179 mac: row.get(6)?,
3180 },
3181 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003182 );
3183 if p(&entry) {
3184 return Ok(Some((
3185 entry,
3186 Self::get_last_off_body(tx)
3187 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003188 )))
3189 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003190 }
3191 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003192 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003193 })
3194 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003195 }
3196
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003197 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08003198 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003199 let _wp = wd::watch_millis("KeystoreDB::insert_last_off_body", 500);
3200
Janis Danisevskis66784c42021-01-27 08:40:25 -08003201 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3202 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003203 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
3204 params!["last_off_body", last_off_body],
3205 )
3206 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003207 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003208 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003209 }
3210
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003211 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08003212 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003213 let _wp = wd::watch_millis("KeystoreDB::update_last_off_body", 500);
3214
Janis Danisevskis66784c42021-01-27 08:40:25 -08003215 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3216 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003217 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
3218 params![last_off_body, "last_off_body"],
3219 )
3220 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003221 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003222 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003223 }
3224
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003225 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003226 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003227 let _wp = wd::watch_millis("KeystoreDB::get_last_off_body", 500);
3228
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003229 tx.query_row(
3230 "SELECT value from perboot.metadata WHERE key = ?;",
3231 params!["last_off_body"],
3232 |row| Ok(row.get(0)?),
3233 )
3234 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003235 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003236}
3237
3238#[cfg(test)]
3239mod tests {
3240
3241 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003242 use crate::key_parameter::{
3243 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3244 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3245 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003246 use crate::key_perm_set;
3247 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003248 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003249 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003250 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3251 HardwareAuthToken::HardwareAuthToken,
3252 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003253 };
3254 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003255 Timestamp::Timestamp,
3256 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003257 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003258 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07003259 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003260 use std::collections::BTreeMap;
3261 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003262 use std::sync::atomic::{AtomicU8, Ordering};
3263 use std::sync::Arc;
3264 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003265 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003266 #[cfg(disabled)]
3267 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003268
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003269 fn new_test_db() -> Result<KeystoreDB> {
3270 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
3271
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003272 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003273 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003274 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003275 })?;
3276 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003277 }
3278
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003279 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3280 where
3281 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3282 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003283 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003284
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003285 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003286 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003287
Janis Danisevskis3395f862021-05-06 10:54:17 -07003288 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003289 }
3290
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003291 fn rebind_alias(
3292 db: &mut KeystoreDB,
3293 newid: &KeyIdGuard,
3294 alias: &str,
3295 domain: Domain,
3296 namespace: i64,
3297 ) -> Result<bool> {
3298 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003299 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003300 })
3301 .context("In rebind_alias.")
3302 }
3303
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003304 #[test]
3305 fn datetime() -> Result<()> {
3306 let conn = Connection::open_in_memory()?;
3307 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3308 let now = SystemTime::now();
3309 let duration = Duration::from_secs(1000);
3310 let then = now.checked_sub(duration).unwrap();
3311 let soon = now.checked_add(duration).unwrap();
3312 conn.execute(
3313 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3314 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3315 )?;
3316 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3317 let mut rows = stmt.query(NO_PARAMS)?;
3318 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3319 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3320 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3321 assert!(rows.next()?.is_none());
3322 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3323 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3324 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3325 Ok(())
3326 }
3327
Joel Galenson0891bc12020-07-20 10:37:03 -07003328 // Ensure that we're using the "injected" random function, not the real one.
3329 #[test]
3330 fn test_mocked_random() {
3331 let rand1 = random();
3332 let rand2 = random();
3333 let rand3 = random();
3334 if rand1 == rand2 {
3335 assert_eq!(rand2 + 1, rand3);
3336 } else {
3337 assert_eq!(rand1 + 1, rand2);
3338 assert_eq!(rand2, rand3);
3339 }
3340 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003341
Joel Galenson26f4d012020-07-17 14:57:21 -07003342 // Test that we have the correct tables.
3343 #[test]
3344 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003345 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003346 let tables = db
3347 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003348 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003349 .query_map(params![], |row| row.get(0))?
3350 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003351 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003352 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003353 assert_eq!(tables[1], "blobmetadata");
3354 assert_eq!(tables[2], "grant");
3355 assert_eq!(tables[3], "keyentry");
3356 assert_eq!(tables[4], "keymetadata");
3357 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003358 let tables = db
3359 .conn
3360 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3361 .query_map(params![], |row| row.get(0))?
3362 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003363
3364 assert_eq!(tables.len(), 2);
3365 assert_eq!(tables[0], "authtoken");
3366 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003367 Ok(())
3368 }
3369
3370 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003371 fn test_auth_token_table_invariant() -> Result<()> {
3372 let mut db = new_test_db()?;
3373 let auth_token1 = HardwareAuthToken {
3374 challenge: i64::MAX,
3375 userId: 200,
3376 authenticatorId: 200,
3377 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3378 timestamp: Timestamp { milliSeconds: 500 },
3379 mac: String::from("mac").into_bytes(),
3380 };
3381 db.insert_auth_token(&auth_token1)?;
3382 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3383 assert_eq!(auth_tokens_returned.len(), 1);
3384
3385 // insert another auth token with the same values for the columns in the UNIQUE constraint
3386 // of the auth token table and different value for timestamp
3387 let auth_token2 = HardwareAuthToken {
3388 challenge: i64::MAX,
3389 userId: 200,
3390 authenticatorId: 200,
3391 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3392 timestamp: Timestamp { milliSeconds: 600 },
3393 mac: String::from("mac").into_bytes(),
3394 };
3395
3396 db.insert_auth_token(&auth_token2)?;
3397 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3398 assert_eq!(auth_tokens_returned.len(), 1);
3399
3400 if let Some(auth_token) = auth_tokens_returned.pop() {
3401 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3402 }
3403
3404 // insert another auth token with the different values for the columns in the UNIQUE
3405 // constraint of the auth token table
3406 let auth_token3 = HardwareAuthToken {
3407 challenge: i64::MAX,
3408 userId: 201,
3409 authenticatorId: 200,
3410 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3411 timestamp: Timestamp { milliSeconds: 600 },
3412 mac: String::from("mac").into_bytes(),
3413 };
3414
3415 db.insert_auth_token(&auth_token3)?;
3416 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3417 assert_eq!(auth_tokens_returned.len(), 2);
3418
3419 Ok(())
3420 }
3421
3422 // utility function for test_auth_token_table_invariant()
3423 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3424 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3425
3426 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3427 .query_map(NO_PARAMS, |row| {
3428 Ok(AuthTokenEntry::new(
3429 HardwareAuthToken {
3430 challenge: row.get(1)?,
3431 userId: row.get(2)?,
3432 authenticatorId: row.get(3)?,
3433 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3434 timestamp: Timestamp { milliSeconds: row.get(5)? },
3435 mac: row.get(6)?,
3436 },
3437 row.get(7)?,
3438 ))
3439 })?
3440 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3441 Ok(auth_token_entries)
3442 }
3443
3444 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003445 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003446 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003447 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003448
Janis Danisevskis66784c42021-01-27 08:40:25 -08003449 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003450 let entries = get_keyentry(&db)?;
3451 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003452
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003453 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003454
3455 let entries_new = get_keyentry(&db)?;
3456 assert_eq!(entries, entries_new);
3457 Ok(())
3458 }
3459
3460 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003461 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003462 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3463 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003464 }
3465
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003466 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003467
Janis Danisevskis66784c42021-01-27 08:40:25 -08003468 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3469 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003470
3471 let entries = get_keyentry(&db)?;
3472 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003473 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3474 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003475
3476 // Test that we must pass in a valid Domain.
3477 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003478 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003479 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003480 );
3481 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003482 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003483 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003484 );
3485 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003486 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003487 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003488 );
3489
3490 Ok(())
3491 }
3492
Joel Galenson33c04ad2020-08-03 11:04:38 -07003493 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003494 fn test_add_unsigned_key() -> Result<()> {
3495 let mut db = new_test_db()?;
3496 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3497 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3498 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3499 db.create_attestation_key_entry(
3500 &public_key,
3501 &raw_public_key,
3502 &private_key,
3503 &KEYSTORE_UUID,
3504 )?;
3505 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3506 assert_eq!(keys.len(), 1);
3507 assert_eq!(keys[0], public_key);
3508 Ok(())
3509 }
3510
3511 #[test]
3512 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3513 let mut db = new_test_db()?;
3514 let expiration_date: i64 = 20;
3515 let namespace: i64 = 30;
3516 let base_byte: u8 = 1;
3517 let loaded_values =
3518 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3519 let chain =
3520 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3521 assert_eq!(true, chain.is_some());
3522 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003523 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003524 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3525 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003526 Ok(())
3527 }
3528
3529 #[test]
3530 fn test_get_attestation_pool_status() -> Result<()> {
3531 let mut db = new_test_db()?;
3532 let namespace: i64 = 30;
3533 load_attestation_key_pool(
3534 &mut db, 10, /* expiration */
3535 namespace, 0x01, /* base_byte */
3536 )?;
3537 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3538 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3539 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3540 assert_eq!(status.expiring, 0);
3541 assert_eq!(status.attested, 3);
3542 assert_eq!(status.unassigned, 0);
3543 assert_eq!(status.total, 3);
3544 assert_eq!(
3545 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3546 1
3547 );
3548 assert_eq!(
3549 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3550 2
3551 );
3552 assert_eq!(
3553 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3554 3
3555 );
3556 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3557 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3558 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3559 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003560 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003561 db.create_attestation_key_entry(
3562 &public_key,
3563 &raw_public_key,
3564 &private_key,
3565 &KEYSTORE_UUID,
3566 )?;
3567 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3568 assert_eq!(status.attested, 3);
3569 assert_eq!(status.unassigned, 0);
3570 assert_eq!(status.total, 4);
3571 db.store_signed_attestation_certificate_chain(
3572 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003573 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003574 &cert_chain,
3575 20,
3576 &KEYSTORE_UUID,
3577 )?;
3578 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3579 assert_eq!(status.attested, 4);
3580 assert_eq!(status.unassigned, 1);
3581 assert_eq!(status.total, 4);
3582 Ok(())
3583 }
3584
3585 #[test]
3586 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003587 let temp_dir =
3588 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3589 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003590 let expiration_date: i64 =
3591 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3592 let namespace: i64 = 30;
3593 let namespace_del1: i64 = 45;
3594 let namespace_del2: i64 = 60;
3595 let entry_values = load_attestation_key_pool(
3596 &mut db,
3597 expiration_date,
3598 namespace,
3599 0x01, /* base_byte */
3600 )?;
3601 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3602 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003603
3604 let blob_entry_row_count: u32 = db
3605 .conn
3606 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3607 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003608 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3609 // one key, one certificate chain, and one certificate.
3610 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003611
Max Bires2b2e6562020-09-22 11:22:36 -07003612 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3613
3614 let mut cert_chain =
3615 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003616 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003617 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003618 assert_eq!(entry_values.batch_cert, value.batch_cert);
3619 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003620 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003621
3622 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3623 Domain::APP,
3624 namespace_del1,
3625 &KEYSTORE_UUID,
3626 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003627 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003628 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3629 Domain::APP,
3630 namespace_del2,
3631 &KEYSTORE_UUID,
3632 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003633 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003634
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003635 // Give the garbage collector half a second to catch up.
3636 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003637
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003638 let blob_entry_row_count: u32 = db
3639 .conn
3640 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3641 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003642 // There shound be 3 blob entries left, because we deleted two of the attestation
3643 // key entries with three blobs each.
3644 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003645
Max Bires2b2e6562020-09-22 11:22:36 -07003646 Ok(())
3647 }
3648
3649 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003650 fn test_delete_all_attestation_keys() -> Result<()> {
3651 let mut db = new_test_db()?;
3652 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3653 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
3654 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3655 let result = db.delete_all_attestation_keys()?;
3656
3657 // Give the garbage collector half a second to catch up.
3658 std::thread::sleep(Duration::from_millis(500));
3659
3660 // Attestation keys should be deleted, and the regular key should remain.
3661 assert_eq!(result, 2);
3662
3663 Ok(())
3664 }
3665
3666 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003667 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003668 fn extractor(
3669 ke: &KeyEntryRow,
3670 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3671 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003672 }
3673
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003674 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003675 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3676 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003677 let entries = get_keyentry(&db)?;
3678 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003679 assert_eq!(
3680 extractor(&entries[0]),
3681 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3682 );
3683 assert_eq!(
3684 extractor(&entries[1]),
3685 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3686 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003687
3688 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003689 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003690 let entries = get_keyentry(&db)?;
3691 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003692 assert_eq!(
3693 extractor(&entries[0]),
3694 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3695 );
3696 assert_eq!(
3697 extractor(&entries[1]),
3698 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3699 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003700
3701 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003702 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003703 let entries = get_keyentry(&db)?;
3704 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003705 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3706 assert_eq!(
3707 extractor(&entries[1]),
3708 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3709 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003710
3711 // Test that we must pass in a valid Domain.
3712 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003713 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003714 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003715 );
3716 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003717 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003718 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003719 );
3720 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003721 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003722 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003723 );
3724
3725 // Test that we correctly handle setting an alias for something that does not exist.
3726 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003727 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003728 "Expected to update a single entry but instead updated 0",
3729 );
3730 // Test that we correctly abort the transaction in this case.
3731 let entries = get_keyentry(&db)?;
3732 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003733 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3734 assert_eq!(
3735 extractor(&entries[1]),
3736 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3737 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003738
3739 Ok(())
3740 }
3741
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003742 #[test]
3743 fn test_grant_ungrant() -> Result<()> {
3744 const CALLER_UID: u32 = 15;
3745 const GRANTEE_UID: u32 = 12;
3746 const SELINUX_NAMESPACE: i64 = 7;
3747
3748 let mut db = new_test_db()?;
3749 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003750 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3751 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3752 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003753 )?;
3754 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003755 domain: super::Domain::APP,
3756 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003757 alias: Some("key".to_string()),
3758 blob: None,
3759 };
3760 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3761 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3762
3763 // Reset totally predictable random number generator in case we
3764 // are not the first test running on this thread.
3765 reset_random();
3766 let next_random = 0i64;
3767
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003768 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003769 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003770 assert_eq!(*a, PVEC1);
3771 assert_eq!(
3772 *k,
3773 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003774 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003776 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003777 alias: Some("key".to_string()),
3778 blob: None,
3779 }
3780 );
3781 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003782 })
3783 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003784
3785 assert_eq!(
3786 app_granted_key,
3787 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003788 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003789 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003790 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003791 alias: None,
3792 blob: None,
3793 }
3794 );
3795
3796 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003797 domain: super::Domain::SELINUX,
3798 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003799 alias: Some("yek".to_string()),
3800 blob: None,
3801 };
3802
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003803 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003804 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003805 assert_eq!(*a, PVEC1);
3806 assert_eq!(
3807 *k,
3808 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003809 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003810 // namespace must be the supplied SELinux
3811 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003812 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003813 alias: Some("yek".to_string()),
3814 blob: None,
3815 }
3816 );
3817 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003818 })
3819 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003820
3821 assert_eq!(
3822 selinux_granted_key,
3823 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003824 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003825 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003826 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003827 alias: None,
3828 blob: None,
3829 }
3830 );
3831
3832 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003833 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003834 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003835 assert_eq!(*a, PVEC2);
3836 assert_eq!(
3837 *k,
3838 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003839 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003840 // namespace must be the supplied SELinux
3841 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003842 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003843 alias: Some("yek".to_string()),
3844 blob: None,
3845 }
3846 );
3847 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003848 })
3849 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003850
3851 assert_eq!(
3852 selinux_granted_key,
3853 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003854 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003855 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003856 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003857 alias: None,
3858 blob: None,
3859 }
3860 );
3861
3862 {
3863 // Limiting scope of stmt, because it borrows db.
3864 let mut stmt = db
3865 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003866 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003867 let mut rows =
3868 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3869 Ok((
3870 row.get(0)?,
3871 row.get(1)?,
3872 row.get(2)?,
3873 KeyPermSet::from(row.get::<_, i32>(3)?),
3874 ))
3875 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003876
3877 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003878 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003879 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003880 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003881 assert!(rows.next().is_none());
3882 }
3883
3884 debug_dump_keyentry_table(&mut db)?;
3885 println!("app_key {:?}", app_key);
3886 println!("selinux_key {:?}", selinux_key);
3887
Janis Danisevskis66784c42021-01-27 08:40:25 -08003888 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3889 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003890
3891 Ok(())
3892 }
3893
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003894 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003895 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3896 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3897
3898 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003899 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003900 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003901 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003902 let mut blob_metadata = BlobMetaData::new();
3903 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3904 db.set_blob(
3905 &key_id,
3906 SubComponentType::KEY_BLOB,
3907 Some(TEST_KEY_BLOB),
3908 Some(&blob_metadata),
3909 )?;
3910 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3911 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003912 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003913
3914 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003915 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003916 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003917 )?;
3918 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003919 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3920 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003921 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003922 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003923 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003924 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003925 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003926 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003927 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003928
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003929 drop(rows);
3930 drop(stmt);
3931
3932 assert_eq!(
3933 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3934 BlobMetaData::load_from_db(id, tx).no_gc()
3935 })
3936 .expect("Should find blob metadata."),
3937 blob_metadata
3938 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003939 Ok(())
3940 }
3941
3942 static TEST_ALIAS: &str = "my super duper key";
3943
3944 #[test]
3945 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3946 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003947 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003948 .context("test_insert_and_load_full_keyentry_domain_app")?
3949 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003950 let (_key_guard, key_entry) = db
3951 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003952 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003953 domain: Domain::APP,
3954 nspace: 0,
3955 alias: Some(TEST_ALIAS.to_string()),
3956 blob: None,
3957 },
3958 KeyType::Client,
3959 KeyEntryLoadBits::BOTH,
3960 1,
3961 |_k, _av| Ok(()),
3962 )
3963 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003964 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003965
3966 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003967 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003968 domain: Domain::APP,
3969 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003970 alias: Some(TEST_ALIAS.to_string()),
3971 blob: None,
3972 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003973 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003974 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003975 |_, _| Ok(()),
3976 )
3977 .unwrap();
3978
3979 assert_eq!(
3980 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3981 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003982 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003983 domain: Domain::APP,
3984 nspace: 0,
3985 alias: Some(TEST_ALIAS.to_string()),
3986 blob: None,
3987 },
3988 KeyType::Client,
3989 KeyEntryLoadBits::NONE,
3990 1,
3991 |_k, _av| Ok(()),
3992 )
3993 .unwrap_err()
3994 .root_cause()
3995 .downcast_ref::<KsError>()
3996 );
3997
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003998 Ok(())
3999 }
4000
4001 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004002 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4003 let mut db = new_test_db()?;
4004
4005 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004006 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004007 domain: Domain::APP,
4008 nspace: 1,
4009 alias: Some(TEST_ALIAS.to_string()),
4010 blob: None,
4011 },
4012 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004013 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004014 )
4015 .expect("Trying to insert cert.");
4016
4017 let (_key_guard, mut key_entry) = db
4018 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004019 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004020 domain: Domain::APP,
4021 nspace: 1,
4022 alias: Some(TEST_ALIAS.to_string()),
4023 blob: None,
4024 },
4025 KeyType::Client,
4026 KeyEntryLoadBits::PUBLIC,
4027 1,
4028 |_k, _av| Ok(()),
4029 )
4030 .expect("Trying to read certificate entry.");
4031
4032 assert!(key_entry.pure_cert());
4033 assert!(key_entry.cert().is_none());
4034 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4035
4036 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004037 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004038 domain: Domain::APP,
4039 nspace: 1,
4040 alias: Some(TEST_ALIAS.to_string()),
4041 blob: None,
4042 },
4043 KeyType::Client,
4044 1,
4045 |_, _| Ok(()),
4046 )
4047 .unwrap();
4048
4049 assert_eq!(
4050 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4051 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004052 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004053 domain: Domain::APP,
4054 nspace: 1,
4055 alias: Some(TEST_ALIAS.to_string()),
4056 blob: None,
4057 },
4058 KeyType::Client,
4059 KeyEntryLoadBits::NONE,
4060 1,
4061 |_k, _av| Ok(()),
4062 )
4063 .unwrap_err()
4064 .root_cause()
4065 .downcast_ref::<KsError>()
4066 );
4067
4068 Ok(())
4069 }
4070
4071 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004072 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4073 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004074 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004075 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4076 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004077 let (_key_guard, key_entry) = db
4078 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004079 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004080 domain: Domain::SELINUX,
4081 nspace: 1,
4082 alias: Some(TEST_ALIAS.to_string()),
4083 blob: None,
4084 },
4085 KeyType::Client,
4086 KeyEntryLoadBits::BOTH,
4087 1,
4088 |_k, _av| Ok(()),
4089 )
4090 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004091 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004092
4093 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004094 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004095 domain: Domain::SELINUX,
4096 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004097 alias: Some(TEST_ALIAS.to_string()),
4098 blob: None,
4099 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004100 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004101 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004102 |_, _| Ok(()),
4103 )
4104 .unwrap();
4105
4106 assert_eq!(
4107 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4108 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004109 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004110 domain: Domain::SELINUX,
4111 nspace: 1,
4112 alias: Some(TEST_ALIAS.to_string()),
4113 blob: None,
4114 },
4115 KeyType::Client,
4116 KeyEntryLoadBits::NONE,
4117 1,
4118 |_k, _av| Ok(()),
4119 )
4120 .unwrap_err()
4121 .root_cause()
4122 .downcast_ref::<KsError>()
4123 );
4124
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004125 Ok(())
4126 }
4127
4128 #[test]
4129 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4130 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004131 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004132 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4133 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004134 let (_, key_entry) = db
4135 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004136 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004137 KeyType::Client,
4138 KeyEntryLoadBits::BOTH,
4139 1,
4140 |_k, _av| Ok(()),
4141 )
4142 .unwrap();
4143
Qi Wub9433b52020-12-01 14:52:46 +08004144 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004145
4146 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004147 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004148 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004149 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004150 |_, _| Ok(()),
4151 )
4152 .unwrap();
4153
4154 assert_eq!(
4155 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4156 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004157 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004158 KeyType::Client,
4159 KeyEntryLoadBits::NONE,
4160 1,
4161 |_k, _av| Ok(()),
4162 )
4163 .unwrap_err()
4164 .root_cause()
4165 .downcast_ref::<KsError>()
4166 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004167
4168 Ok(())
4169 }
4170
4171 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004172 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4173 let mut db = new_test_db()?;
4174 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4175 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4176 .0;
4177 // Update the usage count of the limited use key.
4178 db.check_and_update_key_usage_count(key_id)?;
4179
4180 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004181 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004182 KeyType::Client,
4183 KeyEntryLoadBits::BOTH,
4184 1,
4185 |_k, _av| Ok(()),
4186 )?;
4187
4188 // The usage count is decremented now.
4189 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4190
4191 Ok(())
4192 }
4193
4194 #[test]
4195 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4196 let mut db = new_test_db()?;
4197 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4198 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4199 .0;
4200 // Update the usage count of the limited use key.
4201 db.check_and_update_key_usage_count(key_id).expect(concat!(
4202 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4203 "This should succeed."
4204 ));
4205
4206 // Try to update the exhausted limited use key.
4207 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4208 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4209 "This should fail."
4210 ));
4211 assert_eq!(
4212 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4213 e.root_cause().downcast_ref::<KsError>().unwrap()
4214 );
4215
4216 Ok(())
4217 }
4218
4219 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004220 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4221 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004222 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004223 .context("test_insert_and_load_full_keyentry_from_grant")?
4224 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004225
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004226 let granted_key = db
4227 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004228 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004229 domain: Domain::APP,
4230 nspace: 0,
4231 alias: Some(TEST_ALIAS.to_string()),
4232 blob: None,
4233 },
4234 1,
4235 2,
4236 key_perm_set![KeyPerm::use_()],
4237 |_k, _av| Ok(()),
4238 )
4239 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004240
4241 debug_dump_grant_table(&mut db)?;
4242
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004243 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004244 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4245 assert_eq!(Domain::GRANT, k.domain);
4246 assert!(av.unwrap().includes(KeyPerm::use_()));
4247 Ok(())
4248 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004249 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004250
Qi Wub9433b52020-12-01 14:52:46 +08004251 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004252
Janis Danisevskis66784c42021-01-27 08:40:25 -08004253 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004254
4255 assert_eq!(
4256 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4257 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004258 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004259 KeyType::Client,
4260 KeyEntryLoadBits::NONE,
4261 2,
4262 |_k, _av| Ok(()),
4263 )
4264 .unwrap_err()
4265 .root_cause()
4266 .downcast_ref::<KsError>()
4267 );
4268
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004269 Ok(())
4270 }
4271
Janis Danisevskis45760022021-01-19 16:34:10 -08004272 // This test attempts to load a key by key id while the caller is not the owner
4273 // but a grant exists for the given key and the caller.
4274 #[test]
4275 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4276 let mut db = new_test_db()?;
4277 const OWNER_UID: u32 = 1u32;
4278 const GRANTEE_UID: u32 = 2u32;
4279 const SOMEONE_ELSE_UID: u32 = 3u32;
4280 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4281 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4282 .0;
4283
4284 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004285 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004286 domain: Domain::APP,
4287 nspace: 0,
4288 alias: Some(TEST_ALIAS.to_string()),
4289 blob: None,
4290 },
4291 OWNER_UID,
4292 GRANTEE_UID,
4293 key_perm_set![KeyPerm::use_()],
4294 |_k, _av| Ok(()),
4295 )
4296 .unwrap();
4297
4298 debug_dump_grant_table(&mut db)?;
4299
4300 let id_descriptor =
4301 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4302
4303 let (_, key_entry) = db
4304 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004305 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004306 KeyType::Client,
4307 KeyEntryLoadBits::BOTH,
4308 GRANTEE_UID,
4309 |k, av| {
4310 assert_eq!(Domain::APP, k.domain);
4311 assert_eq!(OWNER_UID as i64, k.nspace);
4312 assert!(av.unwrap().includes(KeyPerm::use_()));
4313 Ok(())
4314 },
4315 )
4316 .unwrap();
4317
4318 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4319
4320 let (_, key_entry) = db
4321 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004322 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004323 KeyType::Client,
4324 KeyEntryLoadBits::BOTH,
4325 SOMEONE_ELSE_UID,
4326 |k, av| {
4327 assert_eq!(Domain::APP, k.domain);
4328 assert_eq!(OWNER_UID as i64, k.nspace);
4329 assert!(av.is_none());
4330 Ok(())
4331 },
4332 )
4333 .unwrap();
4334
4335 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4336
Janis Danisevskis66784c42021-01-27 08:40:25 -08004337 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004338
4339 assert_eq!(
4340 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4341 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004342 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004343 KeyType::Client,
4344 KeyEntryLoadBits::NONE,
4345 GRANTEE_UID,
4346 |_k, _av| Ok(()),
4347 )
4348 .unwrap_err()
4349 .root_cause()
4350 .downcast_ref::<KsError>()
4351 );
4352
4353 Ok(())
4354 }
4355
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004356 // Creates a key migrates it to a different location and then tries to access it by the old
4357 // and new location.
4358 #[test]
4359 fn test_migrate_key_app_to_app() -> Result<()> {
4360 let mut db = new_test_db()?;
4361 const SOURCE_UID: u32 = 1u32;
4362 const DESTINATION_UID: u32 = 2u32;
4363 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4364 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4365 let key_id_guard =
4366 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4367 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4368
4369 let source_descriptor: KeyDescriptor = KeyDescriptor {
4370 domain: Domain::APP,
4371 nspace: -1,
4372 alias: Some(SOURCE_ALIAS.to_string()),
4373 blob: None,
4374 };
4375
4376 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4377 domain: Domain::APP,
4378 nspace: -1,
4379 alias: Some(DESTINATION_ALIAS.to_string()),
4380 blob: None,
4381 };
4382
4383 let key_id = key_id_guard.id();
4384
4385 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4386 Ok(())
4387 })
4388 .unwrap();
4389
4390 let (_, key_entry) = db
4391 .load_key_entry(
4392 &destination_descriptor,
4393 KeyType::Client,
4394 KeyEntryLoadBits::BOTH,
4395 DESTINATION_UID,
4396 |k, av| {
4397 assert_eq!(Domain::APP, k.domain);
4398 assert_eq!(DESTINATION_UID as i64, k.nspace);
4399 assert!(av.is_none());
4400 Ok(())
4401 },
4402 )
4403 .unwrap();
4404
4405 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4406
4407 assert_eq!(
4408 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4409 db.load_key_entry(
4410 &source_descriptor,
4411 KeyType::Client,
4412 KeyEntryLoadBits::NONE,
4413 SOURCE_UID,
4414 |_k, _av| Ok(()),
4415 )
4416 .unwrap_err()
4417 .root_cause()
4418 .downcast_ref::<KsError>()
4419 );
4420
4421 Ok(())
4422 }
4423
4424 // Creates a key migrates it to a different location and then tries to access it by the old
4425 // and new location.
4426 #[test]
4427 fn test_migrate_key_app_to_selinux() -> Result<()> {
4428 let mut db = new_test_db()?;
4429 const SOURCE_UID: u32 = 1u32;
4430 const DESTINATION_UID: u32 = 2u32;
4431 const DESTINATION_NAMESPACE: i64 = 1000i64;
4432 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4433 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4434 let key_id_guard =
4435 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4436 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4437
4438 let source_descriptor: KeyDescriptor = KeyDescriptor {
4439 domain: Domain::APP,
4440 nspace: -1,
4441 alias: Some(SOURCE_ALIAS.to_string()),
4442 blob: None,
4443 };
4444
4445 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4446 domain: Domain::SELINUX,
4447 nspace: DESTINATION_NAMESPACE,
4448 alias: Some(DESTINATION_ALIAS.to_string()),
4449 blob: None,
4450 };
4451
4452 let key_id = key_id_guard.id();
4453
4454 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4455 Ok(())
4456 })
4457 .unwrap();
4458
4459 let (_, key_entry) = db
4460 .load_key_entry(
4461 &destination_descriptor,
4462 KeyType::Client,
4463 KeyEntryLoadBits::BOTH,
4464 DESTINATION_UID,
4465 |k, av| {
4466 assert_eq!(Domain::SELINUX, k.domain);
4467 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4468 assert!(av.is_none());
4469 Ok(())
4470 },
4471 )
4472 .unwrap();
4473
4474 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4475
4476 assert_eq!(
4477 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4478 db.load_key_entry(
4479 &source_descriptor,
4480 KeyType::Client,
4481 KeyEntryLoadBits::NONE,
4482 SOURCE_UID,
4483 |_k, _av| Ok(()),
4484 )
4485 .unwrap_err()
4486 .root_cause()
4487 .downcast_ref::<KsError>()
4488 );
4489
4490 Ok(())
4491 }
4492
4493 // Creates two keys and tries to migrate the first to the location of the second which
4494 // is expected to fail.
4495 #[test]
4496 fn test_migrate_key_destination_occupied() -> Result<()> {
4497 let mut db = new_test_db()?;
4498 const SOURCE_UID: u32 = 1u32;
4499 const DESTINATION_UID: u32 = 2u32;
4500 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4501 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4502 let key_id_guard =
4503 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4504 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4505 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4506 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4507
4508 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4509 domain: Domain::APP,
4510 nspace: -1,
4511 alias: Some(DESTINATION_ALIAS.to_string()),
4512 blob: None,
4513 };
4514
4515 assert_eq!(
4516 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4517 db.migrate_key_namespace(
4518 key_id_guard,
4519 &destination_descriptor,
4520 DESTINATION_UID,
4521 |_k| Ok(())
4522 )
4523 .unwrap_err()
4524 .root_cause()
4525 .downcast_ref::<KsError>()
4526 );
4527
4528 Ok(())
4529 }
4530
Janis Danisevskisaec14592020-11-12 09:41:49 -08004531 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4532
Janis Danisevskisaec14592020-11-12 09:41:49 -08004533 #[test]
4534 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4535 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004536 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4537 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004538 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004539 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004540 .context("test_insert_and_load_full_keyentry_domain_app")?
4541 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004542 let (_key_guard, key_entry) = db
4543 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004544 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004545 domain: Domain::APP,
4546 nspace: 0,
4547 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4548 blob: None,
4549 },
4550 KeyType::Client,
4551 KeyEntryLoadBits::BOTH,
4552 33,
4553 |_k, _av| Ok(()),
4554 )
4555 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004556 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004557 let state = Arc::new(AtomicU8::new(1));
4558 let state2 = state.clone();
4559
4560 // Spawning a second thread that attempts to acquire the key id lock
4561 // for the same key as the primary thread. The primary thread then
4562 // waits, thereby forcing the secondary thread into the second stage
4563 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4564 // The test succeeds if the secondary thread observes the transition
4565 // of `state` from 1 to 2, despite having a whole second to overtake
4566 // the primary thread.
4567 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004568 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004569 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004570 assert!(db
4571 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004572 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004573 domain: Domain::APP,
4574 nspace: 0,
4575 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4576 blob: None,
4577 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004578 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004579 KeyEntryLoadBits::BOTH,
4580 33,
4581 |_k, _av| Ok(()),
4582 )
4583 .is_ok());
4584 // We should only see a 2 here because we can only return
4585 // from load_key_entry when the `_key_guard` expires,
4586 // which happens at the end of the scope.
4587 assert_eq!(2, state2.load(Ordering::Relaxed));
4588 });
4589
4590 thread::sleep(std::time::Duration::from_millis(1000));
4591
4592 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4593
4594 // Return the handle from this scope so we can join with the
4595 // secondary thread after the key id lock has expired.
4596 handle
4597 // This is where the `_key_guard` goes out of scope,
4598 // which is the reason for concurrent load_key_entry on the same key
4599 // to unblock.
4600 };
4601 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4602 // main test thread. We will not see failing asserts in secondary threads otherwise.
4603 handle.join().unwrap();
4604 Ok(())
4605 }
4606
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004607 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004608 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004609 let temp_dir =
4610 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4611
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004612 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4613 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004614
4615 let _tx1 = db1
4616 .conn
4617 .transaction_with_behavior(TransactionBehavior::Immediate)
4618 .expect("Failed to create first transaction.");
4619
4620 let error = db2
4621 .conn
4622 .transaction_with_behavior(TransactionBehavior::Immediate)
4623 .context("Transaction begin failed.")
4624 .expect_err("This should fail.");
4625 let root_cause = error.root_cause();
4626 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4627 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4628 {
4629 return;
4630 }
4631 panic!(
4632 "Unexpected error {:?} \n{:?} \n{:?}",
4633 error,
4634 root_cause,
4635 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4636 )
4637 }
4638
4639 #[cfg(disabled)]
4640 #[test]
4641 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4642 let temp_dir = Arc::new(
4643 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4644 .expect("Failed to create temp dir."),
4645 );
4646
4647 let test_begin = Instant::now();
4648
4649 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4650 const KEY_COUNT: u32 = 500u32;
4651 const OPEN_DB_COUNT: u32 = 50u32;
4652
4653 let mut actual_key_count = KEY_COUNT;
4654 // First insert KEY_COUNT keys.
4655 for count in 0..KEY_COUNT {
4656 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4657 actual_key_count = count;
4658 break;
4659 }
4660 let alias = format!("test_alias_{}", count);
4661 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4662 .expect("Failed to make key entry.");
4663 }
4664
4665 // Insert more keys from a different thread and into a different namespace.
4666 let temp_dir1 = temp_dir.clone();
4667 let handle1 = thread::spawn(move || {
4668 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4669
4670 for count in 0..actual_key_count {
4671 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4672 return;
4673 }
4674 let alias = format!("test_alias_{}", count);
4675 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4676 .expect("Failed to make key entry.");
4677 }
4678
4679 // then unbind them again.
4680 for count in 0..actual_key_count {
4681 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4682 return;
4683 }
4684 let key = KeyDescriptor {
4685 domain: Domain::APP,
4686 nspace: -1,
4687 alias: Some(format!("test_alias_{}", count)),
4688 blob: None,
4689 };
4690 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4691 }
4692 });
4693
4694 // And start unbinding the first set of keys.
4695 let temp_dir2 = temp_dir.clone();
4696 let handle2 = thread::spawn(move || {
4697 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4698
4699 for count in 0..actual_key_count {
4700 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4701 return;
4702 }
4703 let key = KeyDescriptor {
4704 domain: Domain::APP,
4705 nspace: -1,
4706 alias: Some(format!("test_alias_{}", count)),
4707 blob: None,
4708 };
4709 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4710 }
4711 });
4712
4713 let stop_deleting = Arc::new(AtomicU8::new(0));
4714 let stop_deleting2 = stop_deleting.clone();
4715
4716 // And delete anything that is unreferenced keys.
4717 let temp_dir3 = temp_dir.clone();
4718 let handle3 = thread::spawn(move || {
4719 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4720
4721 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4722 while let Some((key_guard, _key)) =
4723 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4724 {
4725 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4726 return;
4727 }
4728 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4729 }
4730 std::thread::sleep(std::time::Duration::from_millis(100));
4731 }
4732 });
4733
4734 // While a lot of inserting and deleting is going on we have to open database connections
4735 // successfully and use them.
4736 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4737 // out of scope.
4738 #[allow(clippy::redundant_clone)]
4739 let temp_dir4 = temp_dir.clone();
4740 let handle4 = thread::spawn(move || {
4741 for count in 0..OPEN_DB_COUNT {
4742 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4743 return;
4744 }
4745 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4746
4747 let alias = format!("test_alias_{}", count);
4748 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4749 .expect("Failed to make key entry.");
4750 let key = KeyDescriptor {
4751 domain: Domain::APP,
4752 nspace: -1,
4753 alias: Some(alias),
4754 blob: None,
4755 };
4756 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4757 }
4758 });
4759
4760 handle1.join().expect("Thread 1 panicked.");
4761 handle2.join().expect("Thread 2 panicked.");
4762 handle4.join().expect("Thread 4 panicked.");
4763
4764 stop_deleting.store(1, Ordering::Relaxed);
4765 handle3.join().expect("Thread 3 panicked.");
4766
4767 Ok(())
4768 }
4769
4770 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004771 fn list() -> Result<()> {
4772 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004773 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004774 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4775 (Domain::APP, 1, "test1"),
4776 (Domain::APP, 1, "test2"),
4777 (Domain::APP, 1, "test3"),
4778 (Domain::APP, 1, "test4"),
4779 (Domain::APP, 1, "test5"),
4780 (Domain::APP, 1, "test6"),
4781 (Domain::APP, 1, "test7"),
4782 (Domain::APP, 2, "test1"),
4783 (Domain::APP, 2, "test2"),
4784 (Domain::APP, 2, "test3"),
4785 (Domain::APP, 2, "test4"),
4786 (Domain::APP, 2, "test5"),
4787 (Domain::APP, 2, "test6"),
4788 (Domain::APP, 2, "test8"),
4789 (Domain::SELINUX, 100, "test1"),
4790 (Domain::SELINUX, 100, "test2"),
4791 (Domain::SELINUX, 100, "test3"),
4792 (Domain::SELINUX, 100, "test4"),
4793 (Domain::SELINUX, 100, "test5"),
4794 (Domain::SELINUX, 100, "test6"),
4795 (Domain::SELINUX, 100, "test9"),
4796 ];
4797
4798 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4799 .iter()
4800 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004801 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4802 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004803 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4804 });
4805 (entry.id(), *ns)
4806 })
4807 .collect();
4808
4809 for (domain, namespace) in
4810 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4811 {
4812 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4813 .iter()
4814 .filter_map(|(domain, ns, alias)| match ns {
4815 ns if *ns == *namespace => Some(KeyDescriptor {
4816 domain: *domain,
4817 nspace: *ns,
4818 alias: Some(alias.to_string()),
4819 blob: None,
4820 }),
4821 _ => None,
4822 })
4823 .collect();
4824 list_o_descriptors.sort();
4825 let mut list_result = db.list(*domain, *namespace)?;
4826 list_result.sort();
4827 assert_eq!(list_o_descriptors, list_result);
4828
4829 let mut list_o_ids: Vec<i64> = list_o_descriptors
4830 .into_iter()
4831 .map(|d| {
4832 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004833 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004834 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004835 KeyType::Client,
4836 KeyEntryLoadBits::NONE,
4837 *namespace as u32,
4838 |_, _| Ok(()),
4839 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004840 .unwrap();
4841 entry.id()
4842 })
4843 .collect();
4844 list_o_ids.sort_unstable();
4845 let mut loaded_entries: Vec<i64> = list_o_keys
4846 .iter()
4847 .filter_map(|(id, ns)| match ns {
4848 ns if *ns == *namespace => Some(*id),
4849 _ => None,
4850 })
4851 .collect();
4852 loaded_entries.sort_unstable();
4853 assert_eq!(list_o_ids, loaded_entries);
4854 }
4855 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4856
4857 Ok(())
4858 }
4859
Joel Galenson0891bc12020-07-20 10:37:03 -07004860 // Helpers
4861
4862 // Checks that the given result is an error containing the given string.
4863 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4864 let error_str = format!(
4865 "{:#?}",
4866 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4867 );
4868 assert!(
4869 error_str.contains(target),
4870 "The string \"{}\" should contain \"{}\"",
4871 error_str,
4872 target
4873 );
4874 }
4875
Joel Galenson2aab4432020-07-22 15:27:57 -07004876 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004877 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004878 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004879 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004880 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004881 namespace: Option<i64>,
4882 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004883 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004884 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004885 }
4886
4887 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4888 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004889 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004890 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004891 Ok(KeyEntryRow {
4892 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004893 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004894 domain: match row.get(2)? {
4895 Some(i) => Some(Domain(i)),
4896 None => None,
4897 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004898 namespace: row.get(3)?,
4899 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004900 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004901 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004902 })
4903 })?
4904 .map(|r| r.context("Could not read keyentry row."))
4905 .collect::<Result<Vec<_>>>()
4906 }
4907
Max Biresb2e1d032021-02-08 21:35:05 -08004908 struct RemoteProvValues {
4909 cert_chain: Vec<u8>,
4910 priv_key: Vec<u8>,
4911 batch_cert: Vec<u8>,
4912 }
4913
Max Bires2b2e6562020-09-22 11:22:36 -07004914 fn load_attestation_key_pool(
4915 db: &mut KeystoreDB,
4916 expiration_date: i64,
4917 namespace: i64,
4918 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004919 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004920 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4921 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4922 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4923 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004924 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004925 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4926 db.store_signed_attestation_certificate_chain(
4927 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004928 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004929 &cert_chain,
4930 expiration_date,
4931 &KEYSTORE_UUID,
4932 )?;
4933 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004934 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004935 }
4936
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004937 // Note: The parameters and SecurityLevel associations are nonsensical. This
4938 // collection is only used to check if the parameters are preserved as expected by the
4939 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004940 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4941 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004942 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4943 KeyParameter::new(
4944 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4945 SecurityLevel::TRUSTED_ENVIRONMENT,
4946 ),
4947 KeyParameter::new(
4948 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4949 SecurityLevel::TRUSTED_ENVIRONMENT,
4950 ),
4951 KeyParameter::new(
4952 KeyParameterValue::Algorithm(Algorithm::RSA),
4953 SecurityLevel::TRUSTED_ENVIRONMENT,
4954 ),
4955 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4956 KeyParameter::new(
4957 KeyParameterValue::BlockMode(BlockMode::ECB),
4958 SecurityLevel::TRUSTED_ENVIRONMENT,
4959 ),
4960 KeyParameter::new(
4961 KeyParameterValue::BlockMode(BlockMode::GCM),
4962 SecurityLevel::TRUSTED_ENVIRONMENT,
4963 ),
4964 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4965 KeyParameter::new(
4966 KeyParameterValue::Digest(Digest::MD5),
4967 SecurityLevel::TRUSTED_ENVIRONMENT,
4968 ),
4969 KeyParameter::new(
4970 KeyParameterValue::Digest(Digest::SHA_2_224),
4971 SecurityLevel::TRUSTED_ENVIRONMENT,
4972 ),
4973 KeyParameter::new(
4974 KeyParameterValue::Digest(Digest::SHA_2_256),
4975 SecurityLevel::STRONGBOX,
4976 ),
4977 KeyParameter::new(
4978 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4979 SecurityLevel::TRUSTED_ENVIRONMENT,
4980 ),
4981 KeyParameter::new(
4982 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4983 SecurityLevel::TRUSTED_ENVIRONMENT,
4984 ),
4985 KeyParameter::new(
4986 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4987 SecurityLevel::STRONGBOX,
4988 ),
4989 KeyParameter::new(
4990 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4991 SecurityLevel::TRUSTED_ENVIRONMENT,
4992 ),
4993 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4994 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4995 KeyParameter::new(
4996 KeyParameterValue::EcCurve(EcCurve::P_224),
4997 SecurityLevel::TRUSTED_ENVIRONMENT,
4998 ),
4999 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5000 KeyParameter::new(
5001 KeyParameterValue::EcCurve(EcCurve::P_384),
5002 SecurityLevel::TRUSTED_ENVIRONMENT,
5003 ),
5004 KeyParameter::new(
5005 KeyParameterValue::EcCurve(EcCurve::P_521),
5006 SecurityLevel::TRUSTED_ENVIRONMENT,
5007 ),
5008 KeyParameter::new(
5009 KeyParameterValue::RSAPublicExponent(3),
5010 SecurityLevel::TRUSTED_ENVIRONMENT,
5011 ),
5012 KeyParameter::new(
5013 KeyParameterValue::IncludeUniqueID,
5014 SecurityLevel::TRUSTED_ENVIRONMENT,
5015 ),
5016 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5017 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5018 KeyParameter::new(
5019 KeyParameterValue::ActiveDateTime(1234567890),
5020 SecurityLevel::STRONGBOX,
5021 ),
5022 KeyParameter::new(
5023 KeyParameterValue::OriginationExpireDateTime(1234567890),
5024 SecurityLevel::TRUSTED_ENVIRONMENT,
5025 ),
5026 KeyParameter::new(
5027 KeyParameterValue::UsageExpireDateTime(1234567890),
5028 SecurityLevel::TRUSTED_ENVIRONMENT,
5029 ),
5030 KeyParameter::new(
5031 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5032 SecurityLevel::TRUSTED_ENVIRONMENT,
5033 ),
5034 KeyParameter::new(
5035 KeyParameterValue::MaxUsesPerBoot(1234567890),
5036 SecurityLevel::TRUSTED_ENVIRONMENT,
5037 ),
5038 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5039 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5040 KeyParameter::new(
5041 KeyParameterValue::NoAuthRequired,
5042 SecurityLevel::TRUSTED_ENVIRONMENT,
5043 ),
5044 KeyParameter::new(
5045 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5046 SecurityLevel::TRUSTED_ENVIRONMENT,
5047 ),
5048 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5049 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5050 KeyParameter::new(
5051 KeyParameterValue::TrustedUserPresenceRequired,
5052 SecurityLevel::TRUSTED_ENVIRONMENT,
5053 ),
5054 KeyParameter::new(
5055 KeyParameterValue::TrustedConfirmationRequired,
5056 SecurityLevel::TRUSTED_ENVIRONMENT,
5057 ),
5058 KeyParameter::new(
5059 KeyParameterValue::UnlockedDeviceRequired,
5060 SecurityLevel::TRUSTED_ENVIRONMENT,
5061 ),
5062 KeyParameter::new(
5063 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5064 SecurityLevel::SOFTWARE,
5065 ),
5066 KeyParameter::new(
5067 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5068 SecurityLevel::SOFTWARE,
5069 ),
5070 KeyParameter::new(
5071 KeyParameterValue::CreationDateTime(12345677890),
5072 SecurityLevel::SOFTWARE,
5073 ),
5074 KeyParameter::new(
5075 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5076 SecurityLevel::TRUSTED_ENVIRONMENT,
5077 ),
5078 KeyParameter::new(
5079 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5080 SecurityLevel::TRUSTED_ENVIRONMENT,
5081 ),
5082 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5083 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5084 KeyParameter::new(
5085 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5086 SecurityLevel::SOFTWARE,
5087 ),
5088 KeyParameter::new(
5089 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5090 SecurityLevel::TRUSTED_ENVIRONMENT,
5091 ),
5092 KeyParameter::new(
5093 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5094 SecurityLevel::TRUSTED_ENVIRONMENT,
5095 ),
5096 KeyParameter::new(
5097 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5098 SecurityLevel::TRUSTED_ENVIRONMENT,
5099 ),
5100 KeyParameter::new(
5101 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5102 SecurityLevel::TRUSTED_ENVIRONMENT,
5103 ),
5104 KeyParameter::new(
5105 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5106 SecurityLevel::TRUSTED_ENVIRONMENT,
5107 ),
5108 KeyParameter::new(
5109 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5110 SecurityLevel::TRUSTED_ENVIRONMENT,
5111 ),
5112 KeyParameter::new(
5113 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5114 SecurityLevel::TRUSTED_ENVIRONMENT,
5115 ),
5116 KeyParameter::new(
5117 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5118 SecurityLevel::TRUSTED_ENVIRONMENT,
5119 ),
5120 KeyParameter::new(
5121 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5122 SecurityLevel::TRUSTED_ENVIRONMENT,
5123 ),
5124 KeyParameter::new(
5125 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5126 SecurityLevel::TRUSTED_ENVIRONMENT,
5127 ),
5128 KeyParameter::new(
5129 KeyParameterValue::VendorPatchLevel(3),
5130 SecurityLevel::TRUSTED_ENVIRONMENT,
5131 ),
5132 KeyParameter::new(
5133 KeyParameterValue::BootPatchLevel(4),
5134 SecurityLevel::TRUSTED_ENVIRONMENT,
5135 ),
5136 KeyParameter::new(
5137 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5138 SecurityLevel::TRUSTED_ENVIRONMENT,
5139 ),
5140 KeyParameter::new(
5141 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5142 SecurityLevel::TRUSTED_ENVIRONMENT,
5143 ),
5144 KeyParameter::new(
5145 KeyParameterValue::MacLength(256),
5146 SecurityLevel::TRUSTED_ENVIRONMENT,
5147 ),
5148 KeyParameter::new(
5149 KeyParameterValue::ResetSinceIdRotation,
5150 SecurityLevel::TRUSTED_ENVIRONMENT,
5151 ),
5152 KeyParameter::new(
5153 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5154 SecurityLevel::TRUSTED_ENVIRONMENT,
5155 ),
Qi Wub9433b52020-12-01 14:52:46 +08005156 ];
5157 if let Some(value) = max_usage_count {
5158 params.push(KeyParameter::new(
5159 KeyParameterValue::UsageCountLimit(value),
5160 SecurityLevel::SOFTWARE,
5161 ));
5162 }
5163 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005164 }
5165
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005166 fn make_test_key_entry(
5167 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005168 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005169 namespace: i64,
5170 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005171 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005172 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08005173 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005174 let mut blob_metadata = BlobMetaData::new();
5175 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5176 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5177 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5178 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5179 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5180
5181 db.set_blob(
5182 &key_id,
5183 SubComponentType::KEY_BLOB,
5184 Some(TEST_KEY_BLOB),
5185 Some(&blob_metadata),
5186 )?;
5187 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5188 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005189
5190 let params = make_test_params(max_usage_count);
5191 db.insert_keyparameter(&key_id, &params)?;
5192
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005193 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005194 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005195 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005196 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005197 Ok(key_id)
5198 }
5199
Qi Wub9433b52020-12-01 14:52:46 +08005200 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5201 let params = make_test_params(max_usage_count);
5202
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005203 let mut blob_metadata = BlobMetaData::new();
5204 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5205 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5206 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5207 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5208 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5209
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005210 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005211 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005212
5213 KeyEntry {
5214 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005215 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005216 cert: Some(TEST_CERT_BLOB.to_vec()),
5217 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005218 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005219 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005220 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005221 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005222 }
5223 }
5224
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005225 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005226 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005227 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005228 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005229 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005230 NO_PARAMS,
5231 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005232 Ok((
5233 row.get(0)?,
5234 row.get(1)?,
5235 row.get(2)?,
5236 row.get(3)?,
5237 row.get(4)?,
5238 row.get(5)?,
5239 row.get(6)?,
5240 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005241 },
5242 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005243
5244 println!("Key entry table rows:");
5245 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005246 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005247 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005248 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5249 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005250 );
5251 }
5252 Ok(())
5253 }
5254
5255 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005256 let mut stmt = db
5257 .conn
5258 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005259 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5260 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5261 })?;
5262
5263 println!("Grant table rows:");
5264 for r in rows {
5265 let (id, gt, ki, av) = r.unwrap();
5266 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5267 }
5268 Ok(())
5269 }
5270
Joel Galenson0891bc12020-07-20 10:37:03 -07005271 // Use a custom random number generator that repeats each number once.
5272 // This allows us to test repeated elements.
5273
5274 thread_local! {
5275 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5276 }
5277
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005278 fn reset_random() {
5279 RANDOM_COUNTER.with(|counter| {
5280 *counter.borrow_mut() = 0;
5281 })
5282 }
5283
Joel Galenson0891bc12020-07-20 10:37:03 -07005284 pub fn random() -> i64 {
5285 RANDOM_COUNTER.with(|counter| {
5286 let result = *counter.borrow() / 2;
5287 *counter.borrow_mut() += 1;
5288 result
5289 })
5290 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005291
5292 #[test]
5293 fn test_last_off_body() -> Result<()> {
5294 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08005295 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005296 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5297 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
5298 tx.commit()?;
5299 let one_second = Duration::from_secs(1);
5300 thread::sleep(one_second);
5301 db.update_last_off_body(MonotonicRawTime::now())?;
5302 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
5303 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
5304 tx2.commit()?;
5305 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
5306 Ok(())
5307 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005308
5309 #[test]
5310 fn test_unbind_keys_for_user() -> Result<()> {
5311 let mut db = new_test_db()?;
5312 db.unbind_keys_for_user(1, false)?;
5313
5314 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5315 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5316 db.unbind_keys_for_user(2, false)?;
5317
5318 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
5319 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
5320
5321 db.unbind_keys_for_user(1, true)?;
5322 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
5323
5324 Ok(())
5325 }
5326
5327 #[test]
5328 fn test_store_super_key() -> Result<()> {
5329 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005330 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005331 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005332 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005333 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005334 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005335
5336 let (encrypted_super_key, metadata) =
5337 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005338 db.store_super_key(
5339 1,
5340 &USER_SUPER_KEY,
5341 &encrypted_super_key,
5342 &metadata,
5343 &KeyMetaData::new(),
5344 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005345
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005346 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005347 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005348
Paul Crowley7a658392021-03-18 17:08:20 -07005349 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005350 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5351 USER_SUPER_KEY.algorithm,
5352 key_entry,
5353 &pw,
5354 None,
5355 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005356
Paul Crowley7a658392021-03-18 17:08:20 -07005357 let decrypted_secret_bytes =
5358 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5359 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005360 Ok(())
5361 }
Seth Moore78c091f2021-04-09 21:38:30 +00005362
5363 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5364 vec![
5365 StatsdStorageType::KeyEntry,
5366 StatsdStorageType::KeyEntryIdIndex,
5367 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5368 StatsdStorageType::BlobEntry,
5369 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5370 StatsdStorageType::KeyParameter,
5371 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5372 StatsdStorageType::KeyMetadata,
5373 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5374 StatsdStorageType::Grant,
5375 StatsdStorageType::AuthToken,
5376 StatsdStorageType::BlobMetadata,
5377 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5378 ]
5379 }
5380
5381 /// Perform a simple check to ensure that we can query all the storage types
5382 /// that are supported by the DB. Check for reasonable values.
5383 #[test]
5384 fn test_query_all_valid_table_sizes() -> Result<()> {
5385 const PAGE_SIZE: i64 = 4096;
5386
5387 let mut db = new_test_db()?;
5388
5389 for t in get_valid_statsd_storage_types() {
5390 let stat = db.get_storage_stat(t)?;
5391 assert!(stat.size >= PAGE_SIZE);
5392 assert!(stat.size >= stat.unused_size);
5393 }
5394
5395 Ok(())
5396 }
5397
5398 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5399 get_valid_statsd_storage_types()
5400 .into_iter()
5401 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5402 .collect()
5403 }
5404
5405 fn assert_storage_increased(
5406 db: &mut KeystoreDB,
5407 increased_storage_types: Vec<StatsdStorageType>,
5408 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5409 ) {
5410 for storage in increased_storage_types {
5411 // Verify the expected storage increased.
5412 let new = db.get_storage_stat(storage).unwrap();
5413 let storage = storage as i32;
5414 let old = &baseline[&storage];
5415 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5416 assert!(
5417 new.unused_size <= old.unused_size,
5418 "{}: {} <= {}",
5419 storage,
5420 new.unused_size,
5421 old.unused_size
5422 );
5423
5424 // Update the baseline with the new value so that it succeeds in the
5425 // later comparison.
5426 baseline.insert(storage, new);
5427 }
5428
5429 // Get an updated map of the storage and verify there were no unexpected changes.
5430 let updated_stats = get_storage_stats_map(db);
5431 assert_eq!(updated_stats.len(), baseline.len());
5432
5433 for &k in baseline.keys() {
5434 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5435 let mut s = String::new();
5436 for &k in map.keys() {
5437 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5438 .expect("string concat failed");
5439 }
5440 s
5441 };
5442
5443 assert!(
5444 updated_stats[&k].size == baseline[&k].size
5445 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5446 "updated_stats:\n{}\nbaseline:\n{}",
5447 stringify(&updated_stats),
5448 stringify(&baseline)
5449 );
5450 }
5451 }
5452
5453 #[test]
5454 fn test_verify_key_table_size_reporting() -> Result<()> {
5455 let mut db = new_test_db()?;
5456 let mut working_stats = get_storage_stats_map(&mut db);
5457
5458 let key_id = db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
5459 assert_storage_increased(
5460 &mut db,
5461 vec![
5462 StatsdStorageType::KeyEntry,
5463 StatsdStorageType::KeyEntryIdIndex,
5464 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5465 ],
5466 &mut working_stats,
5467 );
5468
5469 let mut blob_metadata = BlobMetaData::new();
5470 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5471 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5472 assert_storage_increased(
5473 &mut db,
5474 vec![
5475 StatsdStorageType::BlobEntry,
5476 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5477 StatsdStorageType::BlobMetadata,
5478 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5479 ],
5480 &mut working_stats,
5481 );
5482
5483 let params = make_test_params(None);
5484 db.insert_keyparameter(&key_id, &params)?;
5485 assert_storage_increased(
5486 &mut db,
5487 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5488 &mut working_stats,
5489 );
5490
5491 let mut metadata = KeyMetaData::new();
5492 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5493 db.insert_key_metadata(&key_id, &metadata)?;
5494 assert_storage_increased(
5495 &mut db,
5496 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5497 &mut working_stats,
5498 );
5499
5500 let mut sum = 0;
5501 for stat in working_stats.values() {
5502 sum += stat.size;
5503 }
5504 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5505 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5506
5507 Ok(())
5508 }
5509
5510 #[test]
5511 fn test_verify_auth_table_size_reporting() -> Result<()> {
5512 let mut db = new_test_db()?;
5513 let mut working_stats = get_storage_stats_map(&mut db);
5514 db.insert_auth_token(&HardwareAuthToken {
5515 challenge: 123,
5516 userId: 456,
5517 authenticatorId: 789,
5518 authenticatorType: kmhw_authenticator_type::ANY,
5519 timestamp: Timestamp { milliSeconds: 10 },
5520 mac: b"mac".to_vec(),
5521 })?;
5522 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5523 Ok(())
5524 }
5525
5526 #[test]
5527 fn test_verify_grant_table_size_reporting() -> Result<()> {
5528 const OWNER: i64 = 1;
5529 let mut db = new_test_db()?;
5530 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5531
5532 let mut working_stats = get_storage_stats_map(&mut db);
5533 db.grant(
5534 &KeyDescriptor {
5535 domain: Domain::APP,
5536 nspace: 0,
5537 alias: Some(TEST_ALIAS.to_string()),
5538 blob: None,
5539 },
5540 OWNER as u32,
5541 123,
5542 key_perm_set![KeyPerm::use_()],
5543 |_, _| Ok(()),
5544 )?;
5545
5546 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5547
5548 Ok(())
5549 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005550}