blob: 65ee7ae107792af164fe6961fc5074999657276b [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
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
Janis Danisevskis030ba022021-05-26 11:15:30 -070045pub(crate) mod utils;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -070046mod versioning;
Matthew Maurerd7815ca2021-05-06 21:58:45 -070047
Janis Danisevskis11bd2592022-01-04 19:59:26 -080048use crate::gc::Gc;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080050use crate::key_parameter::{KeyParameter, Tag};
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000051use crate::metrics_store::log_rkp_error_stats;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070052use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000053use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070055 error::{Error as KsError, ErrorCode, ResponseCode},
56 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080057};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080058use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080059use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis030ba022021-05-26 11:15:30 -070060use utils as db_utils;
61use utils::SqlField;
Janis Danisevskis60400fe2020-08-26 15:24:42 -070062
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000063use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080064 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000065 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080066};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070067use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070068 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070069};
Max Bires2b2e6562020-09-22 11:22:36 -070070use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
71 AttestationPoolStatus::AttestationPoolStatus,
72};
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000073use android_security_metrics::aidl::android::security::metrics::{
74 StorageStats::StorageStats,
75 Storage::Storage as MetricsStorage,
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000076 RkpError::RkpError as MetricsRkpError,
Seth Moore78c091f2021-04-09 21:38:30 +000077};
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::{
Joel Galensonff79e362021-05-25 16:30:17 -070085 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080086 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,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700145 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800146 .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,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700220 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221 .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.
Chris Wailes3877f292021-07-26 19:24:18 -0700391 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800392 self.0
393 }
394
395 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700396 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800397 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
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800581/// This type represents a Blob with its metadata and an optional superseded blob.
582#[derive(Debug)]
583pub struct BlobInfo<'a> {
584 blob: &'a [u8],
585 metadata: &'a BlobMetaData,
586 /// Superseded blobs are an artifact of legacy import. In some rare occasions
587 /// the key blob needs to be upgraded during import. In that case two
588 /// blob are imported, the superseded one will have to be imported first,
589 /// so that the garbage collector can reap it.
590 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
591}
592
593impl<'a> BlobInfo<'a> {
594 /// Create a new instance of blob info with blob and corresponding metadata
595 /// and no superseded blob info.
596 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
597 Self { blob, metadata, superseded_blob: None }
598 }
599
600 /// Create a new instance of blob info with blob and corresponding metadata
601 /// as well as superseded blob info.
602 pub fn new_with_superseded(
603 blob: &'a [u8],
604 metadata: &'a BlobMetaData,
605 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
606 ) -> Self {
607 Self { blob, metadata, superseded_blob }
608 }
609}
610
Max Bires8e93d2b2021-01-14 13:17:59 -0800611impl CertificateInfo {
612 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
613 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
614 Self { cert, cert_chain }
615 }
616
617 /// Take the cert
618 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
619 self.cert.take()
620 }
621
622 /// Take the cert chain
623 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
624 self.cert_chain.take()
625 }
626}
627
Max Bires2b2e6562020-09-22 11:22:36 -0700628/// This type represents a certificate chain with a private key corresponding to the leaf
629/// 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 -0700630pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800631 /// A KM key blob
632 pub private_key: ZVec,
633 /// A batch cert for private_key
634 pub batch_cert: Vec<u8>,
635 /// A full certificate chain from root signing authority to private_key, including batch_cert
636 /// for convenience.
637 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700638}
639
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700640/// This type represents a Keystore 2.0 key entry.
641/// An entry has a unique `id` by which it can be found in the database.
642/// It has a security level field, key parameters, and three optional fields
643/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800644#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700645pub struct KeyEntry {
646 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800647 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700648 cert: Option<Vec<u8>>,
649 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800650 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700651 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800652 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800653 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700654}
655
656impl KeyEntry {
657 /// Returns the unique id of the Key entry.
658 pub fn id(&self) -> i64 {
659 self.id
660 }
661 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800662 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
663 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700664 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800665 /// Extracts the Optional KeyMint blob including its metadata.
666 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
667 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700668 }
669 /// Exposes the optional public certificate.
670 pub fn cert(&self) -> &Option<Vec<u8>> {
671 &self.cert
672 }
673 /// Extracts the optional public certificate.
674 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
675 self.cert.take()
676 }
677 /// Exposes the optional public certificate chain.
678 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
679 &self.cert_chain
680 }
681 /// Extracts the optional public certificate_chain.
682 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
683 self.cert_chain.take()
684 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800685 /// Returns the uuid of the owning KeyMint instance.
686 pub fn km_uuid(&self) -> &Uuid {
687 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700688 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700689 /// Exposes the key parameters of this key entry.
690 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
691 &self.parameters
692 }
693 /// Consumes this key entry and extracts the keyparameters from it.
694 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
695 self.parameters
696 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800697 /// Exposes the key metadata of this key entry.
698 pub fn metadata(&self) -> &KeyMetaData {
699 &self.metadata
700 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800701 /// This returns true if the entry is a pure certificate entry with no
702 /// private key component.
703 pub fn pure_cert(&self) -> bool {
704 self.pure_cert
705 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000706 /// Consumes this key entry and extracts the keyparameters and metadata from it.
707 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
708 (self.parameters, self.metadata)
709 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700710}
711
712/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800713#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700714pub struct SubComponentType(u32);
715impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800716 /// Persistent identifier for a key blob.
717 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700718 /// Persistent identifier for a certificate blob.
719 pub const CERT: SubComponentType = Self(1);
720 /// Persistent identifier for a certificate chain blob.
721 pub const CERT_CHAIN: SubComponentType = Self(2);
722}
723
724impl ToSql for SubComponentType {
725 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
726 self.0.to_sql()
727 }
728}
729
730impl FromSql for SubComponentType {
731 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
732 Ok(Self(u32::column_result(value)?))
733 }
734}
735
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800736/// This trait is private to the database module. It is used to convey whether or not the garbage
737/// collector shall be invoked after a database access. All closures passed to
738/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
739/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
740/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
741/// `.need_gc()`.
742trait DoGc<T> {
743 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
744
745 fn no_gc(self) -> Result<(bool, T)>;
746
747 fn need_gc(self) -> Result<(bool, T)>;
748}
749
750impl<T> DoGc<T> for Result<T> {
751 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
752 self.map(|r| (need_gc, r))
753 }
754
755 fn no_gc(self) -> Result<(bool, T)> {
756 self.do_gc(false)
757 }
758
759 fn need_gc(self) -> Result<(bool, T)> {
760 self.do_gc(true)
761 }
762}
763
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700764/// KeystoreDB wraps a connection to an SQLite database and tracks its
765/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700766pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700767 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700768 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700769 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700770}
771
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000772/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000773/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000774#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
775pub struct MonotonicRawTime(i64);
776
777impl MonotonicRawTime {
778 /// Constructs a new MonotonicRawTime
779 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000780 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000781 }
782
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000783 /// Returns the value of MonotonicRawTime in milliseconds as i64
784 pub fn milliseconds(&self) -> i64 {
785 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000786 }
787
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 /// Returns the integer value of MonotonicRawTime as i64
789 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000790 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000791 }
792
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800793 /// Like i64::checked_sub.
794 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
795 self.0.checked_sub(other.0).map(Self)
796 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000797}
798
799impl ToSql for MonotonicRawTime {
800 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
801 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
802 }
803}
804
805impl FromSql for MonotonicRawTime {
806 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
807 Ok(Self(i64::column_result(value)?))
808 }
809}
810
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000811/// This struct encapsulates the information to be stored in the database about the auth tokens
812/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700813#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000814pub struct AuthTokenEntry {
815 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000816 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000817 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818}
819
820impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000821 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822 AuthTokenEntry { auth_token, time_received }
823 }
824
825 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800826 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000827 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800828 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
829 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000830 })
831 }
832
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000833 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800834 pub fn auth_token(&self) -> &HardwareAuthToken {
835 &self.auth_token
836 }
837
838 /// Returns the auth token wrapped by the AuthTokenEntry
839 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000840 self.auth_token
841 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800842
843 /// Returns the time that this auth token was received.
844 pub fn time_received(&self) -> MonotonicRawTime {
845 self.time_received
846 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000847
848 /// Returns the challenge value of the auth token.
849 pub fn challenge(&self) -> i64 {
850 self.auth_token.challenge
851 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000852}
853
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
855/// This object does not allow access to the database connection. But it keeps a database
856/// connection alive in order to keep the in memory per boot database alive.
857pub struct PerBootDbKeepAlive(Connection);
858
Joel Galenson26f4d012020-07-17 14:57:21 -0700859impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800860 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700861 const CURRENT_DB_VERSION: u32 = 1;
862 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800863
Seth Moore78c091f2021-04-09 21:38:30 +0000864 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700865 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000866
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700867 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800868 /// files persistent.sqlite and perboot.sqlite in the given directory.
869 /// It also attempts to initialize all of the tables.
870 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700871 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700872 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700873 let _wp = wd::watch_millis("KeystoreDB::new", 500);
874
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700875 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700876 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800877
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700878 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800879 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700880 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
881 .context("In KeystoreDB::new: trying to upgrade database.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800882 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800883 })?;
884 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700885 }
886
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700887 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
888 // cryptographic binding to the boot level keys was implemented.
889 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
890 tx.execute(
891 "UPDATE persistent.keyentry SET state = ?
892 WHERE
893 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
894 AND
895 id NOT IN (
896 SELECT keyentryid FROM persistent.blobentry
897 WHERE id IN (
898 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
899 )
900 );",
901 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
902 )
903 .context("In from_0_to_1: Failed to delete logical boot level keys.")?;
904 Ok(1)
905 }
906
Janis Danisevskis66784c42021-01-27 08:40:25 -0800907 fn init_tables(tx: &Transaction) -> Result<()> {
908 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700910 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800911 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700912 domain INTEGER,
913 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800914 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800915 state INTEGER,
916 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700917 NO_PARAMS,
918 )
919 .context("Failed to initialize \"keyentry\" table.")?;
920
Janis Danisevskis66784c42021-01-27 08:40:25 -0800921 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800922 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
923 ON keyentry(id);",
924 NO_PARAMS,
925 )
926 .context("Failed to create index keyentry_id_index.")?;
927
928 tx.execute(
929 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
930 ON keyentry(domain, namespace, alias);",
931 NO_PARAMS,
932 )
933 .context("Failed to create index keyentry_domain_namespace_index.")?;
934
935 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700936 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
937 id INTEGER PRIMARY KEY,
938 subcomponent_type INTEGER,
939 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800940 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700941 NO_PARAMS,
942 )
943 .context("Failed to initialize \"blobentry\" table.")?;
944
Janis Danisevskis66784c42021-01-27 08:40:25 -0800945 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800946 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
947 ON blobentry(keyentryid);",
948 NO_PARAMS,
949 )
950 .context("Failed to create index blobentry_keyentryid_index.")?;
951
952 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800953 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
954 id INTEGER PRIMARY KEY,
955 blobentryid INTEGER,
956 tag INTEGER,
957 data ANY,
958 UNIQUE (blobentryid, tag));",
959 NO_PARAMS,
960 )
961 .context("Failed to initialize \"blobmetadata\" table.")?;
962
963 tx.execute(
964 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
965 ON blobmetadata(blobentryid);",
966 NO_PARAMS,
967 )
968 .context("Failed to create index blobmetadata_blobentryid_index.")?;
969
970 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700971 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000972 keyentryid INTEGER,
973 tag INTEGER,
974 data ANY,
975 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700976 NO_PARAMS,
977 )
978 .context("Failed to initialize \"keyparameter\" table.")?;
979
Janis Danisevskis66784c42021-01-27 08:40:25 -0800980 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800981 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
982 ON keyparameter(keyentryid);",
983 NO_PARAMS,
984 )
985 .context("Failed to create index keyparameter_keyentryid_index.")?;
986
987 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800988 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
989 keyentryid INTEGER,
990 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000991 data ANY,
992 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800993 NO_PARAMS,
994 )
995 .context("Failed to initialize \"keymetadata\" table.")?;
996
Janis Danisevskis66784c42021-01-27 08:40:25 -0800997 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800998 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
999 ON keymetadata(keyentryid);",
1000 NO_PARAMS,
1001 )
1002 .context("Failed to create index keymetadata_keyentryid_index.")?;
1003
1004 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001005 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001006 id INTEGER UNIQUE,
1007 grantee INTEGER,
1008 keyentryid INTEGER,
1009 access_vector INTEGER);",
1010 NO_PARAMS,
1011 )
1012 .context("Failed to initialize \"grant\" table.")?;
1013
Joel Galenson0891bc12020-07-20 10:37:03 -07001014 Ok(())
1015 }
1016
Seth Moore472fcbb2021-05-12 10:07:51 -07001017 fn make_persistent_path(db_root: &Path) -> Result<String> {
1018 // Build the path to the sqlite file.
1019 let mut persistent_path = db_root.to_path_buf();
1020 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1021
1022 // Now convert them to strings prefixed with "file:"
1023 let mut persistent_path_str = "file:".to_owned();
1024 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1025
1026 Ok(persistent_path_str)
1027 }
1028
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001029 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001030 let conn =
1031 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1032
Janis Danisevskis66784c42021-01-27 08:40:25 -08001033 loop {
1034 if let Err(e) = conn
1035 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1036 .context("Failed to attach database persistent.")
1037 {
1038 if Self::is_locked_error(&e) {
1039 std::thread::sleep(std::time::Duration::from_micros(500));
1040 continue;
1041 } else {
1042 return Err(e);
1043 }
1044 }
1045 break;
1046 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047
Matthew Maurer4fb19112021-05-06 15:40:44 -07001048 // Drop the cache size from default (2M) to 0.5M
1049 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1050 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001051
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001052 Ok(conn)
1053 }
1054
Seth Moore78c091f2021-04-09 21:38:30 +00001055 fn do_table_size_query(
1056 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001057 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001058 query: &str,
1059 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001060 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001061 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001062 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001063 .with_context(|| {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001064 format!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001065 })
1066 .no_gc()
1067 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001068 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001069 }
1070
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001071 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001072 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001073 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001074 "SELECT page_count * page_size, freelist_count * page_size
1075 FROM pragma_page_count('persistent'),
1076 pragma_page_size('persistent'),
1077 persistent.pragma_freelist_count();",
1078 &[],
1079 )
1080 }
1081
1082 fn get_table_size(
1083 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001084 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001085 schema: &str,
1086 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001087 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001088 self.do_table_size_query(
1089 storage_type,
1090 "SELECT pgsize,unused FROM dbstat(?1)
1091 WHERE name=?2 AND aggregate=TRUE;",
1092 &[schema, table],
1093 )
1094 }
1095
1096 /// Fetches a storage statisitics atom for a given storage type. For storage
1097 /// types that map to a table, information about the table's storage is
1098 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001099 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001100 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1101
Seth Moore78c091f2021-04-09 21:38:30 +00001102 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001103 MetricsStorage::DATABASE => self.get_total_size(),
1104 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001105 self.get_table_size(storage_type, "persistent", "keyentry")
1106 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001108 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1109 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001110 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001111 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1112 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001113 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001114 self.get_table_size(storage_type, "persistent", "blobentry")
1115 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001116 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001120 self.get_table_size(storage_type, "persistent", "keyparameter")
1121 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001122 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001123 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1124 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001125 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001126 self.get_table_size(storage_type, "persistent", "keymetadata")
1127 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001128 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001129 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1130 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001131 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1132 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001133 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1134 // reportable
1135 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001136 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001137 storage_type,
1138 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001140 unused_size: 0,
1141 })
Seth Moore78c091f2021-04-09 21:38:30 +00001142 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001143 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001144 self.get_table_size(storage_type, "persistent", "blobmetadata")
1145 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001146 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001147 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1148 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001149 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001150 }
1151 }
1152
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1155 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001156 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1157 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001158 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001159 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001160 blob_ids_to_delete: &[i64],
1161 max_blobs: usize,
1162 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001163 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001164 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 // Delete the given blobs.
1166 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167 tx.execute(
1168 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001169 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001170 )
1171 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1173 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001174 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001175
1176 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1177
Janis Danisevskis3395f862021-05-06 10:54:17 -07001178 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1179 let result: Vec<(i64, Vec<u8>)> = {
1180 let mut stmt = tx
1181 .prepare(
1182 "SELECT id, blob FROM persistent.blobentry
1183 WHERE subcomponent_type = ?
1184 AND (
1185 id NOT IN (
1186 SELECT MAX(id) FROM persistent.blobentry
1187 WHERE subcomponent_type = ?
1188 GROUP BY keyentryid, subcomponent_type
1189 )
1190 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1191 ) LIMIT ?;",
1192 )
1193 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001194
Janis Danisevskis3395f862021-05-06 10:54:17 -07001195 let rows = stmt
1196 .query_map(
1197 params![
1198 SubComponentType::KEY_BLOB,
1199 SubComponentType::KEY_BLOB,
1200 max_blobs as i64,
1201 ],
1202 |row| Ok((row.get(0)?, row.get(1)?)),
1203 )
1204 .context("Trying to query superseded blob.")?;
1205
1206 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1207 .context("Trying to extract superseded blobs.")?
1208 };
1209
1210 let result = result
1211 .into_iter()
1212 .map(|(blob_id, blob)| {
1213 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1214 })
1215 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1216 .context("Trying to load blob metadata.")?;
1217 if !result.is_empty() {
1218 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001219 }
1220
1221 // We did not find any superseded key blob, so let's remove other superseded blob in
1222 // one transaction.
1223 tx.execute(
1224 "DELETE FROM persistent.blobentry
1225 WHERE NOT subcomponent_type = ?
1226 AND (
1227 id NOT IN (
1228 SELECT MAX(id) FROM persistent.blobentry
1229 WHERE NOT subcomponent_type = ?
1230 GROUP BY keyentryid, subcomponent_type
1231 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1232 );",
1233 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1234 )
1235 .context("Trying to purge superseded blobs.")?;
1236
Janis Danisevskis3395f862021-05-06 10:54:17 -07001237 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001238 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001239 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001240 }
1241
1242 /// This maintenance function should be called only once before the database is used for the
1243 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1244 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1245 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1246 /// Keystore crashed at some point during key generation. Callers may want to log such
1247 /// occurrences.
1248 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1249 /// it to `KeyLifeCycle::Live` may have grants.
1250 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001251 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1252
Janis Danisevskis66784c42021-01-27 08:40:25 -08001253 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1254 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001255 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1256 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1257 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001258 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001259 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001260 })
1261 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001262 }
1263
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001264 /// Checks if a key exists with given key type and key descriptor properties.
1265 pub fn key_exists(
1266 &mut self,
1267 domain: Domain,
1268 nspace: i64,
1269 alias: &str,
1270 key_type: KeyType,
1271 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001272 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1273
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001274 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1275 let key_descriptor =
1276 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001277 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001278 match result {
1279 Ok(_) => Ok(true),
1280 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1281 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1282 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1283 },
1284 }
1285 .no_gc()
1286 })
1287 .context("In key_exists.")
1288 }
1289
Hasini Gunasingheda895552021-01-27 19:34:37 +00001290 /// Stores a super key in the database.
1291 pub fn store_super_key(
1292 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001293 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001294 key_type: &SuperKeyType,
1295 blob: &[u8],
1296 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001297 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001299 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1300
Hasini Gunasingheda895552021-01-27 19:34:37 +00001301 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1302 let key_id = Self::insert_with_retry(|id| {
1303 tx.execute(
1304 "INSERT into persistent.keyentry
1305 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001306 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001307 params![
1308 id,
1309 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001310 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001311 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001312 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 KeyLifeCycle::Live,
1314 &KEYSTORE_UUID,
1315 ],
1316 )
1317 })
1318 .context("Failed to insert into keyentry table.")?;
1319
Paul Crowley8d5b2532021-03-19 10:53:07 -07001320 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1321
Hasini Gunasingheda895552021-01-27 19:34:37 +00001322 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001323 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001324 key_id,
1325 SubComponentType::KEY_BLOB,
1326 Some(blob),
1327 Some(blob_metadata),
1328 )
1329 .context("Failed to store key blob.")?;
1330
1331 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1332 .context("Trying to load key components.")
1333 .no_gc()
1334 })
1335 .context("In store_super_key.")
1336 }
1337
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001338 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001339 pub fn load_super_key(
1340 &mut self,
1341 key_type: &SuperKeyType,
1342 user_id: u32,
1343 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001344 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1345
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001346 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1347 let key_descriptor = KeyDescriptor {
1348 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001349 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001350 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001351 blob: None,
1352 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001353 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001354 match id {
1355 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001356 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001357 .context("In load_super_key. Failed to load key entry.")?;
1358 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1359 }
1360 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1361 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1362 _ => Err(error).context("In load_super_key."),
1363 },
1364 }
1365 .no_gc()
1366 })
1367 .context("In load_super_key.")
1368 }
1369
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001370 /// Atomically loads a key entry and associated metadata or creates it using the
1371 /// callback create_new_key callback. The callback is called during a database
1372 /// transaction. This means that implementers should be mindful about using
1373 /// blocking operations such as IPC or grabbing mutexes.
1374 pub fn get_or_create_key_with<F>(
1375 &mut self,
1376 domain: Domain,
1377 namespace: i64,
1378 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001379 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001380 create_new_key: F,
1381 ) -> Result<(KeyIdGuard, KeyEntry)>
1382 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001383 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001384 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001385 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1386
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1388 let id = {
1389 let mut stmt = tx
1390 .prepare(
1391 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001392 WHERE
1393 key_type = ?
1394 AND domain = ?
1395 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001396 AND alias = ?
1397 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 )
1399 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1400 let mut rows = stmt
1401 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1402 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 db_utils::with_rows_extract_one(&mut rows, |row| {
1405 Ok(match row {
1406 Some(r) => r.get(0).context("Failed to unpack id.")?,
1407 None => None,
1408 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001409 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001410 .context("In get_or_create_key_with.")?
1411 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001412
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 let (id, entry) = match id {
1414 Some(id) => (
1415 id,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001416 Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 .context("In get_or_create_key_with.")?,
1418 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001419
Janis Danisevskis66784c42021-01-27 08:40:25 -08001420 None => {
1421 let id = Self::insert_with_retry(|id| {
1422 tx.execute(
1423 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001424 (id, key_type, domain, namespace, alias, state, km_uuid)
1425 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001426 params![
1427 id,
1428 KeyType::Super,
1429 domain.0,
1430 namespace,
1431 alias,
1432 KeyLifeCycle::Live,
1433 km_uuid,
1434 ],
1435 )
1436 })
1437 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001438
Janis Danisevskis66784c42021-01-27 08:40:25 -08001439 let (blob, metadata) =
1440 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001441 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001442 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001443 id,
1444 SubComponentType::KEY_BLOB,
1445 Some(&blob),
1446 Some(&metadata),
1447 )
Paul Crowley7a658392021-03-18 17:08:20 -07001448 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001449 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001450 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001451 KeyEntry {
1452 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001453 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001454 pure_cert: false,
1455 ..Default::default()
1456 },
1457 )
1458 }
1459 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001460 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001461 })
1462 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001463 }
1464
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001465 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001466 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1467 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001468 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1469 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001470 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001471 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001472 loop {
1473 match self
1474 .conn
1475 .transaction_with_behavior(behavior)
1476 .context("In with_transaction.")
1477 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1478 .and_then(|(result, tx)| {
1479 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1480 Ok(result)
1481 }) {
1482 Ok(result) => break Ok(result),
1483 Err(e) => {
1484 if Self::is_locked_error(&e) {
1485 std::thread::sleep(std::time::Duration::from_micros(500));
1486 continue;
1487 } else {
1488 return Err(e).context("In with_transaction.");
1489 }
1490 }
1491 }
1492 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001493 .map(|(need_gc, result)| {
1494 if need_gc {
1495 if let Some(ref gc) = self.gc {
1496 gc.notify_gc();
1497 }
1498 }
1499 result
1500 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001501 }
1502
1503 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001504 matches!(
1505 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1506 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1507 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1508 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001509 }
1510
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001511 /// Creates a new key entry and allocates a new randomized id for the new key.
1512 /// The key id gets associated with a domain and namespace but not with an alias.
1513 /// To complete key generation `rebind_alias` should be called after all of the
1514 /// key artifacts, i.e., blobs and parameters have been associated with the new
1515 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1516 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001517 pub fn create_key_entry(
1518 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001519 domain: &Domain,
1520 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001521 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001522 km_uuid: &Uuid,
1523 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001524 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1525
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001526 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001527 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 })
1529 .context("In create_key_entry.")
1530 }
1531
1532 fn create_key_entry_internal(
1533 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001534 domain: &Domain,
1535 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001536 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001537 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001538 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001539 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001540 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001541 _ => {
1542 return Err(KsError::sys())
1543 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1544 }
1545 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001546 Ok(KEY_ID_LOCK.get(
1547 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001548 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001549 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001550 (id, key_type, domain, namespace, alias, state, km_uuid)
1551 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001552 params![
1553 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001554 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001555 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001556 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001557 KeyLifeCycle::Existing,
1558 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001559 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001560 )
1561 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001562 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001563 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001564 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001565
Max Bires2b2e6562020-09-22 11:22:36 -07001566 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1567 /// The key id gets associated with a domain and namespace later but not with an alias. The
1568 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1569 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1570 /// a key.
1571 pub fn create_attestation_key_entry(
1572 &mut self,
1573 maced_public_key: &[u8],
1574 raw_public_key: &[u8],
1575 private_key: &[u8],
1576 km_uuid: &Uuid,
1577 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001578 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1579
Max Bires2b2e6562020-09-22 11:22:36 -07001580 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1581 let key_id = KEY_ID_LOCK.get(
1582 Self::insert_with_retry(|id| {
1583 tx.execute(
1584 "INSERT into persistent.keyentry
1585 (id, key_type, domain, namespace, alias, state, km_uuid)
1586 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1587 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1588 )
1589 })
1590 .context("In create_key_entry")?,
1591 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001592 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001593 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001594 key_id.0,
1595 SubComponentType::KEY_BLOB,
1596 Some(private_key),
1597 None,
1598 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001599 let mut metadata = KeyMetaData::new();
1600 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1601 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001602 metadata.store_in_db(key_id.0, tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001603 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001604 })
1605 .context("In create_attestation_key_entry")
1606 }
1607
Janis Danisevskis377d1002021-01-27 19:07:48 -08001608 /// Set a new blob and associates it with the given key id. Each blob
1609 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001610 /// Each key can have one of each sub component type associated. If more
1611 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001612 /// will get garbage collected.
1613 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1614 /// removed by setting blob to None.
1615 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001616 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001617 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001618 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001619 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001620 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001621 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001622 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1623
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001624 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001625 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001626 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001627 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001628 }
1629
Janis Danisevskiseed69842021-02-18 20:04:10 -08001630 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1631 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1632 /// We use this to insert key blobs into the database which can then be garbage collected
1633 /// lazily by the key garbage collector.
1634 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001635 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1636
Janis Danisevskiseed69842021-02-18 20:04:10 -08001637 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1638 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001639 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001640 Self::UNASSIGNED_KEY_ID,
1641 SubComponentType::KEY_BLOB,
1642 Some(blob),
1643 Some(blob_metadata),
1644 )
1645 .need_gc()
1646 })
1647 .context("In set_deleted_blob.")
1648 }
1649
Janis Danisevskis377d1002021-01-27 19:07:48 -08001650 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001651 tx: &Transaction,
1652 key_id: i64,
1653 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001654 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001655 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001656 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001657 match (blob, sc_type) {
1658 (Some(blob), _) => {
1659 tx.execute(
1660 "INSERT INTO persistent.blobentry
1661 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1662 params![sc_type, key_id, blob],
1663 )
1664 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001665 if let Some(blob_metadata) = blob_metadata {
1666 let blob_id = tx
1667 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1668 row.get(0)
1669 })
1670 .context("In set_blob_internal: Failed to get new blob id.")?;
1671 blob_metadata
1672 .store_in_db(blob_id, tx)
1673 .context("In set_blob_internal: Trying to store blob metadata.")?;
1674 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001675 }
1676 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1677 tx.execute(
1678 "DELETE FROM persistent.blobentry
1679 WHERE subcomponent_type = ? AND keyentryid = ?;",
1680 params![sc_type, key_id],
1681 )
1682 .context("In set_blob_internal: Failed to delete blob.")?;
1683 }
1684 (None, _) => {
1685 return Err(KsError::sys())
1686 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1687 }
1688 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001689 Ok(())
1690 }
1691
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001692 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1693 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001694 #[cfg(test)]
1695 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001696 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001697 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001698 })
1699 .context("In insert_keyparameter.")
1700 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001701
Janis Danisevskis66784c42021-01-27 08:40:25 -08001702 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001703 tx: &Transaction,
1704 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001705 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001706 ) -> Result<()> {
1707 let mut stmt = tx
1708 .prepare(
1709 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1710 VALUES (?, ?, ?, ?);",
1711 )
1712 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1713
Janis Danisevskis66784c42021-01-27 08:40:25 -08001714 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001715 stmt.insert(params![
1716 key_id.0,
1717 p.get_tag().0,
1718 p.key_parameter_value(),
1719 p.security_level().0
1720 ])
1721 .with_context(|| {
1722 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1723 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001724 }
1725 Ok(())
1726 }
1727
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001728 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001729 #[cfg(test)]
1730 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001731 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001732 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 })
1734 .context("In insert_key_metadata.")
1735 }
1736
Max Bires2b2e6562020-09-22 11:22:36 -07001737 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1738 /// on the public key.
1739 pub fn store_signed_attestation_certificate_chain(
1740 &mut self,
1741 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001742 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001743 cert_chain: &[u8],
1744 expiration_date: i64,
1745 km_uuid: &Uuid,
1746 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001747 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1748
Max Bires2b2e6562020-09-22 11:22:36 -07001749 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1750 let mut stmt = tx
1751 .prepare(
1752 "SELECT keyentryid
1753 FROM persistent.keymetadata
1754 WHERE tag = ? AND data = ? AND keyentryid IN
1755 (SELECT id
1756 FROM persistent.keyentry
1757 WHERE
1758 alias IS NULL AND
1759 domain IS NULL AND
1760 namespace IS NULL AND
1761 key_type = ? AND
1762 km_uuid = ?);",
1763 )
1764 .context("Failed to store attestation certificate chain.")?;
1765 let mut rows = stmt
1766 .query(params![
1767 KeyMetaData::AttestationRawPubKey,
1768 raw_public_key,
1769 KeyType::Attestation,
1770 km_uuid
1771 ])
1772 .context("Failed to fetch keyid")?;
1773 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1774 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1775 .get(0)
1776 .context("Failed to unpack id.")
1777 })
1778 .context("Failed to get key_id.")?;
1779 let num_updated = tx
1780 .execute(
1781 "UPDATE persistent.keyentry
1782 SET alias = ?
1783 WHERE id = ?;",
1784 params!["signed", key_id],
1785 )
1786 .context("Failed to update alias.")?;
1787 if num_updated != 1 {
1788 return Err(KsError::sys()).context("Alias not updated for the key.");
1789 }
1790 let mut metadata = KeyMetaData::new();
1791 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1792 expiration_date,
1793 )));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001794 metadata.store_in_db(key_id, tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001795 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001796 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001797 key_id,
1798 SubComponentType::CERT_CHAIN,
1799 Some(cert_chain),
1800 None,
1801 )
1802 .context("Failed to insert cert chain")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001803 Self::set_blob_internal(tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
Max Biresb2e1d032021-02-08 21:35:05 -08001804 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001805 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001806 })
1807 .context("In store_signed_attestation_certificate_chain: ")
1808 }
1809
1810 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1811 /// currently have a key assigned to it.
1812 pub fn assign_attestation_key(
1813 &mut self,
1814 domain: Domain,
1815 namespace: i64,
1816 km_uuid: &Uuid,
1817 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001818 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1819
Max Bires2b2e6562020-09-22 11:22:36 -07001820 match domain {
1821 Domain::APP | Domain::SELINUX => {}
1822 _ => {
1823 return Err(KsError::sys()).context(format!(
1824 concat!(
1825 "In assign_attestation_key: Domain {:?} ",
1826 "must be either App or SELinux.",
1827 ),
1828 domain
1829 ));
1830 }
1831 }
1832 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1833 let result = tx
1834 .execute(
1835 "UPDATE persistent.keyentry
1836 SET domain=?1, namespace=?2
1837 WHERE
1838 id =
1839 (SELECT MIN(id)
1840 FROM persistent.keyentry
1841 WHERE ALIAS IS NOT NULL
1842 AND domain IS NULL
1843 AND key_type IS ?3
1844 AND state IS ?4
1845 AND km_uuid IS ?5)
1846 AND
1847 (SELECT COUNT(*)
1848 FROM persistent.keyentry
1849 WHERE domain=?1
1850 AND namespace=?2
1851 AND key_type IS ?3
1852 AND state IS ?4
1853 AND km_uuid IS ?5) = 0;",
1854 params![
1855 domain.0 as u32,
1856 namespace,
1857 KeyType::Attestation,
1858 KeyLifeCycle::Live,
1859 km_uuid,
1860 ],
1861 )
1862 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001863 if result == 0 {
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +00001864 log_rkp_error_stats(MetricsRkpError::OUT_OF_KEYS);
Max Bires01f8af22021-03-02 23:24:50 -08001865 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1866 } else if result > 1 {
1867 return Err(KsError::sys())
1868 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001869 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001870 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001871 })
1872 .context("In assign_attestation_key: ")
1873 }
1874
1875 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1876 /// provisioning server, or the maximum number available if there are not num_keys number of
1877 /// entries in the table.
1878 pub fn fetch_unsigned_attestation_keys(
1879 &mut self,
1880 num_keys: i32,
1881 km_uuid: &Uuid,
1882 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001883 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1884
Max Bires2b2e6562020-09-22 11:22:36 -07001885 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1886 let mut stmt = tx
1887 .prepare(
1888 "SELECT data
1889 FROM persistent.keymetadata
1890 WHERE tag = ? AND keyentryid IN
1891 (SELECT id
1892 FROM persistent.keyentry
1893 WHERE
1894 alias IS NULL AND
1895 domain IS NULL AND
1896 namespace IS NULL AND
1897 key_type = ? AND
1898 km_uuid = ?
1899 LIMIT ?);",
1900 )
1901 .context("Failed to prepare statement")?;
1902 let rows = stmt
1903 .query_map(
1904 params![
1905 KeyMetaData::AttestationMacedPublicKey,
1906 KeyType::Attestation,
1907 km_uuid,
1908 num_keys
1909 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001910 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001911 )?
1912 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1913 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001914 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001915 })
1916 .context("In fetch_unsigned_attestation_keys")
1917 }
1918
1919 /// Removes any keys that have expired as of the current time. Returns the number of keys
1920 /// marked unreferenced that are bound to be garbage collected.
1921 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001922 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1923
Max Bires2b2e6562020-09-22 11:22:36 -07001924 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1925 let mut stmt = tx
1926 .prepare(
1927 "SELECT keyentryid, data
1928 FROM persistent.keymetadata
1929 WHERE tag = ? AND keyentryid IN
1930 (SELECT id
1931 FROM persistent.keyentry
1932 WHERE key_type = ?);",
1933 )
1934 .context("Failed to prepare query")?;
1935 let key_ids_to_check = stmt
1936 .query_map(
1937 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1938 |row| Ok((row.get(0)?, row.get(1)?)),
1939 )?
1940 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1941 .context("Failed to get date metadata")?;
1942 let curr_time = DateTime::from_millis_epoch(
1943 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1944 );
1945 let mut num_deleted = 0;
1946 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001947 if Self::mark_unreferenced(tx, id)? {
Max Bires2b2e6562020-09-22 11:22:36 -07001948 num_deleted += 1;
1949 }
1950 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001951 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001952 })
1953 .context("In delete_expired_attestation_keys: ")
1954 }
1955
Max Bires60d7ed12021-03-05 15:59:22 -08001956 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1957 /// they are in. This is useful primarily as a testing mechanism.
1958 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001959 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1960
Max Bires60d7ed12021-03-05 15:59:22 -08001961 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1962 let mut stmt = tx
1963 .prepare(
1964 "SELECT id FROM persistent.keyentry
1965 WHERE key_type IS ?;",
1966 )
1967 .context("Failed to prepare statement")?;
1968 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001969 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001970 .collect::<rusqlite::Result<Vec<i64>>>()
1971 .context("Failed to execute statement")?;
1972 let num_deleted = keys_to_delete
1973 .iter()
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001974 .map(|id| Self::mark_unreferenced(tx, *id))
Max Bires60d7ed12021-03-05 15:59:22 -08001975 .collect::<Result<Vec<bool>>>()
1976 .context("Failed to execute mark_unreferenced on a keyid")?
1977 .into_iter()
1978 .filter(|result| *result)
1979 .count() as i64;
1980 Ok(num_deleted).do_gc(num_deleted != 0)
1981 })
1982 .context("In delete_all_attestation_keys: ")
1983 }
1984
Max Bires2b2e6562020-09-22 11:22:36 -07001985 /// Counts the number of keys that will expire by the provided epoch date and the number of
1986 /// keys not currently assigned to a domain.
1987 pub fn get_attestation_pool_status(
1988 &mut self,
1989 date: i64,
1990 km_uuid: &Uuid,
1991 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001992 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1993
Max Bires2b2e6562020-09-22 11:22:36 -07001994 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1995 let mut stmt = tx.prepare(
1996 "SELECT data
1997 FROM persistent.keymetadata
1998 WHERE tag = ? AND keyentryid IN
1999 (SELECT id
2000 FROM persistent.keyentry
2001 WHERE alias IS NOT NULL
2002 AND key_type = ?
2003 AND km_uuid = ?
2004 AND state = ?);",
2005 )?;
2006 let times = stmt
2007 .query_map(
2008 params![
2009 KeyMetaData::AttestationExpirationDate,
2010 KeyType::Attestation,
2011 km_uuid,
2012 KeyLifeCycle::Live
2013 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002014 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002015 )?
2016 .collect::<rusqlite::Result<Vec<DateTime>>>()
2017 .context("Failed to execute metadata statement")?;
2018 let expiring =
2019 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2020 as i32;
2021 stmt = tx.prepare(
2022 "SELECT alias, domain
2023 FROM persistent.keyentry
2024 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2025 )?;
2026 let rows = stmt
2027 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2028 Ok((row.get(0)?, row.get(1)?))
2029 })?
2030 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2031 .context("Failed to execute keyentry statement")?;
2032 let mut unassigned = 0i32;
2033 let mut attested = 0i32;
2034 let total = rows.len() as i32;
2035 for (alias, domain) in rows {
2036 match (alias, domain) {
2037 (Some(_alias), None) => {
2038 attested += 1;
2039 unassigned += 1;
2040 }
2041 (Some(_alias), Some(_domain)) => {
2042 attested += 1;
2043 }
2044 _ => {}
2045 }
2046 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002047 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002048 })
2049 .context("In get_attestation_pool_status: ")
2050 }
2051
2052 /// Fetches the private key and corresponding certificate chain assigned to a
2053 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2054 /// not assigned, or one CertificateChain.
2055 pub fn retrieve_attestation_key_and_cert_chain(
2056 &mut self,
2057 domain: Domain,
2058 namespace: i64,
2059 km_uuid: &Uuid,
2060 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002061 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2062
Max Bires2b2e6562020-09-22 11:22:36 -07002063 match domain {
2064 Domain::APP | Domain::SELINUX => {}
2065 _ => {
2066 return Err(KsError::sys())
2067 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2068 }
2069 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002070 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2071 let mut stmt = tx.prepare(
2072 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002073 FROM persistent.blobentry
2074 WHERE keyentryid IN
2075 (SELECT id
2076 FROM persistent.keyentry
2077 WHERE key_type = ?
2078 AND domain = ?
2079 AND namespace = ?
2080 AND state = ?
2081 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 )?;
2083 let rows = stmt
2084 .query_map(
2085 params![
2086 KeyType::Attestation,
2087 domain.0 as u32,
2088 namespace,
2089 KeyLifeCycle::Live,
2090 km_uuid
2091 ],
2092 |row| Ok((row.get(0)?, row.get(1)?)),
2093 )?
2094 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002095 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002096 if rows.is_empty() {
2097 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002098 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002099 return Err(KsError::sys()).context(format!(
2100 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002101 "Expected to get a single attestation",
2102 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2103 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002104 rows.len()
2105 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002106 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002107 let mut km_blob: Vec<u8> = Vec::new();
2108 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002109 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002110 for row in rows {
2111 let sub_type: SubComponentType = row.0;
2112 match sub_type {
2113 SubComponentType::KEY_BLOB => {
2114 km_blob = row.1;
2115 }
2116 SubComponentType::CERT_CHAIN => {
2117 cert_chain_blob = row.1;
2118 }
Max Biresb2e1d032021-02-08 21:35:05 -08002119 SubComponentType::CERT => {
2120 batch_cert_blob = row.1;
2121 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002122 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2123 }
2124 }
2125 Ok(Some(CertificateChain {
2126 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002127 batch_cert: batch_cert_blob,
2128 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002129 }))
2130 .no_gc()
2131 })
Max Biresb2e1d032021-02-08 21:35:05 -08002132 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002133 }
2134
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002135 /// Updates the alias column of the given key id `newid` with the given alias,
2136 /// and atomically, removes the alias, domain, and namespace from another row
2137 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002138 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2139 /// collector.
2140 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002141 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002142 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002143 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002144 domain: &Domain,
2145 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002146 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002147 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002148 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002149 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002150 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002151 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002152 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002153 domain
2154 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002155 }
2156 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002157 let updated = tx
2158 .execute(
2159 "UPDATE persistent.keyentry
2160 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002161 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2162 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002163 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002164 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002165 let result = tx
2166 .execute(
2167 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002168 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002169 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002170 params![
2171 alias,
2172 KeyLifeCycle::Live,
2173 newid.0,
2174 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002175 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002176 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002177 key_type,
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.
Chris Wailes3877f292021-07-26 19:24:18 -07002260 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002261 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002262 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002263 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002264 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002265 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002266 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08002267 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002268 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002269 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002270 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002271 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2272
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 let (alias, domain, namespace) = match key {
2274 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2275 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2276 (alias, key.domain, nspace)
2277 }
2278 _ => {
2279 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2280 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2281 }
2282 };
2283 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002284 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002285 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002286 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
2287
2288 // In some occasions the key blob is already upgraded during the import.
2289 // In order to make sure it gets properly deleted it is inserted into the
2290 // database here and then immediately replaced by the superseding blob.
2291 // The garbage collector will then subject the blob to deleteKey of the
2292 // KM back end to permanently invalidate the key.
2293 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
2294 Self::set_blob_internal(
2295 tx,
2296 key_id.id(),
2297 SubComponentType::KEY_BLOB,
2298 Some(blob),
2299 Some(blob_metadata),
2300 )
2301 .context("Trying to insert superseded key blob.")?;
2302 true
2303 } else {
2304 false
2305 };
2306
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002307 Self::set_blob_internal(
2308 tx,
2309 key_id.id(),
2310 SubComponentType::KEY_BLOB,
2311 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002312 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002313 )
2314 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002315 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002316 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002317 .context("Trying to insert the certificate.")?;
2318 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002319 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002320 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002321 tx,
2322 key_id.id(),
2323 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002324 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002325 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002326 )
2327 .context("Trying to insert the certificate chain.")?;
2328 }
2329 Self::insert_keyparameter_internal(tx, &key_id, params)
2330 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002331 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002332 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002333 .context("Trying to rebind alias.")?
2334 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002335 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002336 })
2337 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002338 }
2339
Janis Danisevskis377d1002021-01-27 19:07:48 -08002340 /// Store a new certificate
2341 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2342 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002343 pub fn store_new_certificate(
2344 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002345 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002346 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002347 cert: &[u8],
2348 km_uuid: &Uuid,
2349 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002350 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2351
Janis Danisevskis377d1002021-01-27 19:07:48 -08002352 let (alias, domain, namespace) = match key {
2353 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2354 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2355 (alias, key.domain, nspace)
2356 }
2357 _ => {
2358 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2359 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2360 )
2361 }
2362 };
2363 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002364 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002365 .context("Trying to create new key entry.")?;
2366
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002367 Self::set_blob_internal(
2368 tx,
2369 key_id.id(),
2370 SubComponentType::CERT_CHAIN,
2371 Some(cert),
2372 None,
2373 )
2374 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002375
2376 let mut metadata = KeyMetaData::new();
2377 metadata.add(KeyMetaEntry::CreationDate(
2378 DateTime::now().context("Trying to make creation time.")?,
2379 ));
2380
2381 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2382
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002383 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002384 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002385 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002386 })
2387 .context("In store_new_certificate.")
2388 }
2389
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002390 // Helper function loading the key_id given the key descriptor
2391 // tuple comprising domain, namespace, and alias.
2392 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002393 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002394 let alias = key
2395 .alias
2396 .as_ref()
2397 .map_or_else(|| Err(KsError::sys()), Ok)
2398 .context("In load_key_entry_id: Alias must be specified.")?;
2399 let mut stmt = tx
2400 .prepare(
2401 "SELECT id FROM persistent.keyentry
2402 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002403 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002404 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002405 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002406 AND alias = ?
2407 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408 )
2409 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2410 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002411 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002412 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002413 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002414 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002415 .get(0)
2416 .context("Failed to unpack id.")
2417 })
2418 .context("In load_key_entry_id.")
2419 }
2420
2421 /// This helper function completes the access tuple of a key, which is required
2422 /// to perform access control. The strategy depends on the `domain` field in the
2423 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002424 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002425 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002426 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002427 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002428 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002429 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002430 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002431 /// `namespace`.
2432 /// In each case the information returned is sufficient to perform the access
2433 /// check and the key id can be used to load further key artifacts.
2434 fn load_access_tuple(
2435 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002436 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002437 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 caller_uid: u32,
2439 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2440 match key.domain {
2441 // Domain App or SELinux. In this case we load the key_id from
2442 // the keyentry database for further loading of key components.
2443 // We already have the full access tuple to perform access control.
2444 // The only distinction is that we use the caller_uid instead
2445 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002446 // Domain::APP.
2447 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002448 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002449 if access_key.domain == Domain::APP {
2450 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002451 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002452 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002453 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002454
2455 Ok((key_id, access_key, None))
2456 }
2457
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002458 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002459 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002460 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002461 let mut stmt = tx
2462 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002463 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002464 WHERE grantee = ? AND id = ? AND
2465 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002466 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002467 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002468 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002469 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002470 .context("Domain:Grant: query failed.")?;
2471 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002472 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002473 let r =
2474 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002475 Ok((
2476 r.get(0).context("Failed to unpack key_id.")?,
2477 r.get(1).context("Failed to unpack access_vector.")?,
2478 ))
2479 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002480 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002481 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002482 }
2483
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002484 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002485 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002486 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002487 let (domain, namespace): (Domain, i64) = {
2488 let mut stmt = tx
2489 .prepare(
2490 "SELECT domain, namespace FROM persistent.keyentry
2491 WHERE
2492 id = ?
2493 AND state = ?;",
2494 )
2495 .context("Domain::KEY_ID: prepare statement failed")?;
2496 let mut rows = stmt
2497 .query(params![key.nspace, KeyLifeCycle::Live])
2498 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002499 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002500 let r =
2501 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002502 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002503 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002504 r.get(1).context("Failed to unpack namespace.")?,
2505 ))
2506 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002507 .context("Domain::KEY_ID.")?
2508 };
2509
2510 // We may use a key by id after loading it by grant.
2511 // In this case we have to check if the caller has a grant for this particular
2512 // key. We can skip this if we already know that the caller is the owner.
2513 // But we cannot know this if domain is anything but App. E.g. in the case
2514 // of Domain::SELINUX we have to speculatively check for grants because we have to
2515 // consult the SEPolicy before we know if the caller is the owner.
2516 let access_vector: Option<KeyPermSet> =
2517 if domain != Domain::APP || namespace != caller_uid as i64 {
2518 let access_vector: Option<i32> = tx
2519 .query_row(
2520 "SELECT access_vector FROM persistent.grant
2521 WHERE grantee = ? AND keyentryid = ?;",
2522 params![caller_uid as i64, key.nspace],
2523 |row| row.get(0),
2524 )
2525 .optional()
2526 .context("Domain::KEY_ID: query grant failed.")?;
2527 access_vector.map(|p| p.into())
2528 } else {
2529 None
2530 };
2531
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002532 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002533 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002534 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002535 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002536
Janis Danisevskis45760022021-01-19 16:34:10 -08002537 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002538 }
2539 _ => Err(anyhow!(KsError::sys())),
2540 }
2541 }
2542
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002543 fn load_blob_components(
2544 key_id: i64,
2545 load_bits: KeyEntryLoadBits,
2546 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002547 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002548 let mut stmt = tx
2549 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002550 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002551 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2552 )
2553 .context("In load_blob_components: prepare statement failed.")?;
2554
2555 let mut rows =
2556 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2557
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002558 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002559 let mut cert_blob: Option<Vec<u8>> = None;
2560 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002561 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002562 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002563 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002564 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002565 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002566 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2567 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002568 key_blob = Some((
2569 row.get(0).context("Failed to extract key blob id.")?,
2570 row.get(2).context("Failed to extract key blob.")?,
2571 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002572 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002573 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002574 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002575 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002576 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002577 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002578 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002579 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002580 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002581 (SubComponentType::CERT, _, _)
2582 | (SubComponentType::CERT_CHAIN, _, _)
2583 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002584 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2585 }
2586 Ok(())
2587 })
2588 .context("In load_blob_components.")?;
2589
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002590 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2591 Ok(Some((
2592 blob,
2593 BlobMetaData::load_from_db(blob_id, tx)
2594 .context("In load_blob_components: Trying to load blob_metadata.")?,
2595 )))
2596 })?;
2597
2598 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002599 }
2600
2601 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2602 let mut stmt = tx
2603 .prepare(
2604 "SELECT tag, data, security_level from persistent.keyparameter
2605 WHERE keyentryid = ?;",
2606 )
2607 .context("In load_key_parameters: prepare statement failed.")?;
2608
2609 let mut parameters: Vec<KeyParameter> = Vec::new();
2610
2611 let mut rows =
2612 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002613 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002614 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2615 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002616 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002617 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002618 .context("Failed to read KeyParameter.")?,
2619 );
2620 Ok(())
2621 })
2622 .context("In load_key_parameters.")?;
2623
2624 Ok(parameters)
2625 }
2626
Qi Wub9433b52020-12-01 14:52:46 +08002627 /// Decrements the usage count of a limited use key. This function first checks whether the
2628 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2629 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2630 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002631 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002632 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2633
Qi Wub9433b52020-12-01 14:52:46 +08002634 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2635 let limit: Option<i32> = tx
2636 .query_row(
2637 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2638 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2639 |row| row.get(0),
2640 )
2641 .optional()
2642 .context("Trying to load usage count")?;
2643
2644 let limit = limit
2645 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2646 .context("The Key no longer exists. Key is exhausted.")?;
2647
2648 tx.execute(
2649 "UPDATE persistent.keyparameter
2650 SET data = data - 1
2651 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2652 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2653 )
2654 .context("Failed to update key usage count.")?;
2655
2656 match limit {
2657 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002658 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002659 .context("Trying to mark limited use key for deletion."),
2660 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002661 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002662 }
2663 })
2664 .context("In check_and_update_key_usage_count.")
2665 }
2666
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002667 /// Load a key entry by the given key descriptor.
2668 /// It uses the `check_permission` callback to verify if the access is allowed
2669 /// given the key access tuple read from the database using `load_access_tuple`.
2670 /// With `load_bits` the caller may specify which blobs shall be loaded from
2671 /// the blob database.
2672 pub fn load_key_entry(
2673 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002674 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002675 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002676 load_bits: KeyEntryLoadBits,
2677 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002678 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2679 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002680 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2681
Janis Danisevskis66784c42021-01-27 08:40:25 -08002682 loop {
2683 match self.load_key_entry_internal(
2684 key,
2685 key_type,
2686 load_bits,
2687 caller_uid,
2688 &check_permission,
2689 ) {
2690 Ok(result) => break Ok(result),
2691 Err(e) => {
2692 if Self::is_locked_error(&e) {
2693 std::thread::sleep(std::time::Duration::from_micros(500));
2694 continue;
2695 } else {
2696 return Err(e).context("In load_key_entry.");
2697 }
2698 }
2699 }
2700 }
2701 }
2702
2703 fn load_key_entry_internal(
2704 &mut self,
2705 key: &KeyDescriptor,
2706 key_type: KeyType,
2707 load_bits: KeyEntryLoadBits,
2708 caller_uid: u32,
2709 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002710 ) -> Result<(KeyIdGuard, KeyEntry)> {
2711 // KEY ID LOCK 1/2
2712 // If we got a key descriptor with a key id we can get the lock right away.
2713 // Otherwise we have to defer it until we know the key id.
2714 let key_id_guard = match key.domain {
2715 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2716 _ => None,
2717 };
2718
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002719 let tx = self
2720 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002721 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002722 .context("In load_key_entry: Failed to initialize transaction.")?;
2723
2724 // Load the key_id and complete the access control tuple.
2725 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002726 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2727 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002728
2729 // Perform access control. It is vital that we return here if the permission is denied.
2730 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002731 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002732
Janis Danisevskisaec14592020-11-12 09:41:49 -08002733 // KEY ID LOCK 2/2
2734 // If we did not get a key id lock by now, it was because we got a key descriptor
2735 // without a key id. At this point we got the key id, so we can try and get a lock.
2736 // However, we cannot block here, because we are in the middle of the transaction.
2737 // So first we try to get the lock non blocking. If that fails, we roll back the
2738 // transaction and block until we get the lock. After we successfully got the lock,
2739 // we start a new transaction and load the access tuple again.
2740 //
2741 // We don't need to perform access control again, because we already established
2742 // that the caller had access to the given key. But we need to make sure that the
2743 // key id still exists. So we have to load the key entry by key id this time.
2744 let (key_id_guard, tx) = match key_id_guard {
2745 None => match KEY_ID_LOCK.try_get(key_id) {
2746 None => {
2747 // Roll back the transaction.
2748 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002749
Janis Danisevskisaec14592020-11-12 09:41:49 -08002750 // Block until we have a key id lock.
2751 let key_id_guard = KEY_ID_LOCK.get(key_id);
2752
2753 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002754 let tx = self
2755 .conn
2756 .unchecked_transaction()
2757 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002758
2759 Self::load_access_tuple(
2760 &tx,
2761 // This time we have to load the key by the retrieved key id, because the
2762 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002763 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002764 domain: Domain::KEY_ID,
2765 nspace: key_id,
2766 ..Default::default()
2767 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002768 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002769 caller_uid,
2770 )
2771 .context("In load_key_entry. (deferred key lock)")?;
2772 (key_id_guard, tx)
2773 }
2774 Some(l) => (l, tx),
2775 },
2776 Some(key_id_guard) => (key_id_guard, tx),
2777 };
2778
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002779 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2780 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002781
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002782 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2783
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002784 Ok((key_id_guard, key_entry))
2785 }
2786
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002787 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002788 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002789 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2790 .context("Trying to delete keyentry.")?;
2791 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2792 .context("Trying to delete keymetadata.")?;
2793 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2794 .context("Trying to delete keyparameters.")?;
2795 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2796 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002797 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002798 }
2799
2800 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002801 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002802 pub fn unbind_key(
2803 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002804 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002805 key_type: KeyType,
2806 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002807 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002808 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002809 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2810
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002811 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2812 let (key_id, access_key_descriptor, access_vector) =
2813 Self::load_access_tuple(tx, key, key_type, caller_uid)
2814 .context("Trying to get access tuple.")?;
2815
2816 // Perform access control. It is vital that we return here if the permission is denied.
2817 // So do not touch that '?' at the end.
2818 check_permission(&access_key_descriptor, access_vector)
2819 .context("While checking permission.")?;
2820
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002821 Self::mark_unreferenced(tx, key_id)
2822 .map(|need_gc| (need_gc, ()))
2823 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002824 })
2825 .context("In unbind_key.")
2826 }
2827
Max Bires8e93d2b2021-01-14 13:17:59 -08002828 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2829 tx.query_row(
2830 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2831 params![key_id],
2832 |row| row.get(0),
2833 )
2834 .context("In get_key_km_uuid.")
2835 }
2836
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002837 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2838 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2839 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002840 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2841
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002842 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2843 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2844 .context("In unbind_keys_for_namespace.");
2845 }
2846 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2847 tx.execute(
2848 "DELETE FROM persistent.keymetadata
2849 WHERE keyentryid IN (
2850 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002851 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002852 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002853 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002854 )
2855 .context("Trying to delete keymetadata.")?;
2856 tx.execute(
2857 "DELETE FROM persistent.keyparameter
2858 WHERE keyentryid IN (
2859 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002860 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002861 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002862 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002863 )
2864 .context("Trying to delete keyparameters.")?;
2865 tx.execute(
2866 "DELETE FROM persistent.grant
2867 WHERE keyentryid IN (
2868 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002869 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002870 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002871 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002872 )
2873 .context("Trying to delete grants.")?;
2874 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002875 "DELETE FROM persistent.keyentry
2876 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2877 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002878 )
2879 .context("Trying to delete keyentry.")?;
2880 Ok(()).need_gc()
2881 })
2882 .context("In unbind_keys_for_namespace")
2883 }
2884
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002885 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2886 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2887 {
2888 tx.execute(
2889 "DELETE FROM persistent.keymetadata
2890 WHERE keyentryid IN (
2891 SELECT id FROM persistent.keyentry
2892 WHERE state = ?
2893 );",
2894 params![KeyLifeCycle::Unreferenced],
2895 )
2896 .context("Trying to delete keymetadata.")?;
2897 tx.execute(
2898 "DELETE FROM persistent.keyparameter
2899 WHERE keyentryid IN (
2900 SELECT id FROM persistent.keyentry
2901 WHERE state = ?
2902 );",
2903 params![KeyLifeCycle::Unreferenced],
2904 )
2905 .context("Trying to delete keyparameters.")?;
2906 tx.execute(
2907 "DELETE FROM persistent.grant
2908 WHERE keyentryid IN (
2909 SELECT id FROM persistent.keyentry
2910 WHERE state = ?
2911 );",
2912 params![KeyLifeCycle::Unreferenced],
2913 )
2914 .context("Trying to delete grants.")?;
2915 tx.execute(
2916 "DELETE FROM persistent.keyentry
2917 WHERE state = ?;",
2918 params![KeyLifeCycle::Unreferenced],
2919 )
2920 .context("Trying to delete keyentry.")?;
2921 Result::<()>::Ok(())
2922 }
2923 .context("In cleanup_unreferenced")
2924 }
2925
Hasini Gunasingheda895552021-01-27 19:34:37 +00002926 /// Delete the keys created on behalf of the user, denoted by the user id.
2927 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2928 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2929 /// The caller of this function should notify the gc if the returned value is true.
2930 pub fn unbind_keys_for_user(
2931 &mut self,
2932 user_id: u32,
2933 keep_non_super_encrypted_keys: bool,
2934 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002935 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2936
Hasini Gunasingheda895552021-01-27 19:34:37 +00002937 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2938 let mut stmt = tx
2939 .prepare(&format!(
2940 "SELECT id from persistent.keyentry
2941 WHERE (
2942 key_type = ?
2943 AND domain = ?
2944 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2945 AND state = ?
2946 ) OR (
2947 key_type = ?
2948 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002949 AND state = ?
2950 );",
2951 aid_user_offset = AID_USER_OFFSET
2952 ))
2953 .context(concat!(
2954 "In unbind_keys_for_user. ",
2955 "Failed to prepare the query to find the keys created by apps."
2956 ))?;
2957
2958 let mut rows = stmt
2959 .query(params![
2960 // WHERE client key:
2961 KeyType::Client,
2962 Domain::APP.0 as u32,
2963 user_id,
2964 KeyLifeCycle::Live,
2965 // OR super key:
2966 KeyType::Super,
2967 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002968 KeyLifeCycle::Live
2969 ])
2970 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2971
2972 let mut key_ids: Vec<i64> = Vec::new();
2973 db_utils::with_rows_extract_all(&mut rows, |row| {
2974 key_ids
2975 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2976 Ok(())
2977 })
2978 .context("In unbind_keys_for_user.")?;
2979
2980 let mut notify_gc = false;
2981 for key_id in key_ids {
2982 if keep_non_super_encrypted_keys {
2983 // Load metadata and filter out non-super-encrypted keys.
2984 if let (_, Some((_, blob_metadata)), _, _) =
2985 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2986 .context("In unbind_keys_for_user: Trying to load blob info.")?
2987 {
2988 if blob_metadata.encrypted_by().is_none() {
2989 continue;
2990 }
2991 }
2992 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002993 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002994 .context("In unbind_keys_for_user.")?
2995 || notify_gc;
2996 }
2997 Ok(()).do_gc(notify_gc)
2998 })
2999 .context("In unbind_keys_for_user.")
3000 }
3001
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003002 fn load_key_components(
3003 tx: &Transaction,
3004 load_bits: KeyEntryLoadBits,
3005 key_id: i64,
3006 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003007 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003008
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003009 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003010 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003011
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003012 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08003013 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003014
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003015 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08003016 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003017
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003018 Ok(KeyEntry {
3019 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003020 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003021 cert: cert_blob,
3022 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003023 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003024 parameters,
3025 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003026 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003027 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003028 }
3029
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003030 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3031 /// The key descriptors will have the domain, nspace, and alias field set.
3032 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07003033 pub fn list(
3034 &mut self,
3035 domain: Domain,
3036 namespace: i64,
3037 key_type: KeyType,
3038 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003039 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3040
Janis Danisevskis66784c42021-01-27 08:40:25 -08003041 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3042 let mut stmt = tx
3043 .prepare(
3044 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07003045 WHERE domain = ?
3046 AND namespace = ?
3047 AND alias IS NOT NULL
3048 AND state = ?
3049 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003050 )
3051 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003052
Janis Danisevskis66784c42021-01-27 08:40:25 -08003053 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003054 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08003055 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003056
Janis Danisevskis66784c42021-01-27 08:40:25 -08003057 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3058 db_utils::with_rows_extract_all(&mut rows, |row| {
3059 descriptors.push(KeyDescriptor {
3060 domain,
3061 nspace: namespace,
3062 alias: Some(row.get(0).context("Trying to extract alias.")?),
3063 blob: None,
3064 });
3065 Ok(())
3066 })
3067 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003068 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003069 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003070 }
3071
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003072 /// Adds a grant to the grant table.
3073 /// Like `load_key_entry` this function loads the access tuple before
3074 /// it uses the callback for a permission check. Upon success,
3075 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3076 /// grant table. The new row will have a randomized id, which is used as
3077 /// grant id in the namespace field of the resulting KeyDescriptor.
3078 pub fn grant(
3079 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003080 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003081 caller_uid: u32,
3082 grantee_uid: u32,
3083 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003084 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003085 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003086 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3087
Janis Danisevskis66784c42021-01-27 08:40:25 -08003088 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3089 // Load the key_id and complete the access control tuple.
3090 // We ignore the access vector here because grants cannot be granted.
3091 // The access vector returned here expresses the permissions the
3092 // grantee has if key.domain == Domain::GRANT. But this vector
3093 // cannot include the grant permission by design, so there is no way the
3094 // subsequent permission check can pass.
3095 // We could check key.domain == Domain::GRANT and fail early.
3096 // But even if we load the access tuple by grant here, the permission
3097 // check denies the attempt to create a grant by grant descriptor.
3098 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003099 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003100 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101
Janis Danisevskis66784c42021-01-27 08:40:25 -08003102 // Perform access control. It is vital that we return here if the permission
3103 // was denied. So do not touch that '?' at the end of the line.
3104 // This permission check checks if the caller has the grant permission
3105 // for the given key and in addition to all of the permissions
3106 // expressed in `access_vector`.
3107 check_permission(&access_key_descriptor, &access_vector)
3108 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003109
Janis Danisevskis66784c42021-01-27 08:40:25 -08003110 let grant_id = if let Some(grant_id) = tx
3111 .query_row(
3112 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003113 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003114 params![key_id, grantee_uid],
3115 |row| row.get(0),
3116 )
3117 .optional()
3118 .context("In grant: Failed get optional existing grant id.")?
3119 {
3120 tx.execute(
3121 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003122 SET access_vector = ?
3123 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003124 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003125 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003126 .context("In grant: Failed to update existing grant.")?;
3127 grant_id
3128 } else {
3129 Self::insert_with_retry(|id| {
3130 tx.execute(
3131 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3132 VALUES (?, ?, ?, ?);",
3133 params![id, grantee_uid, key_id, i32::from(access_vector)],
3134 )
3135 })
3136 .context("In grant")?
3137 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003138
Janis Danisevskis66784c42021-01-27 08:40:25 -08003139 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003140 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003141 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003142 }
3143
3144 /// This function checks permissions like `grant` and `load_key_entry`
3145 /// before removing a grant from the grant table.
3146 pub fn ungrant(
3147 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003148 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003149 caller_uid: u32,
3150 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003151 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003152 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003153 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3154
Janis Danisevskis66784c42021-01-27 08:40:25 -08003155 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3156 // Load the key_id and complete the access control tuple.
3157 // We ignore the access vector here because grants cannot be granted.
3158 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003159 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003160 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003161
Janis Danisevskis66784c42021-01-27 08:40:25 -08003162 // Perform access control. We must return here if the permission
3163 // was denied. So do not touch the '?' at the end of this line.
3164 check_permission(&access_key_descriptor)
3165 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003166
Janis Danisevskis66784c42021-01-27 08:40:25 -08003167 tx.execute(
3168 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003169 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003170 params![key_id, grantee_uid],
3171 )
3172 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003173
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003174 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003175 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003176 }
3177
Joel Galenson845f74b2020-09-09 14:11:55 -07003178 // Generates a random id and passes it to the given function, which will
3179 // try to insert it into a database. If that insertion fails, retry;
3180 // otherwise return the id.
3181 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3182 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003183 let newid: i64 = match random() {
3184 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3185 i => i,
3186 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003187 match inserter(newid) {
3188 // If the id already existed, try again.
3189 Err(rusqlite::Error::SqliteFailure(
3190 libsqlite3_sys::Error {
3191 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3192 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3193 },
3194 _,
3195 )) => (),
3196 Err(e) => {
3197 return Err(e).context("In insert_with_retry: failed to insert into database.")
3198 }
3199 _ => return Ok(newid),
3200 }
3201 }
3202 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003203
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003204 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3205 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3206 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3207 auth_token.clone(),
3208 MonotonicRawTime::now(),
3209 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003210 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003211
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003212 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003213 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003214 where
3215 F: Fn(&AuthTokenEntry) -> bool,
3216 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003217 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003218 }
3219
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003220 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003221 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3222 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003223 }
3224
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003225 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003226 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3227 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003228 }
3229
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003230 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003231 fn get_last_off_body(&self) -> MonotonicRawTime {
3232 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003233 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003234
3235 /// Load descriptor of a key by key id
3236 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3237 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3238
3239 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3240 tx.query_row(
3241 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3242 params![key_id],
3243 |row| {
3244 Ok(KeyDescriptor {
3245 domain: Domain(row.get(0)?),
3246 nspace: row.get(1)?,
3247 alias: row.get(2)?,
3248 blob: None,
3249 })
3250 },
3251 )
3252 .optional()
3253 .context("Trying to load key descriptor")
3254 .no_gc()
3255 })
3256 .context("In load_key_descriptor.")
3257 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003258}
3259
3260#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08003261pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07003262
3263 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003264 use crate::key_parameter::{
3265 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3266 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3267 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003268 use crate::key_perm_set;
3269 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08003270 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003271 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003272 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3273 HardwareAuthToken::HardwareAuthToken,
3274 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003275 };
3276 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003277 Timestamp::Timestamp,
3278 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003279 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003280 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003281 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003282 use std::collections::BTreeMap;
3283 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003284 use std::sync::atomic::{AtomicU8, Ordering};
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003285 use std::sync::{Arc, RwLock};
Janis Danisevskisaec14592020-11-12 09:41:49 -08003286 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003287 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003288 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003289 #[cfg(disabled)]
3290 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003291
Seth Moore7ee79f92021-12-07 11:42:49 -08003292 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003293 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003294
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003295 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003296 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003297 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003298 })?;
3299 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003300 }
3301
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003302 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3303 where
3304 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3305 {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003306 let super_key: Arc<RwLock<SuperKeyManager>> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003307
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003308 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003309 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003310
Janis Danisevskis3395f862021-05-06 10:54:17 -07003311 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003312 }
3313
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003314 fn rebind_alias(
3315 db: &mut KeystoreDB,
3316 newid: &KeyIdGuard,
3317 alias: &str,
3318 domain: Domain,
3319 namespace: i64,
3320 ) -> Result<bool> {
3321 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003322 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003323 })
3324 .context("In rebind_alias.")
3325 }
3326
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003327 #[test]
3328 fn datetime() -> Result<()> {
3329 let conn = Connection::open_in_memory()?;
3330 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3331 let now = SystemTime::now();
3332 let duration = Duration::from_secs(1000);
3333 let then = now.checked_sub(duration).unwrap();
3334 let soon = now.checked_add(duration).unwrap();
3335 conn.execute(
3336 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3337 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3338 )?;
3339 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3340 let mut rows = stmt.query(NO_PARAMS)?;
3341 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3342 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3343 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3344 assert!(rows.next()?.is_none());
3345 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3346 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3347 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3348 Ok(())
3349 }
3350
Joel Galenson0891bc12020-07-20 10:37:03 -07003351 // Ensure that we're using the "injected" random function, not the real one.
3352 #[test]
3353 fn test_mocked_random() {
3354 let rand1 = random();
3355 let rand2 = random();
3356 let rand3 = random();
3357 if rand1 == rand2 {
3358 assert_eq!(rand2 + 1, rand3);
3359 } else {
3360 assert_eq!(rand1 + 1, rand2);
3361 assert_eq!(rand2, rand3);
3362 }
3363 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003364
Joel Galenson26f4d012020-07-17 14:57:21 -07003365 // Test that we have the correct tables.
3366 #[test]
3367 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003368 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003369 let tables = db
3370 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003371 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003372 .query_map(params![], |row| row.get(0))?
3373 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003374 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003375 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003376 assert_eq!(tables[1], "blobmetadata");
3377 assert_eq!(tables[2], "grant");
3378 assert_eq!(tables[3], "keyentry");
3379 assert_eq!(tables[4], "keymetadata");
3380 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003381 Ok(())
3382 }
3383
3384 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003385 fn test_auth_token_table_invariant() -> Result<()> {
3386 let mut db = new_test_db()?;
3387 let auth_token1 = 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: 500 },
3393 mac: String::from("mac").into_bytes(),
3394 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003395 db.insert_auth_token(&auth_token1);
3396 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003397 assert_eq!(auth_tokens_returned.len(), 1);
3398
3399 // insert another auth token with the same values for the columns in the UNIQUE constraint
3400 // of the auth token table and different value for timestamp
3401 let auth_token2 = HardwareAuthToken {
3402 challenge: i64::MAX,
3403 userId: 200,
3404 authenticatorId: 200,
3405 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3406 timestamp: Timestamp { milliSeconds: 600 },
3407 mac: String::from("mac").into_bytes(),
3408 };
3409
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003410 db.insert_auth_token(&auth_token2);
3411 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003412 assert_eq!(auth_tokens_returned.len(), 1);
3413
3414 if let Some(auth_token) = auth_tokens_returned.pop() {
3415 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3416 }
3417
3418 // insert another auth token with the different values for the columns in the UNIQUE
3419 // constraint of the auth token table
3420 let auth_token3 = HardwareAuthToken {
3421 challenge: i64::MAX,
3422 userId: 201,
3423 authenticatorId: 200,
3424 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3425 timestamp: Timestamp { milliSeconds: 600 },
3426 mac: String::from("mac").into_bytes(),
3427 };
3428
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003429 db.insert_auth_token(&auth_token3);
3430 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003431 assert_eq!(auth_tokens_returned.len(), 2);
3432
3433 Ok(())
3434 }
3435
3436 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003437 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3438 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003439 }
3440
3441 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003442 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003443 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003444 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003445
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003446 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003447 let entries = get_keyentry(&db)?;
3448 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003449
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003450 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003451
3452 let entries_new = get_keyentry(&db)?;
3453 assert_eq!(entries, entries_new);
3454 Ok(())
3455 }
3456
3457 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003458 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003459 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3460 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003461 }
3462
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003463 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003464
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003465 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3466 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003467
3468 let entries = get_keyentry(&db)?;
3469 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003470 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3471 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003472
3473 // Test that we must pass in a valid Domain.
3474 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003475 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003476 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003477 );
3478 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003479 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003480 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003481 );
3482 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003483 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003484 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003485 );
3486
3487 Ok(())
3488 }
3489
Joel Galenson33c04ad2020-08-03 11:04:38 -07003490 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003491 fn test_add_unsigned_key() -> Result<()> {
3492 let mut db = new_test_db()?;
3493 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3494 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3495 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3496 db.create_attestation_key_entry(
3497 &public_key,
3498 &raw_public_key,
3499 &private_key,
3500 &KEYSTORE_UUID,
3501 )?;
3502 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3503 assert_eq!(keys.len(), 1);
3504 assert_eq!(keys[0], public_key);
3505 Ok(())
3506 }
3507
3508 #[test]
3509 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3510 let mut db = new_test_db()?;
3511 let expiration_date: i64 = 20;
3512 let namespace: i64 = 30;
3513 let base_byte: u8 = 1;
3514 let loaded_values =
3515 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3516 let chain =
3517 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Chris Wailes3877f292021-07-26 19:24:18 -07003518 assert!(chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003519 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003520 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003521 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3522 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003523 Ok(())
3524 }
3525
3526 #[test]
3527 fn test_get_attestation_pool_status() -> Result<()> {
3528 let mut db = new_test_db()?;
3529 let namespace: i64 = 30;
3530 load_attestation_key_pool(
3531 &mut db, 10, /* expiration */
3532 namespace, 0x01, /* base_byte */
3533 )?;
3534 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3535 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3536 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3537 assert_eq!(status.expiring, 0);
3538 assert_eq!(status.attested, 3);
3539 assert_eq!(status.unassigned, 0);
3540 assert_eq!(status.total, 3);
3541 assert_eq!(
3542 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3543 1
3544 );
3545 assert_eq!(
3546 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3547 2
3548 );
3549 assert_eq!(
3550 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3551 3
3552 );
3553 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3554 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3555 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3556 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003557 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003558 db.create_attestation_key_entry(
3559 &public_key,
3560 &raw_public_key,
3561 &private_key,
3562 &KEYSTORE_UUID,
3563 )?;
3564 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3565 assert_eq!(status.attested, 3);
3566 assert_eq!(status.unassigned, 0);
3567 assert_eq!(status.total, 4);
3568 db.store_signed_attestation_certificate_chain(
3569 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003570 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003571 &cert_chain,
3572 20,
3573 &KEYSTORE_UUID,
3574 )?;
3575 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3576 assert_eq!(status.attested, 4);
3577 assert_eq!(status.unassigned, 1);
3578 assert_eq!(status.total, 4);
3579 Ok(())
3580 }
3581
3582 #[test]
3583 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003584 let temp_dir =
3585 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3586 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003587 let expiration_date: i64 =
3588 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3589 let namespace: i64 = 30;
3590 let namespace_del1: i64 = 45;
3591 let namespace_del2: i64 = 60;
3592 let entry_values = load_attestation_key_pool(
3593 &mut db,
3594 expiration_date,
3595 namespace,
3596 0x01, /* base_byte */
3597 )?;
3598 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3599 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003600
3601 let blob_entry_row_count: u32 = db
3602 .conn
3603 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3604 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003605 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3606 // one key, one certificate chain, and one certificate.
3607 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003608
Max Bires2b2e6562020-09-22 11:22:36 -07003609 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3610
3611 let mut cert_chain =
3612 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003613 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003614 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003615 assert_eq!(entry_values.batch_cert, value.batch_cert);
3616 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003617 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003618
3619 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3620 Domain::APP,
3621 namespace_del1,
3622 &KEYSTORE_UUID,
3623 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003624 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003625 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3626 Domain::APP,
3627 namespace_del2,
3628 &KEYSTORE_UUID,
3629 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003630 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003631
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003632 // Give the garbage collector half a second to catch up.
3633 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003634
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003635 let blob_entry_row_count: u32 = db
3636 .conn
3637 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3638 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003639 // There shound be 3 blob entries left, because we deleted two of the attestation
3640 // key entries with three blobs each.
3641 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003642
Max Bires2b2e6562020-09-22 11:22:36 -07003643 Ok(())
3644 }
3645
3646 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003647 fn test_delete_all_attestation_keys() -> Result<()> {
3648 let mut db = new_test_db()?;
3649 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3650 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003651 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003652 let result = db.delete_all_attestation_keys()?;
3653
3654 // Give the garbage collector half a second to catch up.
3655 std::thread::sleep(Duration::from_millis(500));
3656
3657 // Attestation keys should be deleted, and the regular key should remain.
3658 assert_eq!(result, 2);
3659
3660 Ok(())
3661 }
3662
3663 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003664 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003665 fn extractor(
3666 ke: &KeyEntryRow,
3667 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3668 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003669 }
3670
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003671 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003672 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3673 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003674 let entries = get_keyentry(&db)?;
3675 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003676 assert_eq!(
3677 extractor(&entries[0]),
3678 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3679 );
3680 assert_eq!(
3681 extractor(&entries[1]),
3682 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3683 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003684
3685 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003686 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003687 let entries = get_keyentry(&db)?;
3688 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003689 assert_eq!(
3690 extractor(&entries[0]),
3691 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3692 );
3693 assert_eq!(
3694 extractor(&entries[1]),
3695 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3696 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003697
3698 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003699 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003700 let entries = get_keyentry(&db)?;
3701 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003702 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3703 assert_eq!(
3704 extractor(&entries[1]),
3705 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3706 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003707
3708 // Test that we must pass in a valid Domain.
3709 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003710 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003711 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003712 );
3713 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003714 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003715 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003716 );
3717 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003718 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003719 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003720 );
3721
3722 // Test that we correctly handle setting an alias for something that does not exist.
3723 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003724 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003725 "Expected to update a single entry but instead updated 0",
3726 );
3727 // Test that we correctly abort the transaction in this case.
3728 let entries = get_keyentry(&db)?;
3729 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003730 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3731 assert_eq!(
3732 extractor(&entries[1]),
3733 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3734 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003735
3736 Ok(())
3737 }
3738
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003739 #[test]
3740 fn test_grant_ungrant() -> Result<()> {
3741 const CALLER_UID: u32 = 15;
3742 const GRANTEE_UID: u32 = 12;
3743 const SELINUX_NAMESPACE: i64 = 7;
3744
3745 let mut db = new_test_db()?;
3746 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003747 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3748 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3749 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003750 )?;
3751 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003752 domain: super::Domain::APP,
3753 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003754 alias: Some("key".to_string()),
3755 blob: None,
3756 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003757 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3758 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003759
3760 // Reset totally predictable random number generator in case we
3761 // are not the first test running on this thread.
3762 reset_random();
3763 let next_random = 0i64;
3764
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003765 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003766 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003767 assert_eq!(*a, PVEC1);
3768 assert_eq!(
3769 *k,
3770 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003771 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003772 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003773 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003774 alias: Some("key".to_string()),
3775 blob: None,
3776 }
3777 );
3778 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003779 })
3780 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003781
3782 assert_eq!(
3783 app_granted_key,
3784 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003785 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003786 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003787 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003788 alias: None,
3789 blob: None,
3790 }
3791 );
3792
3793 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003794 domain: super::Domain::SELINUX,
3795 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003796 alias: Some("yek".to_string()),
3797 blob: None,
3798 };
3799
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003800 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003801 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003802 assert_eq!(*a, PVEC1);
3803 assert_eq!(
3804 *k,
3805 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003806 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003807 // namespace must be the supplied SELinux
3808 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003809 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003810 alias: Some("yek".to_string()),
3811 blob: None,
3812 }
3813 );
3814 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003815 })
3816 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003817
3818 assert_eq!(
3819 selinux_granted_key,
3820 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003821 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003822 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003823 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003824 alias: None,
3825 blob: None,
3826 }
3827 );
3828
3829 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003830 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003831 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003832 assert_eq!(*a, PVEC2);
3833 assert_eq!(
3834 *k,
3835 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003836 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003837 // namespace must be the supplied SELinux
3838 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003839 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003840 alias: Some("yek".to_string()),
3841 blob: None,
3842 }
3843 );
3844 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003845 })
3846 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003847
3848 assert_eq!(
3849 selinux_granted_key,
3850 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003851 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003852 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003853 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003854 alias: None,
3855 blob: None,
3856 }
3857 );
3858
3859 {
3860 // Limiting scope of stmt, because it borrows db.
3861 let mut stmt = db
3862 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003863 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003864 let mut rows =
3865 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3866 Ok((
3867 row.get(0)?,
3868 row.get(1)?,
3869 row.get(2)?,
3870 KeyPermSet::from(row.get::<_, i32>(3)?),
3871 ))
3872 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003873
3874 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003875 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003876 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003877 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003878 assert!(rows.next().is_none());
3879 }
3880
3881 debug_dump_keyentry_table(&mut db)?;
3882 println!("app_key {:?}", app_key);
3883 println!("selinux_key {:?}", selinux_key);
3884
Janis Danisevskis66784c42021-01-27 08:40:25 -08003885 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3886 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003887
3888 Ok(())
3889 }
3890
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003891 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003892 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3893 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3894
3895 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003896 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003897 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003898 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003899 let mut blob_metadata = BlobMetaData::new();
3900 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3901 db.set_blob(
3902 &key_id,
3903 SubComponentType::KEY_BLOB,
3904 Some(TEST_KEY_BLOB),
3905 Some(&blob_metadata),
3906 )?;
3907 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3908 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003909 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003910
3911 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003912 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003913 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003914 )?;
3915 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003916 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3917 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003918 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003919 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003920 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003921 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003922 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003923 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003924 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003925
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003926 drop(rows);
3927 drop(stmt);
3928
3929 assert_eq!(
3930 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3931 BlobMetaData::load_from_db(id, tx).no_gc()
3932 })
3933 .expect("Should find blob metadata."),
3934 blob_metadata
3935 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003936 Ok(())
3937 }
3938
3939 static TEST_ALIAS: &str = "my super duper key";
3940
3941 #[test]
3942 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3943 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003944 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003945 .context("test_insert_and_load_full_keyentry_domain_app")?
3946 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003947 let (_key_guard, key_entry) = db
3948 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003949 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003950 domain: Domain::APP,
3951 nspace: 0,
3952 alias: Some(TEST_ALIAS.to_string()),
3953 blob: None,
3954 },
3955 KeyType::Client,
3956 KeyEntryLoadBits::BOTH,
3957 1,
3958 |_k, _av| Ok(()),
3959 )
3960 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003961 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003962
3963 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003964 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003965 domain: Domain::APP,
3966 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003967 alias: Some(TEST_ALIAS.to_string()),
3968 blob: None,
3969 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003970 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003971 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003972 |_, _| Ok(()),
3973 )
3974 .unwrap();
3975
3976 assert_eq!(
3977 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3978 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003979 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003980 domain: Domain::APP,
3981 nspace: 0,
3982 alias: Some(TEST_ALIAS.to_string()),
3983 blob: None,
3984 },
3985 KeyType::Client,
3986 KeyEntryLoadBits::NONE,
3987 1,
3988 |_k, _av| Ok(()),
3989 )
3990 .unwrap_err()
3991 .root_cause()
3992 .downcast_ref::<KsError>()
3993 );
3994
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003995 Ok(())
3996 }
3997
3998 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003999 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4000 let mut db = new_test_db()?;
4001
4002 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004003 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004004 domain: Domain::APP,
4005 nspace: 1,
4006 alias: Some(TEST_ALIAS.to_string()),
4007 blob: None,
4008 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004009 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004010 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004011 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004012 )
4013 .expect("Trying to insert cert.");
4014
4015 let (_key_guard, mut key_entry) = db
4016 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004017 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004018 domain: Domain::APP,
4019 nspace: 1,
4020 alias: Some(TEST_ALIAS.to_string()),
4021 blob: None,
4022 },
4023 KeyType::Client,
4024 KeyEntryLoadBits::PUBLIC,
4025 1,
4026 |_k, _av| Ok(()),
4027 )
4028 .expect("Trying to read certificate entry.");
4029
4030 assert!(key_entry.pure_cert());
4031 assert!(key_entry.cert().is_none());
4032 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4033
4034 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004035 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004036 domain: Domain::APP,
4037 nspace: 1,
4038 alias: Some(TEST_ALIAS.to_string()),
4039 blob: None,
4040 },
4041 KeyType::Client,
4042 1,
4043 |_, _| Ok(()),
4044 )
4045 .unwrap();
4046
4047 assert_eq!(
4048 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4049 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004050 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004051 domain: Domain::APP,
4052 nspace: 1,
4053 alias: Some(TEST_ALIAS.to_string()),
4054 blob: None,
4055 },
4056 KeyType::Client,
4057 KeyEntryLoadBits::NONE,
4058 1,
4059 |_k, _av| Ok(()),
4060 )
4061 .unwrap_err()
4062 .root_cause()
4063 .downcast_ref::<KsError>()
4064 );
4065
4066 Ok(())
4067 }
4068
4069 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004070 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4071 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004072 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004073 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4074 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004075 let (_key_guard, key_entry) = db
4076 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004077 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004078 domain: Domain::SELINUX,
4079 nspace: 1,
4080 alias: Some(TEST_ALIAS.to_string()),
4081 blob: None,
4082 },
4083 KeyType::Client,
4084 KeyEntryLoadBits::BOTH,
4085 1,
4086 |_k, _av| Ok(()),
4087 )
4088 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004089 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004090
4091 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004092 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004093 domain: Domain::SELINUX,
4094 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004095 alias: Some(TEST_ALIAS.to_string()),
4096 blob: None,
4097 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004098 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004099 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004100 |_, _| Ok(()),
4101 )
4102 .unwrap();
4103
4104 assert_eq!(
4105 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4106 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004107 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004108 domain: Domain::SELINUX,
4109 nspace: 1,
4110 alias: Some(TEST_ALIAS.to_string()),
4111 blob: None,
4112 },
4113 KeyType::Client,
4114 KeyEntryLoadBits::NONE,
4115 1,
4116 |_k, _av| Ok(()),
4117 )
4118 .unwrap_err()
4119 .root_cause()
4120 .downcast_ref::<KsError>()
4121 );
4122
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004123 Ok(())
4124 }
4125
4126 #[test]
4127 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4128 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004129 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004130 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4131 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004132 let (_, key_entry) = db
4133 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004134 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004135 KeyType::Client,
4136 KeyEntryLoadBits::BOTH,
4137 1,
4138 |_k, _av| Ok(()),
4139 )
4140 .unwrap();
4141
Qi Wub9433b52020-12-01 14:52:46 +08004142 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004143
4144 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004145 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004146 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004147 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004148 |_, _| Ok(()),
4149 )
4150 .unwrap();
4151
4152 assert_eq!(
4153 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4154 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004155 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004156 KeyType::Client,
4157 KeyEntryLoadBits::NONE,
4158 1,
4159 |_k, _av| Ok(()),
4160 )
4161 .unwrap_err()
4162 .root_cause()
4163 .downcast_ref::<KsError>()
4164 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004165
4166 Ok(())
4167 }
4168
4169 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004170 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4171 let mut db = new_test_db()?;
4172 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4173 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4174 .0;
4175 // Update the usage count of the limited use key.
4176 db.check_and_update_key_usage_count(key_id)?;
4177
4178 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004179 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004180 KeyType::Client,
4181 KeyEntryLoadBits::BOTH,
4182 1,
4183 |_k, _av| Ok(()),
4184 )?;
4185
4186 // The usage count is decremented now.
4187 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4188
4189 Ok(())
4190 }
4191
4192 #[test]
4193 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4194 let mut db = new_test_db()?;
4195 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4196 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4197 .0;
4198 // Update the usage count of the limited use key.
4199 db.check_and_update_key_usage_count(key_id).expect(concat!(
4200 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4201 "This should succeed."
4202 ));
4203
4204 // Try to update the exhausted limited use key.
4205 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4206 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4207 "This should fail."
4208 ));
4209 assert_eq!(
4210 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4211 e.root_cause().downcast_ref::<KsError>().unwrap()
4212 );
4213
4214 Ok(())
4215 }
4216
4217 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004218 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4219 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004220 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004221 .context("test_insert_and_load_full_keyentry_from_grant")?
4222 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004223
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004224 let granted_key = db
4225 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004226 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004227 domain: Domain::APP,
4228 nspace: 0,
4229 alias: Some(TEST_ALIAS.to_string()),
4230 blob: None,
4231 },
4232 1,
4233 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004234 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004235 |_k, _av| Ok(()),
4236 )
4237 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004238
4239 debug_dump_grant_table(&mut db)?;
4240
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004241 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004242 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4243 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004244 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08004245 Ok(())
4246 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004247 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004248
Qi Wub9433b52020-12-01 14:52:46 +08004249 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004250
Janis Danisevskis66784c42021-01-27 08:40:25 -08004251 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004252
4253 assert_eq!(
4254 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4255 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004256 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004257 KeyType::Client,
4258 KeyEntryLoadBits::NONE,
4259 2,
4260 |_k, _av| Ok(()),
4261 )
4262 .unwrap_err()
4263 .root_cause()
4264 .downcast_ref::<KsError>()
4265 );
4266
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004267 Ok(())
4268 }
4269
Janis Danisevskis45760022021-01-19 16:34:10 -08004270 // This test attempts to load a key by key id while the caller is not the owner
4271 // but a grant exists for the given key and the caller.
4272 #[test]
4273 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4274 let mut db = new_test_db()?;
4275 const OWNER_UID: u32 = 1u32;
4276 const GRANTEE_UID: u32 = 2u32;
4277 const SOMEONE_ELSE_UID: u32 = 3u32;
4278 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4279 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4280 .0;
4281
4282 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004283 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004284 domain: Domain::APP,
4285 nspace: 0,
4286 alias: Some(TEST_ALIAS.to_string()),
4287 blob: None,
4288 },
4289 OWNER_UID,
4290 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004291 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08004292 |_k, _av| Ok(()),
4293 )
4294 .unwrap();
4295
4296 debug_dump_grant_table(&mut db)?;
4297
4298 let id_descriptor =
4299 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4300
4301 let (_, key_entry) = db
4302 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004303 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004304 KeyType::Client,
4305 KeyEntryLoadBits::BOTH,
4306 GRANTEE_UID,
4307 |k, av| {
4308 assert_eq!(Domain::APP, k.domain);
4309 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004310 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08004311 Ok(())
4312 },
4313 )
4314 .unwrap();
4315
4316 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4317
4318 let (_, key_entry) = db
4319 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004320 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004321 KeyType::Client,
4322 KeyEntryLoadBits::BOTH,
4323 SOMEONE_ELSE_UID,
4324 |k, av| {
4325 assert_eq!(Domain::APP, k.domain);
4326 assert_eq!(OWNER_UID as i64, k.nspace);
4327 assert!(av.is_none());
4328 Ok(())
4329 },
4330 )
4331 .unwrap();
4332
4333 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4334
Janis Danisevskis66784c42021-01-27 08:40:25 -08004335 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004336
4337 assert_eq!(
4338 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4339 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004340 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004341 KeyType::Client,
4342 KeyEntryLoadBits::NONE,
4343 GRANTEE_UID,
4344 |_k, _av| Ok(()),
4345 )
4346 .unwrap_err()
4347 .root_cause()
4348 .downcast_ref::<KsError>()
4349 );
4350
4351 Ok(())
4352 }
4353
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004354 // Creates a key migrates it to a different location and then tries to access it by the old
4355 // and new location.
4356 #[test]
4357 fn test_migrate_key_app_to_app() -> Result<()> {
4358 let mut db = new_test_db()?;
4359 const SOURCE_UID: u32 = 1u32;
4360 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004361 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4362 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004363 let key_id_guard =
4364 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4365 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4366
4367 let source_descriptor: KeyDescriptor = KeyDescriptor {
4368 domain: Domain::APP,
4369 nspace: -1,
4370 alias: Some(SOURCE_ALIAS.to_string()),
4371 blob: None,
4372 };
4373
4374 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4375 domain: Domain::APP,
4376 nspace: -1,
4377 alias: Some(DESTINATION_ALIAS.to_string()),
4378 blob: None,
4379 };
4380
4381 let key_id = key_id_guard.id();
4382
4383 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4384 Ok(())
4385 })
4386 .unwrap();
4387
4388 let (_, key_entry) = db
4389 .load_key_entry(
4390 &destination_descriptor,
4391 KeyType::Client,
4392 KeyEntryLoadBits::BOTH,
4393 DESTINATION_UID,
4394 |k, av| {
4395 assert_eq!(Domain::APP, k.domain);
4396 assert_eq!(DESTINATION_UID as i64, k.nspace);
4397 assert!(av.is_none());
4398 Ok(())
4399 },
4400 )
4401 .unwrap();
4402
4403 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4404
4405 assert_eq!(
4406 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4407 db.load_key_entry(
4408 &source_descriptor,
4409 KeyType::Client,
4410 KeyEntryLoadBits::NONE,
4411 SOURCE_UID,
4412 |_k, _av| Ok(()),
4413 )
4414 .unwrap_err()
4415 .root_cause()
4416 .downcast_ref::<KsError>()
4417 );
4418
4419 Ok(())
4420 }
4421
4422 // Creates a key migrates it to a different location and then tries to access it by the old
4423 // and new location.
4424 #[test]
4425 fn test_migrate_key_app_to_selinux() -> Result<()> {
4426 let mut db = new_test_db()?;
4427 const SOURCE_UID: u32 = 1u32;
4428 const DESTINATION_UID: u32 = 2u32;
4429 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004430 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4431 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004432 let key_id_guard =
4433 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4434 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4435
4436 let source_descriptor: KeyDescriptor = KeyDescriptor {
4437 domain: Domain::APP,
4438 nspace: -1,
4439 alias: Some(SOURCE_ALIAS.to_string()),
4440 blob: None,
4441 };
4442
4443 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4444 domain: Domain::SELINUX,
4445 nspace: DESTINATION_NAMESPACE,
4446 alias: Some(DESTINATION_ALIAS.to_string()),
4447 blob: None,
4448 };
4449
4450 let key_id = key_id_guard.id();
4451
4452 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4453 Ok(())
4454 })
4455 .unwrap();
4456
4457 let (_, key_entry) = db
4458 .load_key_entry(
4459 &destination_descriptor,
4460 KeyType::Client,
4461 KeyEntryLoadBits::BOTH,
4462 DESTINATION_UID,
4463 |k, av| {
4464 assert_eq!(Domain::SELINUX, k.domain);
4465 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4466 assert!(av.is_none());
4467 Ok(())
4468 },
4469 )
4470 .unwrap();
4471
4472 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4473
4474 assert_eq!(
4475 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4476 db.load_key_entry(
4477 &source_descriptor,
4478 KeyType::Client,
4479 KeyEntryLoadBits::NONE,
4480 SOURCE_UID,
4481 |_k, _av| Ok(()),
4482 )
4483 .unwrap_err()
4484 .root_cause()
4485 .downcast_ref::<KsError>()
4486 );
4487
4488 Ok(())
4489 }
4490
4491 // Creates two keys and tries to migrate the first to the location of the second which
4492 // is expected to fail.
4493 #[test]
4494 fn test_migrate_key_destination_occupied() -> Result<()> {
4495 let mut db = new_test_db()?;
4496 const SOURCE_UID: u32 = 1u32;
4497 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004498 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4499 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004500 let key_id_guard =
4501 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4502 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4503 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4504 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4505
4506 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4507 domain: Domain::APP,
4508 nspace: -1,
4509 alias: Some(DESTINATION_ALIAS.to_string()),
4510 blob: None,
4511 };
4512
4513 assert_eq!(
4514 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4515 db.migrate_key_namespace(
4516 key_id_guard,
4517 &destination_descriptor,
4518 DESTINATION_UID,
4519 |_k| Ok(())
4520 )
4521 .unwrap_err()
4522 .root_cause()
4523 .downcast_ref::<KsError>()
4524 );
4525
4526 Ok(())
4527 }
4528
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004529 #[test]
4530 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004531 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4532 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4533 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004534 const UID: u32 = 33;
4535 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4536 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4537 let key_id_untouched1 =
4538 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4539 let key_id_untouched2 =
4540 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4541 let key_id_deleted =
4542 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4543
4544 let (_, key_entry) = db
4545 .load_key_entry(
4546 &KeyDescriptor {
4547 domain: Domain::APP,
4548 nspace: -1,
4549 alias: Some(ALIAS1.to_string()),
4550 blob: None,
4551 },
4552 KeyType::Client,
4553 KeyEntryLoadBits::BOTH,
4554 UID,
4555 |k, av| {
4556 assert_eq!(Domain::APP, k.domain);
4557 assert_eq!(UID as i64, k.nspace);
4558 assert!(av.is_none());
4559 Ok(())
4560 },
4561 )
4562 .unwrap();
4563 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4564 let (_, key_entry) = db
4565 .load_key_entry(
4566 &KeyDescriptor {
4567 domain: Domain::APP,
4568 nspace: -1,
4569 alias: Some(ALIAS2.to_string()),
4570 blob: None,
4571 },
4572 KeyType::Client,
4573 KeyEntryLoadBits::BOTH,
4574 UID,
4575 |k, av| {
4576 assert_eq!(Domain::APP, k.domain);
4577 assert_eq!(UID as i64, k.nspace);
4578 assert!(av.is_none());
4579 Ok(())
4580 },
4581 )
4582 .unwrap();
4583 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4584 let (_, key_entry) = db
4585 .load_key_entry(
4586 &KeyDescriptor {
4587 domain: Domain::APP,
4588 nspace: -1,
4589 alias: Some(ALIAS3.to_string()),
4590 blob: None,
4591 },
4592 KeyType::Client,
4593 KeyEntryLoadBits::BOTH,
4594 UID,
4595 |k, av| {
4596 assert_eq!(Domain::APP, k.domain);
4597 assert_eq!(UID as i64, k.nspace);
4598 assert!(av.is_none());
4599 Ok(())
4600 },
4601 )
4602 .unwrap();
4603 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4604
4605 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4606 KeystoreDB::from_0_to_1(tx).no_gc()
4607 })
4608 .unwrap();
4609
4610 let (_, key_entry) = db
4611 .load_key_entry(
4612 &KeyDescriptor {
4613 domain: Domain::APP,
4614 nspace: -1,
4615 alias: Some(ALIAS1.to_string()),
4616 blob: None,
4617 },
4618 KeyType::Client,
4619 KeyEntryLoadBits::BOTH,
4620 UID,
4621 |k, av| {
4622 assert_eq!(Domain::APP, k.domain);
4623 assert_eq!(UID as i64, k.nspace);
4624 assert!(av.is_none());
4625 Ok(())
4626 },
4627 )
4628 .unwrap();
4629 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4630 let (_, key_entry) = db
4631 .load_key_entry(
4632 &KeyDescriptor {
4633 domain: Domain::APP,
4634 nspace: -1,
4635 alias: Some(ALIAS2.to_string()),
4636 blob: None,
4637 },
4638 KeyType::Client,
4639 KeyEntryLoadBits::BOTH,
4640 UID,
4641 |k, av| {
4642 assert_eq!(Domain::APP, k.domain);
4643 assert_eq!(UID as i64, k.nspace);
4644 assert!(av.is_none());
4645 Ok(())
4646 },
4647 )
4648 .unwrap();
4649 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4650 assert_eq!(
4651 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4652 db.load_key_entry(
4653 &KeyDescriptor {
4654 domain: Domain::APP,
4655 nspace: -1,
4656 alias: Some(ALIAS3.to_string()),
4657 blob: None,
4658 },
4659 KeyType::Client,
4660 KeyEntryLoadBits::BOTH,
4661 UID,
4662 |k, av| {
4663 assert_eq!(Domain::APP, k.domain);
4664 assert_eq!(UID as i64, k.nspace);
4665 assert!(av.is_none());
4666 Ok(())
4667 },
4668 )
4669 .unwrap_err()
4670 .root_cause()
4671 .downcast_ref::<KsError>()
4672 );
4673 }
4674
Janis Danisevskisaec14592020-11-12 09:41:49 -08004675 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4676
Janis Danisevskisaec14592020-11-12 09:41:49 -08004677 #[test]
4678 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4679 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004680 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4681 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004682 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004683 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004684 .context("test_insert_and_load_full_keyentry_domain_app")?
4685 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004686 let (_key_guard, key_entry) = db
4687 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004688 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004689 domain: Domain::APP,
4690 nspace: 0,
4691 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4692 blob: None,
4693 },
4694 KeyType::Client,
4695 KeyEntryLoadBits::BOTH,
4696 33,
4697 |_k, _av| Ok(()),
4698 )
4699 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004700 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004701 let state = Arc::new(AtomicU8::new(1));
4702 let state2 = state.clone();
4703
4704 // Spawning a second thread that attempts to acquire the key id lock
4705 // for the same key as the primary thread. The primary thread then
4706 // waits, thereby forcing the secondary thread into the second stage
4707 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4708 // The test succeeds if the secondary thread observes the transition
4709 // of `state` from 1 to 2, despite having a whole second to overtake
4710 // the primary thread.
4711 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004712 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004713 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004714 assert!(db
4715 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004716 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004717 domain: Domain::APP,
4718 nspace: 0,
4719 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4720 blob: None,
4721 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004722 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004723 KeyEntryLoadBits::BOTH,
4724 33,
4725 |_k, _av| Ok(()),
4726 )
4727 .is_ok());
4728 // We should only see a 2 here because we can only return
4729 // from load_key_entry when the `_key_guard` expires,
4730 // which happens at the end of the scope.
4731 assert_eq!(2, state2.load(Ordering::Relaxed));
4732 });
4733
4734 thread::sleep(std::time::Duration::from_millis(1000));
4735
4736 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4737
4738 // Return the handle from this scope so we can join with the
4739 // secondary thread after the key id lock has expired.
4740 handle
4741 // This is where the `_key_guard` goes out of scope,
4742 // which is the reason for concurrent load_key_entry on the same key
4743 // to unblock.
4744 };
4745 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4746 // main test thread. We will not see failing asserts in secondary threads otherwise.
4747 handle.join().unwrap();
4748 Ok(())
4749 }
4750
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004751 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004752 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004753 let temp_dir =
4754 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4755
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004756 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4757 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004758
4759 let _tx1 = db1
4760 .conn
4761 .transaction_with_behavior(TransactionBehavior::Immediate)
4762 .expect("Failed to create first transaction.");
4763
4764 let error = db2
4765 .conn
4766 .transaction_with_behavior(TransactionBehavior::Immediate)
4767 .context("Transaction begin failed.")
4768 .expect_err("This should fail.");
4769 let root_cause = error.root_cause();
4770 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4771 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4772 {
4773 return;
4774 }
4775 panic!(
4776 "Unexpected error {:?} \n{:?} \n{:?}",
4777 error,
4778 root_cause,
4779 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4780 )
4781 }
4782
4783 #[cfg(disabled)]
4784 #[test]
4785 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4786 let temp_dir = Arc::new(
4787 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4788 .expect("Failed to create temp dir."),
4789 );
4790
4791 let test_begin = Instant::now();
4792
Janis Danisevskis66784c42021-01-27 08:40:25 -08004793 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004794 let mut db =
4795 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004796 const OPEN_DB_COUNT: u32 = 50u32;
4797
4798 let mut actual_key_count = KEY_COUNT;
4799 // First insert KEY_COUNT keys.
4800 for count in 0..KEY_COUNT {
4801 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4802 actual_key_count = count;
4803 break;
4804 }
4805 let alias = format!("test_alias_{}", count);
4806 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4807 .expect("Failed to make key entry.");
4808 }
4809
4810 // Insert more keys from a different thread and into a different namespace.
4811 let temp_dir1 = temp_dir.clone();
4812 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004813 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4814 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004815
4816 for count in 0..actual_key_count {
4817 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4818 return;
4819 }
4820 let alias = format!("test_alias_{}", count);
4821 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4822 .expect("Failed to make key entry.");
4823 }
4824
4825 // then unbind them again.
4826 for count in 0..actual_key_count {
4827 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4828 return;
4829 }
4830 let key = KeyDescriptor {
4831 domain: Domain::APP,
4832 nspace: -1,
4833 alias: Some(format!("test_alias_{}", count)),
4834 blob: None,
4835 };
4836 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4837 }
4838 });
4839
4840 // And start unbinding the first set of keys.
4841 let temp_dir2 = temp_dir.clone();
4842 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004843 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4844 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004845
4846 for count in 0..actual_key_count {
4847 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4848 return;
4849 }
4850 let key = KeyDescriptor {
4851 domain: Domain::APP,
4852 nspace: -1,
4853 alias: Some(format!("test_alias_{}", count)),
4854 blob: None,
4855 };
4856 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4857 }
4858 });
4859
Janis Danisevskis66784c42021-01-27 08:40:25 -08004860 // While a lot of inserting and deleting is going on we have to open database connections
4861 // successfully and use them.
4862 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4863 // out of scope.
4864 #[allow(clippy::redundant_clone)]
4865 let temp_dir4 = temp_dir.clone();
4866 let handle4 = thread::spawn(move || {
4867 for count in 0..OPEN_DB_COUNT {
4868 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4869 return;
4870 }
Seth Moore444b51a2021-06-11 09:49:49 -07004871 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4872 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004873
4874 let alias = format!("test_alias_{}", count);
4875 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4876 .expect("Failed to make key entry.");
4877 let key = KeyDescriptor {
4878 domain: Domain::APP,
4879 nspace: -1,
4880 alias: Some(alias),
4881 blob: None,
4882 };
4883 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4884 }
4885 });
4886
4887 handle1.join().expect("Thread 1 panicked.");
4888 handle2.join().expect("Thread 2 panicked.");
4889 handle4.join().expect("Thread 4 panicked.");
4890
Janis Danisevskis66784c42021-01-27 08:40:25 -08004891 Ok(())
4892 }
4893
4894 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004895 fn list() -> Result<()> {
4896 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004897 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004898 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4899 (Domain::APP, 1, "test1"),
4900 (Domain::APP, 1, "test2"),
4901 (Domain::APP, 1, "test3"),
4902 (Domain::APP, 1, "test4"),
4903 (Domain::APP, 1, "test5"),
4904 (Domain::APP, 1, "test6"),
4905 (Domain::APP, 1, "test7"),
4906 (Domain::APP, 2, "test1"),
4907 (Domain::APP, 2, "test2"),
4908 (Domain::APP, 2, "test3"),
4909 (Domain::APP, 2, "test4"),
4910 (Domain::APP, 2, "test5"),
4911 (Domain::APP, 2, "test6"),
4912 (Domain::APP, 2, "test8"),
4913 (Domain::SELINUX, 100, "test1"),
4914 (Domain::SELINUX, 100, "test2"),
4915 (Domain::SELINUX, 100, "test3"),
4916 (Domain::SELINUX, 100, "test4"),
4917 (Domain::SELINUX, 100, "test5"),
4918 (Domain::SELINUX, 100, "test6"),
4919 (Domain::SELINUX, 100, "test9"),
4920 ];
4921
4922 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4923 .iter()
4924 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004925 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4926 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004927 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4928 });
4929 (entry.id(), *ns)
4930 })
4931 .collect();
4932
4933 for (domain, namespace) in
4934 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4935 {
4936 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4937 .iter()
4938 .filter_map(|(domain, ns, alias)| match ns {
4939 ns if *ns == *namespace => Some(KeyDescriptor {
4940 domain: *domain,
4941 nspace: *ns,
4942 alias: Some(alias.to_string()),
4943 blob: None,
4944 }),
4945 _ => None,
4946 })
4947 .collect();
4948 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07004949 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004950 list_result.sort();
4951 assert_eq!(list_o_descriptors, list_result);
4952
4953 let mut list_o_ids: Vec<i64> = list_o_descriptors
4954 .into_iter()
4955 .map(|d| {
4956 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004957 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004958 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004959 KeyType::Client,
4960 KeyEntryLoadBits::NONE,
4961 *namespace as u32,
4962 |_, _| Ok(()),
4963 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004964 .unwrap();
4965 entry.id()
4966 })
4967 .collect();
4968 list_o_ids.sort_unstable();
4969 let mut loaded_entries: Vec<i64> = list_o_keys
4970 .iter()
4971 .filter_map(|(id, ns)| match ns {
4972 ns if *ns == *namespace => Some(*id),
4973 _ => None,
4974 })
4975 .collect();
4976 loaded_entries.sort_unstable();
4977 assert_eq!(list_o_ids, loaded_entries);
4978 }
Janis Danisevskis18313832021-05-17 13:30:32 -07004979 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004980
4981 Ok(())
4982 }
4983
Joel Galenson0891bc12020-07-20 10:37:03 -07004984 // Helpers
4985
4986 // Checks that the given result is an error containing the given string.
4987 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4988 let error_str = format!(
4989 "{:#?}",
4990 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4991 );
4992 assert!(
4993 error_str.contains(target),
4994 "The string \"{}\" should contain \"{}\"",
4995 error_str,
4996 target
4997 );
4998 }
4999
Joel Galenson2aab4432020-07-22 15:27:57 -07005000 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07005001 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005002 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005003 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005004 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005005 namespace: Option<i64>,
5006 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005007 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08005008 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005009 }
5010
5011 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
5012 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07005013 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07005014 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07005015 Ok(KeyEntryRow {
5016 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005017 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07005018 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07005019 namespace: row.get(3)?,
5020 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005021 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08005022 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07005023 })
5024 })?
5025 .map(|r| r.context("Could not read keyentry row."))
5026 .collect::<Result<Vec<_>>>()
5027 }
5028
Max Biresb2e1d032021-02-08 21:35:05 -08005029 struct RemoteProvValues {
5030 cert_chain: Vec<u8>,
5031 priv_key: Vec<u8>,
5032 batch_cert: Vec<u8>,
5033 }
5034
Max Bires2b2e6562020-09-22 11:22:36 -07005035 fn load_attestation_key_pool(
5036 db: &mut KeystoreDB,
5037 expiration_date: i64,
5038 namespace: i64,
5039 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08005040 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07005041 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
5042 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
5043 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5044 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005045 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005046 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5047 db.store_signed_attestation_certificate_chain(
5048 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005049 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005050 &cert_chain,
5051 expiration_date,
5052 &KEYSTORE_UUID,
5053 )?;
5054 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005055 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005056 }
5057
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005058 // Note: The parameters and SecurityLevel associations are nonsensical. This
5059 // collection is only used to check if the parameters are preserved as expected by the
5060 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005061 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5062 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005063 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5064 KeyParameter::new(
5065 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5066 SecurityLevel::TRUSTED_ENVIRONMENT,
5067 ),
5068 KeyParameter::new(
5069 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5070 SecurityLevel::TRUSTED_ENVIRONMENT,
5071 ),
5072 KeyParameter::new(
5073 KeyParameterValue::Algorithm(Algorithm::RSA),
5074 SecurityLevel::TRUSTED_ENVIRONMENT,
5075 ),
5076 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5077 KeyParameter::new(
5078 KeyParameterValue::BlockMode(BlockMode::ECB),
5079 SecurityLevel::TRUSTED_ENVIRONMENT,
5080 ),
5081 KeyParameter::new(
5082 KeyParameterValue::BlockMode(BlockMode::GCM),
5083 SecurityLevel::TRUSTED_ENVIRONMENT,
5084 ),
5085 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5086 KeyParameter::new(
5087 KeyParameterValue::Digest(Digest::MD5),
5088 SecurityLevel::TRUSTED_ENVIRONMENT,
5089 ),
5090 KeyParameter::new(
5091 KeyParameterValue::Digest(Digest::SHA_2_224),
5092 SecurityLevel::TRUSTED_ENVIRONMENT,
5093 ),
5094 KeyParameter::new(
5095 KeyParameterValue::Digest(Digest::SHA_2_256),
5096 SecurityLevel::STRONGBOX,
5097 ),
5098 KeyParameter::new(
5099 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5100 SecurityLevel::TRUSTED_ENVIRONMENT,
5101 ),
5102 KeyParameter::new(
5103 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5104 SecurityLevel::TRUSTED_ENVIRONMENT,
5105 ),
5106 KeyParameter::new(
5107 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5108 SecurityLevel::STRONGBOX,
5109 ),
5110 KeyParameter::new(
5111 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5112 SecurityLevel::TRUSTED_ENVIRONMENT,
5113 ),
5114 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5115 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5116 KeyParameter::new(
5117 KeyParameterValue::EcCurve(EcCurve::P_224),
5118 SecurityLevel::TRUSTED_ENVIRONMENT,
5119 ),
5120 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5121 KeyParameter::new(
5122 KeyParameterValue::EcCurve(EcCurve::P_384),
5123 SecurityLevel::TRUSTED_ENVIRONMENT,
5124 ),
5125 KeyParameter::new(
5126 KeyParameterValue::EcCurve(EcCurve::P_521),
5127 SecurityLevel::TRUSTED_ENVIRONMENT,
5128 ),
5129 KeyParameter::new(
5130 KeyParameterValue::RSAPublicExponent(3),
5131 SecurityLevel::TRUSTED_ENVIRONMENT,
5132 ),
5133 KeyParameter::new(
5134 KeyParameterValue::IncludeUniqueID,
5135 SecurityLevel::TRUSTED_ENVIRONMENT,
5136 ),
5137 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5138 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5139 KeyParameter::new(
5140 KeyParameterValue::ActiveDateTime(1234567890),
5141 SecurityLevel::STRONGBOX,
5142 ),
5143 KeyParameter::new(
5144 KeyParameterValue::OriginationExpireDateTime(1234567890),
5145 SecurityLevel::TRUSTED_ENVIRONMENT,
5146 ),
5147 KeyParameter::new(
5148 KeyParameterValue::UsageExpireDateTime(1234567890),
5149 SecurityLevel::TRUSTED_ENVIRONMENT,
5150 ),
5151 KeyParameter::new(
5152 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5153 SecurityLevel::TRUSTED_ENVIRONMENT,
5154 ),
5155 KeyParameter::new(
5156 KeyParameterValue::MaxUsesPerBoot(1234567890),
5157 SecurityLevel::TRUSTED_ENVIRONMENT,
5158 ),
5159 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5160 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5161 KeyParameter::new(
5162 KeyParameterValue::NoAuthRequired,
5163 SecurityLevel::TRUSTED_ENVIRONMENT,
5164 ),
5165 KeyParameter::new(
5166 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5167 SecurityLevel::TRUSTED_ENVIRONMENT,
5168 ),
5169 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5170 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5171 KeyParameter::new(
5172 KeyParameterValue::TrustedUserPresenceRequired,
5173 SecurityLevel::TRUSTED_ENVIRONMENT,
5174 ),
5175 KeyParameter::new(
5176 KeyParameterValue::TrustedConfirmationRequired,
5177 SecurityLevel::TRUSTED_ENVIRONMENT,
5178 ),
5179 KeyParameter::new(
5180 KeyParameterValue::UnlockedDeviceRequired,
5181 SecurityLevel::TRUSTED_ENVIRONMENT,
5182 ),
5183 KeyParameter::new(
5184 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5185 SecurityLevel::SOFTWARE,
5186 ),
5187 KeyParameter::new(
5188 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5189 SecurityLevel::SOFTWARE,
5190 ),
5191 KeyParameter::new(
5192 KeyParameterValue::CreationDateTime(12345677890),
5193 SecurityLevel::SOFTWARE,
5194 ),
5195 KeyParameter::new(
5196 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5197 SecurityLevel::TRUSTED_ENVIRONMENT,
5198 ),
5199 KeyParameter::new(
5200 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5201 SecurityLevel::TRUSTED_ENVIRONMENT,
5202 ),
5203 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5204 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5205 KeyParameter::new(
5206 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5207 SecurityLevel::SOFTWARE,
5208 ),
5209 KeyParameter::new(
5210 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5211 SecurityLevel::TRUSTED_ENVIRONMENT,
5212 ),
5213 KeyParameter::new(
5214 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5215 SecurityLevel::TRUSTED_ENVIRONMENT,
5216 ),
5217 KeyParameter::new(
5218 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5219 SecurityLevel::TRUSTED_ENVIRONMENT,
5220 ),
5221 KeyParameter::new(
5222 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5223 SecurityLevel::TRUSTED_ENVIRONMENT,
5224 ),
5225 KeyParameter::new(
5226 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5227 SecurityLevel::TRUSTED_ENVIRONMENT,
5228 ),
5229 KeyParameter::new(
5230 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5231 SecurityLevel::TRUSTED_ENVIRONMENT,
5232 ),
5233 KeyParameter::new(
5234 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5235 SecurityLevel::TRUSTED_ENVIRONMENT,
5236 ),
5237 KeyParameter::new(
5238 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5239 SecurityLevel::TRUSTED_ENVIRONMENT,
5240 ),
5241 KeyParameter::new(
5242 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5243 SecurityLevel::TRUSTED_ENVIRONMENT,
5244 ),
5245 KeyParameter::new(
5246 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5247 SecurityLevel::TRUSTED_ENVIRONMENT,
5248 ),
5249 KeyParameter::new(
5250 KeyParameterValue::VendorPatchLevel(3),
5251 SecurityLevel::TRUSTED_ENVIRONMENT,
5252 ),
5253 KeyParameter::new(
5254 KeyParameterValue::BootPatchLevel(4),
5255 SecurityLevel::TRUSTED_ENVIRONMENT,
5256 ),
5257 KeyParameter::new(
5258 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5259 SecurityLevel::TRUSTED_ENVIRONMENT,
5260 ),
5261 KeyParameter::new(
5262 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5263 SecurityLevel::TRUSTED_ENVIRONMENT,
5264 ),
5265 KeyParameter::new(
5266 KeyParameterValue::MacLength(256),
5267 SecurityLevel::TRUSTED_ENVIRONMENT,
5268 ),
5269 KeyParameter::new(
5270 KeyParameterValue::ResetSinceIdRotation,
5271 SecurityLevel::TRUSTED_ENVIRONMENT,
5272 ),
5273 KeyParameter::new(
5274 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5275 SecurityLevel::TRUSTED_ENVIRONMENT,
5276 ),
Qi Wub9433b52020-12-01 14:52:46 +08005277 ];
5278 if let Some(value) = max_usage_count {
5279 params.push(KeyParameter::new(
5280 KeyParameterValue::UsageCountLimit(value),
5281 SecurityLevel::SOFTWARE,
5282 ));
5283 }
5284 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005285 }
5286
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005287 fn make_test_key_entry(
5288 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005289 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005290 namespace: i64,
5291 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005292 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005293 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005294 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005295 let mut blob_metadata = BlobMetaData::new();
5296 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5297 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5298 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5299 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5300 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5301
5302 db.set_blob(
5303 &key_id,
5304 SubComponentType::KEY_BLOB,
5305 Some(TEST_KEY_BLOB),
5306 Some(&blob_metadata),
5307 )?;
5308 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5309 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005310
5311 let params = make_test_params(max_usage_count);
5312 db.insert_keyparameter(&key_id, &params)?;
5313
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005314 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005315 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005316 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005317 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005318 Ok(key_id)
5319 }
5320
Qi Wub9433b52020-12-01 14:52:46 +08005321 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5322 let params = make_test_params(max_usage_count);
5323
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005324 let mut blob_metadata = BlobMetaData::new();
5325 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5326 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5327 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5328 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5329 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5330
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005331 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005332 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005333
5334 KeyEntry {
5335 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005336 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005337 cert: Some(TEST_CERT_BLOB.to_vec()),
5338 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005339 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005340 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005341 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005342 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005343 }
5344 }
5345
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005346 fn make_bootlevel_key_entry(
5347 db: &mut KeystoreDB,
5348 domain: Domain,
5349 namespace: i64,
5350 alias: &str,
5351 logical_only: bool,
5352 ) -> Result<KeyIdGuard> {
5353 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5354 let mut blob_metadata = BlobMetaData::new();
5355 if !logical_only {
5356 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5357 }
5358 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5359
5360 db.set_blob(
5361 &key_id,
5362 SubComponentType::KEY_BLOB,
5363 Some(TEST_KEY_BLOB),
5364 Some(&blob_metadata),
5365 )?;
5366 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5367 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5368
5369 let mut params = make_test_params(None);
5370 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5371
5372 db.insert_keyparameter(&key_id, &params)?;
5373
5374 let mut metadata = KeyMetaData::new();
5375 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5376 db.insert_key_metadata(&key_id, &metadata)?;
5377 rebind_alias(db, &key_id, alias, domain, namespace)?;
5378 Ok(key_id)
5379 }
5380
5381 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5382 let mut params = make_test_params(None);
5383 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5384
5385 let mut blob_metadata = BlobMetaData::new();
5386 if !logical_only {
5387 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5388 }
5389 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5390
5391 let mut metadata = KeyMetaData::new();
5392 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5393
5394 KeyEntry {
5395 id: key_id,
5396 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5397 cert: Some(TEST_CERT_BLOB.to_vec()),
5398 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5399 km_uuid: KEYSTORE_UUID,
5400 parameters: params,
5401 metadata,
5402 pure_cert: false,
5403 }
5404 }
5405
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005406 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005407 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005408 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005409 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005410 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005411 NO_PARAMS,
5412 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005413 Ok((
5414 row.get(0)?,
5415 row.get(1)?,
5416 row.get(2)?,
5417 row.get(3)?,
5418 row.get(4)?,
5419 row.get(5)?,
5420 row.get(6)?,
5421 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005422 },
5423 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005424
5425 println!("Key entry table rows:");
5426 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005427 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005428 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005429 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5430 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005431 );
5432 }
5433 Ok(())
5434 }
5435
5436 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005437 let mut stmt = db
5438 .conn
5439 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005440 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5441 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5442 })?;
5443
5444 println!("Grant table rows:");
5445 for r in rows {
5446 let (id, gt, ki, av) = r.unwrap();
5447 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5448 }
5449 Ok(())
5450 }
5451
Joel Galenson0891bc12020-07-20 10:37:03 -07005452 // Use a custom random number generator that repeats each number once.
5453 // This allows us to test repeated elements.
5454
5455 thread_local! {
5456 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5457 }
5458
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005459 fn reset_random() {
5460 RANDOM_COUNTER.with(|counter| {
5461 *counter.borrow_mut() = 0;
5462 })
5463 }
5464
Joel Galenson0891bc12020-07-20 10:37:03 -07005465 pub fn random() -> i64 {
5466 RANDOM_COUNTER.with(|counter| {
5467 let result = *counter.borrow() / 2;
5468 *counter.borrow_mut() += 1;
5469 result
5470 })
5471 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005472
5473 #[test]
5474 fn test_last_off_body() -> Result<()> {
5475 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005476 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005477 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005478 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005479 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005480 let one_second = Duration::from_secs(1);
5481 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005482 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005483 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005484 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005485 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005486 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005487 Ok(())
5488 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005489
5490 #[test]
5491 fn test_unbind_keys_for_user() -> Result<()> {
5492 let mut db = new_test_db()?;
5493 db.unbind_keys_for_user(1, false)?;
5494
5495 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5496 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5497 db.unbind_keys_for_user(2, false)?;
5498
Janis Danisevskis18313832021-05-17 13:30:32 -07005499 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5500 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005501
5502 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005503 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005504
5505 Ok(())
5506 }
5507
5508 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005509 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5510 let mut db = new_test_db()?;
5511 let super_key = keystore2_crypto::generate_aes256_key()?;
5512 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5513 let (encrypted_super_key, metadata) =
5514 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5515
5516 let key_name_enc = SuperKeyType {
5517 alias: "test_super_key_1",
5518 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5519 };
5520
5521 let key_name_nonenc = SuperKeyType {
5522 alias: "test_super_key_2",
5523 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5524 };
5525
5526 // Install two super keys.
5527 db.store_super_key(
5528 1,
5529 &key_name_nonenc,
5530 &super_key,
5531 &BlobMetaData::new(),
5532 &KeyMetaData::new(),
5533 )?;
5534 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5535
5536 // Check that both can be found in the database.
5537 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5538 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5539
5540 // Install the same keys for a different user.
5541 db.store_super_key(
5542 2,
5543 &key_name_nonenc,
5544 &super_key,
5545 &BlobMetaData::new(),
5546 &KeyMetaData::new(),
5547 )?;
5548 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5549
5550 // Check that the second pair of keys can be found in the database.
5551 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5552 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5553
5554 // Delete only encrypted keys.
5555 db.unbind_keys_for_user(1, true)?;
5556
5557 // The encrypted superkey should be gone now.
5558 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5559 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5560
5561 // Reinsert the encrypted key.
5562 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5563
5564 // Check that both can be found in the database, again..
5565 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5566 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5567
5568 // Delete all even unencrypted keys.
5569 db.unbind_keys_for_user(1, false)?;
5570
5571 // Both should be gone now.
5572 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5573 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5574
5575 // Check that the second pair of keys was untouched.
5576 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5577 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5578
5579 Ok(())
5580 }
5581
5582 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005583 fn test_store_super_key() -> Result<()> {
5584 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005585 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005586 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005587 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005588 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005589 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005590
5591 let (encrypted_super_key, metadata) =
5592 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005593 db.store_super_key(
5594 1,
5595 &USER_SUPER_KEY,
5596 &encrypted_super_key,
5597 &metadata,
5598 &KeyMetaData::new(),
5599 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005600
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005601 // Check if super key exists.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005602 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005603
Paul Crowley7a658392021-03-18 17:08:20 -07005604 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005605 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5606 USER_SUPER_KEY.algorithm,
5607 key_entry,
5608 &pw,
5609 None,
5610 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005611
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005612 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005613 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005614
Hasini Gunasingheda895552021-01-27 19:34:37 +00005615 Ok(())
5616 }
Seth Moore78c091f2021-04-09 21:38:30 +00005617
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005618 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005619 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005620 MetricsStorage::KEY_ENTRY,
5621 MetricsStorage::KEY_ENTRY_ID_INDEX,
5622 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5623 MetricsStorage::BLOB_ENTRY,
5624 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5625 MetricsStorage::KEY_PARAMETER,
5626 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5627 MetricsStorage::KEY_METADATA,
5628 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5629 MetricsStorage::GRANT,
5630 MetricsStorage::AUTH_TOKEN,
5631 MetricsStorage::BLOB_METADATA,
5632 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005633 ]
5634 }
5635
5636 /// Perform a simple check to ensure that we can query all the storage types
5637 /// that are supported by the DB. Check for reasonable values.
5638 #[test]
5639 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005640 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005641
5642 let mut db = new_test_db()?;
5643
5644 for t in get_valid_statsd_storage_types() {
5645 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005646 // AuthToken can be less than a page since it's in a btree, not sqlite
5647 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005648 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005649 } else {
5650 assert!(stat.size >= PAGE_SIZE);
5651 }
Seth Moore78c091f2021-04-09 21:38:30 +00005652 assert!(stat.size >= stat.unused_size);
5653 }
5654
5655 Ok(())
5656 }
5657
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005658 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005659 get_valid_statsd_storage_types()
5660 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005661 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005662 .collect()
5663 }
5664
5665 fn assert_storage_increased(
5666 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005667 increased_storage_types: Vec<MetricsStorage>,
5668 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005669 ) {
5670 for storage in increased_storage_types {
5671 // Verify the expected storage increased.
5672 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005673 let storage = storage;
5674 let old = &baseline[&storage.0];
5675 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005676 assert!(
5677 new.unused_size <= old.unused_size,
5678 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005679 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005680 new.unused_size,
5681 old.unused_size
5682 );
5683
5684 // Update the baseline with the new value so that it succeeds in the
5685 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005686 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005687 }
5688
5689 // Get an updated map of the storage and verify there were no unexpected changes.
5690 let updated_stats = get_storage_stats_map(db);
5691 assert_eq!(updated_stats.len(), baseline.len());
5692
5693 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005694 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005695 let mut s = String::new();
5696 for &k in map.keys() {
5697 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5698 .expect("string concat failed");
5699 }
5700 s
5701 };
5702
5703 assert!(
5704 updated_stats[&k].size == baseline[&k].size
5705 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5706 "updated_stats:\n{}\nbaseline:\n{}",
5707 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005708 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005709 );
5710 }
5711 }
5712
5713 #[test]
5714 fn test_verify_key_table_size_reporting() -> Result<()> {
5715 let mut db = new_test_db()?;
5716 let mut working_stats = get_storage_stats_map(&mut db);
5717
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005718 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005719 assert_storage_increased(
5720 &mut db,
5721 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005722 MetricsStorage::KEY_ENTRY,
5723 MetricsStorage::KEY_ENTRY_ID_INDEX,
5724 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005725 ],
5726 &mut working_stats,
5727 );
5728
5729 let mut blob_metadata = BlobMetaData::new();
5730 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5731 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5732 assert_storage_increased(
5733 &mut db,
5734 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005735 MetricsStorage::BLOB_ENTRY,
5736 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5737 MetricsStorage::BLOB_METADATA,
5738 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005739 ],
5740 &mut working_stats,
5741 );
5742
5743 let params = make_test_params(None);
5744 db.insert_keyparameter(&key_id, &params)?;
5745 assert_storage_increased(
5746 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005747 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005748 &mut working_stats,
5749 );
5750
5751 let mut metadata = KeyMetaData::new();
5752 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5753 db.insert_key_metadata(&key_id, &metadata)?;
5754 assert_storage_increased(
5755 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005756 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005757 &mut working_stats,
5758 );
5759
5760 let mut sum = 0;
5761 for stat in working_stats.values() {
5762 sum += stat.size;
5763 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005764 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005765 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5766
5767 Ok(())
5768 }
5769
5770 #[test]
5771 fn test_verify_auth_table_size_reporting() -> Result<()> {
5772 let mut db = new_test_db()?;
5773 let mut working_stats = get_storage_stats_map(&mut db);
5774 db.insert_auth_token(&HardwareAuthToken {
5775 challenge: 123,
5776 userId: 456,
5777 authenticatorId: 789,
5778 authenticatorType: kmhw_authenticator_type::ANY,
5779 timestamp: Timestamp { milliSeconds: 10 },
5780 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005781 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005782 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005783 Ok(())
5784 }
5785
5786 #[test]
5787 fn test_verify_grant_table_size_reporting() -> Result<()> {
5788 const OWNER: i64 = 1;
5789 let mut db = new_test_db()?;
5790 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5791
5792 let mut working_stats = get_storage_stats_map(&mut db);
5793 db.grant(
5794 &KeyDescriptor {
5795 domain: Domain::APP,
5796 nspace: 0,
5797 alias: Some(TEST_ALIAS.to_string()),
5798 blob: None,
5799 },
5800 OWNER as u32,
5801 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005802 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005803 |_, _| Ok(()),
5804 )?;
5805
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005806 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005807
5808 Ok(())
5809 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005810
5811 #[test]
5812 fn find_auth_token_entry_returns_latest() -> Result<()> {
5813 let mut db = new_test_db()?;
5814 db.insert_auth_token(&HardwareAuthToken {
5815 challenge: 123,
5816 userId: 456,
5817 authenticatorId: 789,
5818 authenticatorType: kmhw_authenticator_type::ANY,
5819 timestamp: Timestamp { milliSeconds: 10 },
5820 mac: b"mac0".to_vec(),
5821 });
5822 std::thread::sleep(std::time::Duration::from_millis(1));
5823 db.insert_auth_token(&HardwareAuthToken {
5824 challenge: 123,
5825 userId: 457,
5826 authenticatorId: 789,
5827 authenticatorType: kmhw_authenticator_type::ANY,
5828 timestamp: Timestamp { milliSeconds: 12 },
5829 mac: b"mac1".to_vec(),
5830 });
5831 std::thread::sleep(std::time::Duration::from_millis(1));
5832 db.insert_auth_token(&HardwareAuthToken {
5833 challenge: 123,
5834 userId: 458,
5835 authenticatorId: 789,
5836 authenticatorType: kmhw_authenticator_type::ANY,
5837 timestamp: Timestamp { milliSeconds: 3 },
5838 mac: b"mac2".to_vec(),
5839 });
5840 // All three entries are in the database
5841 assert_eq!(db.perboot.auth_tokens_len(), 3);
5842 // It selected the most recent timestamp
5843 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5844 Ok(())
5845 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005846
5847 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005848 fn test_load_key_descriptor() -> Result<()> {
5849 let mut db = new_test_db()?;
5850 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5851
5852 let key = db.load_key_descriptor(key_id)?.unwrap();
5853
5854 assert_eq!(key.domain, Domain::APP);
5855 assert_eq!(key.nspace, 1);
5856 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5857
5858 // No such id
5859 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5860 Ok(())
5861 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005862}