blob: 02ef408de0e3abef6317e74e48b4664279d30c71 [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
Max Birescd7f7412022-02-11 13:47:36 -0800326static EXPIRATION_BUFFER_MS: i64 = 20000;
327
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800328/// Indicates how the sensitive part of this key blob is encrypted.
329#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
330pub enum EncryptedBy {
331 /// The keyblob is encrypted by a user password.
332 /// In the database this variant is represented as NULL.
333 Password,
334 /// The keyblob is encrypted by another key with wrapped key id.
335 /// In the database this variant is represented as non NULL value
336 /// that is convertible to i64, typically NUMERIC.
337 KeyId(i64),
338}
339
340impl ToSql for EncryptedBy {
341 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
342 match self {
343 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
344 Self::KeyId(id) => id.to_sql(),
345 }
346 }
347}
348
349impl FromSql for EncryptedBy {
350 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
351 match value {
352 ValueRef::Null => Ok(Self::Password),
353 _ => Ok(Self::KeyId(i64::column_result(value)?)),
354 }
355 }
356}
357
358/// A database representation of wall clock time. DateTime stores unix epoch time as
359/// i64 in milliseconds.
360#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
361pub struct DateTime(i64);
362
363/// Error type returned when creating DateTime or converting it from and to
364/// SystemTime.
365#[derive(thiserror::Error, Debug)]
366pub enum DateTimeError {
367 /// This is returned when SystemTime and Duration computations fail.
368 #[error(transparent)]
369 SystemTimeError(#[from] SystemTimeError),
370
371 /// This is returned when type conversions fail.
372 #[error(transparent)]
373 TypeConversion(#[from] std::num::TryFromIntError),
374
375 /// This is returned when checked time arithmetic failed.
376 #[error("Time arithmetic failed.")]
377 TimeArithmetic,
378}
379
380impl DateTime {
381 /// Constructs a new DateTime object denoting the current time. This may fail during
382 /// conversion to unix epoch time and during conversion to the internal i64 representation.
383 pub fn now() -> Result<Self, DateTimeError> {
384 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
385 }
386
387 /// Constructs a new DateTime object from milliseconds.
388 pub fn from_millis_epoch(millis: i64) -> Self {
389 Self(millis)
390 }
391
392 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700393 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800394 self.0
395 }
396
397 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700398 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800399 self.0 / 1000
400 }
401}
402
403impl ToSql for DateTime {
404 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
405 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
406 }
407}
408
409impl FromSql for DateTime {
410 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
411 Ok(Self(i64::column_result(value)?))
412 }
413}
414
415impl TryInto<SystemTime> for DateTime {
416 type Error = DateTimeError;
417
418 fn try_into(self) -> Result<SystemTime, Self::Error> {
419 // We want to construct a SystemTime representation equivalent to self, denoting
420 // a point in time THEN, but we cannot set the time directly. We can only construct
421 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
422 // and between EPOCH and THEN. With this common reference we can construct the
423 // duration between NOW and THEN which we can add to our SystemTime representation
424 // of NOW to get a SystemTime representation of THEN.
425 // Durations can only be positive, thus the if statement below.
426 let now = SystemTime::now();
427 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
428 let then_epoch = Duration::from_millis(self.0.try_into()?);
429 Ok(if now_epoch > then_epoch {
430 // then = now - (now_epoch - then_epoch)
431 now_epoch
432 .checked_sub(then_epoch)
433 .and_then(|d| now.checked_sub(d))
434 .ok_or(DateTimeError::TimeArithmetic)?
435 } else {
436 // then = now + (then_epoch - now_epoch)
437 then_epoch
438 .checked_sub(now_epoch)
439 .and_then(|d| now.checked_add(d))
440 .ok_or(DateTimeError::TimeArithmetic)?
441 })
442 }
443}
444
445impl TryFrom<SystemTime> for DateTime {
446 type Error = DateTimeError;
447
448 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
449 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
450 }
451}
452
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800453#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
454enum KeyLifeCycle {
455 /// Existing keys have a key ID but are not fully populated yet.
456 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
457 /// them to Unreferenced for garbage collection.
458 Existing,
459 /// A live key is fully populated and usable by clients.
460 Live,
461 /// An unreferenced key is scheduled for garbage collection.
462 Unreferenced,
463}
464
465impl ToSql for KeyLifeCycle {
466 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
467 match self {
468 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
469 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
470 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
471 }
472 }
473}
474
475impl FromSql for KeyLifeCycle {
476 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
477 match i64::column_result(value)? {
478 0 => Ok(KeyLifeCycle::Existing),
479 1 => Ok(KeyLifeCycle::Live),
480 2 => Ok(KeyLifeCycle::Unreferenced),
481 v => Err(FromSqlError::OutOfRange(v)),
482 }
483 }
484}
485
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700486/// Keys have a KeyMint blob component and optional public certificate and
487/// certificate chain components.
488/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
489/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800490#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700491pub struct KeyEntryLoadBits(u32);
492
493impl KeyEntryLoadBits {
494 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
495 pub const NONE: KeyEntryLoadBits = Self(0);
496 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
497 pub const KM: KeyEntryLoadBits = Self(1);
498 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
499 pub const PUBLIC: KeyEntryLoadBits = Self(2);
500 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
501 pub const BOTH: KeyEntryLoadBits = Self(3);
502
503 /// Returns true if this object indicates that the public components shall be loaded.
504 pub const fn load_public(&self) -> bool {
505 self.0 & Self::PUBLIC.0 != 0
506 }
507
508 /// Returns true if the object indicates that the KeyMint component shall be loaded.
509 pub const fn load_km(&self) -> bool {
510 self.0 & Self::KM.0 != 0
511 }
512}
513
Janis Danisevskisaec14592020-11-12 09:41:49 -0800514lazy_static! {
515 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
516}
517
518struct KeyIdLockDb {
519 locked_keys: Mutex<HashSet<i64>>,
520 cond_var: Condvar,
521}
522
523/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
524/// from the database a second time. Most functions manipulating the key blob database
525/// require a KeyIdGuard.
526#[derive(Debug)]
527pub struct KeyIdGuard(i64);
528
529impl KeyIdLockDb {
530 fn new() -> Self {
531 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
532 }
533
534 /// This function blocks until an exclusive lock for the given key entry id can
535 /// be acquired. It returns a guard object, that represents the lifecycle of the
536 /// acquired lock.
537 pub fn get(&self, key_id: i64) -> KeyIdGuard {
538 let mut locked_keys = self.locked_keys.lock().unwrap();
539 while locked_keys.contains(&key_id) {
540 locked_keys = self.cond_var.wait(locked_keys).unwrap();
541 }
542 locked_keys.insert(key_id);
543 KeyIdGuard(key_id)
544 }
545
546 /// This function attempts to acquire an exclusive lock on a given key id. If the
547 /// given key id is already taken the function returns None immediately. If a lock
548 /// can be acquired this function returns a guard object, that represents the
549 /// lifecycle of the acquired lock.
550 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
551 let mut locked_keys = self.locked_keys.lock().unwrap();
552 if locked_keys.insert(key_id) {
553 Some(KeyIdGuard(key_id))
554 } else {
555 None
556 }
557 }
558}
559
560impl KeyIdGuard {
561 /// Get the numeric key id of the locked key.
562 pub fn id(&self) -> i64 {
563 self.0
564 }
565}
566
567impl Drop for KeyIdGuard {
568 fn drop(&mut self) {
569 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
570 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800571 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800572 KEY_ID_LOCK.cond_var.notify_all();
573 }
574}
575
Max Bires8e93d2b2021-01-14 13:17:59 -0800576/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700577#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800578pub struct CertificateInfo {
579 cert: Option<Vec<u8>>,
580 cert_chain: Option<Vec<u8>>,
581}
582
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800583/// This type represents a Blob with its metadata and an optional superseded blob.
584#[derive(Debug)]
585pub struct BlobInfo<'a> {
586 blob: &'a [u8],
587 metadata: &'a BlobMetaData,
588 /// Superseded blobs are an artifact of legacy import. In some rare occasions
589 /// the key blob needs to be upgraded during import. In that case two
590 /// blob are imported, the superseded one will have to be imported first,
591 /// so that the garbage collector can reap it.
592 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
593}
594
595impl<'a> BlobInfo<'a> {
596 /// Create a new instance of blob info with blob and corresponding metadata
597 /// and no superseded blob info.
598 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
599 Self { blob, metadata, superseded_blob: None }
600 }
601
602 /// Create a new instance of blob info with blob and corresponding metadata
603 /// as well as superseded blob info.
604 pub fn new_with_superseded(
605 blob: &'a [u8],
606 metadata: &'a BlobMetaData,
607 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
608 ) -> Self {
609 Self { blob, metadata, superseded_blob }
610 }
611}
612
Max Bires8e93d2b2021-01-14 13:17:59 -0800613impl CertificateInfo {
614 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
615 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
616 Self { cert, cert_chain }
617 }
618
619 /// Take the cert
620 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
621 self.cert.take()
622 }
623
624 /// Take the cert chain
625 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
626 self.cert_chain.take()
627 }
628}
629
Max Bires2b2e6562020-09-22 11:22:36 -0700630/// This type represents a certificate chain with a private key corresponding to the leaf
631/// 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 -0700632pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800633 /// A KM key blob
634 pub private_key: ZVec,
635 /// A batch cert for private_key
636 pub batch_cert: Vec<u8>,
637 /// A full certificate chain from root signing authority to private_key, including batch_cert
638 /// for convenience.
639 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700640}
641
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700642/// This type represents a Keystore 2.0 key entry.
643/// An entry has a unique `id` by which it can be found in the database.
644/// It has a security level field, key parameters, and three optional fields
645/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800646#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700647pub struct KeyEntry {
648 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800649 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700650 cert: Option<Vec<u8>>,
651 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800652 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700653 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800654 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800655 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700656}
657
658impl KeyEntry {
659 /// Returns the unique id of the Key entry.
660 pub fn id(&self) -> i64 {
661 self.id
662 }
663 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800664 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
665 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700666 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800667 /// Extracts the Optional KeyMint blob including its metadata.
668 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
669 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700670 }
671 /// Exposes the optional public certificate.
672 pub fn cert(&self) -> &Option<Vec<u8>> {
673 &self.cert
674 }
675 /// Extracts the optional public certificate.
676 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
677 self.cert.take()
678 }
679 /// Exposes the optional public certificate chain.
680 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
681 &self.cert_chain
682 }
683 /// Extracts the optional public certificate_chain.
684 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
685 self.cert_chain.take()
686 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800687 /// Returns the uuid of the owning KeyMint instance.
688 pub fn km_uuid(&self) -> &Uuid {
689 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700690 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700691 /// Exposes the key parameters of this key entry.
692 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
693 &self.parameters
694 }
695 /// Consumes this key entry and extracts the keyparameters from it.
696 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
697 self.parameters
698 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800699 /// Exposes the key metadata of this key entry.
700 pub fn metadata(&self) -> &KeyMetaData {
701 &self.metadata
702 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800703 /// This returns true if the entry is a pure certificate entry with no
704 /// private key component.
705 pub fn pure_cert(&self) -> bool {
706 self.pure_cert
707 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000708 /// Consumes this key entry and extracts the keyparameters and metadata from it.
709 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
710 (self.parameters, self.metadata)
711 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700712}
713
714/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800715#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700716pub struct SubComponentType(u32);
717impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800718 /// Persistent identifier for a key blob.
719 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700720 /// Persistent identifier for a certificate blob.
721 pub const CERT: SubComponentType = Self(1);
722 /// Persistent identifier for a certificate chain blob.
723 pub const CERT_CHAIN: SubComponentType = Self(2);
724}
725
726impl ToSql for SubComponentType {
727 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
728 self.0.to_sql()
729 }
730}
731
732impl FromSql for SubComponentType {
733 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
734 Ok(Self(u32::column_result(value)?))
735 }
736}
737
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800738/// This trait is private to the database module. It is used to convey whether or not the garbage
739/// collector shall be invoked after a database access. All closures passed to
740/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
741/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
742/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
743/// `.need_gc()`.
744trait DoGc<T> {
745 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
746
747 fn no_gc(self) -> Result<(bool, T)>;
748
749 fn need_gc(self) -> Result<(bool, T)>;
750}
751
752impl<T> DoGc<T> for Result<T> {
753 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
754 self.map(|r| (need_gc, r))
755 }
756
757 fn no_gc(self) -> Result<(bool, T)> {
758 self.do_gc(false)
759 }
760
761 fn need_gc(self) -> Result<(bool, T)> {
762 self.do_gc(true)
763 }
764}
765
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700766/// KeystoreDB wraps a connection to an SQLite database and tracks its
767/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700768pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700769 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700770 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700771 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700772}
773
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000774/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000775/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000776#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
777pub struct MonotonicRawTime(i64);
778
779impl MonotonicRawTime {
780 /// Constructs a new MonotonicRawTime
781 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000782 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000783 }
784
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000785 /// Returns the value of MonotonicRawTime in milliseconds as i64
786 pub fn milliseconds(&self) -> i64 {
787 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000788 }
789
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000790 /// Returns the integer value of MonotonicRawTime as i64
791 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000792 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000793 }
794
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800795 /// Like i64::checked_sub.
796 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
797 self.0.checked_sub(other.0).map(Self)
798 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000799}
800
801impl ToSql for MonotonicRawTime {
802 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
803 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
804 }
805}
806
807impl FromSql for MonotonicRawTime {
808 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
809 Ok(Self(i64::column_result(value)?))
810 }
811}
812
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000813/// This struct encapsulates the information to be stored in the database about the auth tokens
814/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700815#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000816pub struct AuthTokenEntry {
817 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000818 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000819 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000820}
821
822impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000823 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000824 AuthTokenEntry { auth_token, time_received }
825 }
826
827 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800828 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000829 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800830 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
831 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000832 })
833 }
834
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000835 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800836 pub fn auth_token(&self) -> &HardwareAuthToken {
837 &self.auth_token
838 }
839
840 /// Returns the auth token wrapped by the AuthTokenEntry
841 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000842 self.auth_token
843 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800844
845 /// Returns the time that this auth token was received.
846 pub fn time_received(&self) -> MonotonicRawTime {
847 self.time_received
848 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000849
850 /// Returns the challenge value of the auth token.
851 pub fn challenge(&self) -> i64 {
852 self.auth_token.challenge
853 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000854}
855
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800856/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
857/// This object does not allow access to the database connection. But it keeps a database
858/// connection alive in order to keep the in memory per boot database alive.
859pub struct PerBootDbKeepAlive(Connection);
860
Joel Galenson26f4d012020-07-17 14:57:21 -0700861impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800862 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700863 const CURRENT_DB_VERSION: u32 = 1;
864 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800865
Seth Moore78c091f2021-04-09 21:38:30 +0000866 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700867 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000868
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700869 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800870 /// files persistent.sqlite and perboot.sqlite in the given directory.
871 /// It also attempts to initialize all of the tables.
872 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700873 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700874 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700875 let _wp = wd::watch_millis("KeystoreDB::new", 500);
876
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700877 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700878 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800879
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700880 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800881 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700882 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
883 .context("In KeystoreDB::new: trying to upgrade database.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800884 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800885 })?;
886 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700887 }
888
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700889 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
890 // cryptographic binding to the boot level keys was implemented.
891 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
892 tx.execute(
893 "UPDATE persistent.keyentry SET state = ?
894 WHERE
895 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
896 AND
897 id NOT IN (
898 SELECT keyentryid FROM persistent.blobentry
899 WHERE id IN (
900 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
901 )
902 );",
903 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
904 )
905 .context("In from_0_to_1: Failed to delete logical boot level keys.")?;
906 Ok(1)
907 }
908
Janis Danisevskis66784c42021-01-27 08:40:25 -0800909 fn init_tables(tx: &Transaction) -> Result<()> {
910 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700911 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700912 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800913 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700914 domain INTEGER,
915 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800916 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800917 state INTEGER,
918 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700919 NO_PARAMS,
920 )
921 .context("Failed to initialize \"keyentry\" table.")?;
922
Janis Danisevskis66784c42021-01-27 08:40:25 -0800923 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800924 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
925 ON keyentry(id);",
926 NO_PARAMS,
927 )
928 .context("Failed to create index keyentry_id_index.")?;
929
930 tx.execute(
931 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
932 ON keyentry(domain, namespace, alias);",
933 NO_PARAMS,
934 )
935 .context("Failed to create index keyentry_domain_namespace_index.")?;
936
937 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700938 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
939 id INTEGER PRIMARY KEY,
940 subcomponent_type INTEGER,
941 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800942 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700943 NO_PARAMS,
944 )
945 .context("Failed to initialize \"blobentry\" table.")?;
946
Janis Danisevskis66784c42021-01-27 08:40:25 -0800947 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800948 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
949 ON blobentry(keyentryid);",
950 NO_PARAMS,
951 )
952 .context("Failed to create index blobentry_keyentryid_index.")?;
953
954 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800955 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
956 id INTEGER PRIMARY KEY,
957 blobentryid INTEGER,
958 tag INTEGER,
959 data ANY,
960 UNIQUE (blobentryid, tag));",
961 NO_PARAMS,
962 )
963 .context("Failed to initialize \"blobmetadata\" table.")?;
964
965 tx.execute(
966 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
967 ON blobmetadata(blobentryid);",
968 NO_PARAMS,
969 )
970 .context("Failed to create index blobmetadata_blobentryid_index.")?;
971
972 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700973 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000974 keyentryid INTEGER,
975 tag INTEGER,
976 data ANY,
977 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700978 NO_PARAMS,
979 )
980 .context("Failed to initialize \"keyparameter\" table.")?;
981
Janis Danisevskis66784c42021-01-27 08:40:25 -0800982 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800983 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
984 ON keyparameter(keyentryid);",
985 NO_PARAMS,
986 )
987 .context("Failed to create index keyparameter_keyentryid_index.")?;
988
989 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800990 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
991 keyentryid INTEGER,
992 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000993 data ANY,
994 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800995 NO_PARAMS,
996 )
997 .context("Failed to initialize \"keymetadata\" table.")?;
998
Janis Danisevskis66784c42021-01-27 08:40:25 -0800999 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -08001000 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
1001 ON keymetadata(keyentryid);",
1002 NO_PARAMS,
1003 )
1004 .context("Failed to create index keymetadata_keyentryid_index.")?;
1005
1006 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001007 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001008 id INTEGER UNIQUE,
1009 grantee INTEGER,
1010 keyentryid INTEGER,
1011 access_vector INTEGER);",
1012 NO_PARAMS,
1013 )
1014 .context("Failed to initialize \"grant\" table.")?;
1015
Joel Galenson0891bc12020-07-20 10:37:03 -07001016 Ok(())
1017 }
1018
Seth Moore472fcbb2021-05-12 10:07:51 -07001019 fn make_persistent_path(db_root: &Path) -> Result<String> {
1020 // Build the path to the sqlite file.
1021 let mut persistent_path = db_root.to_path_buf();
1022 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1023
1024 // Now convert them to strings prefixed with "file:"
1025 let mut persistent_path_str = "file:".to_owned();
1026 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1027
1028 Ok(persistent_path_str)
1029 }
1030
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001031 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001032 let conn =
1033 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1034
Janis Danisevskis66784c42021-01-27 08:40:25 -08001035 loop {
1036 if let Err(e) = conn
1037 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1038 .context("Failed to attach database persistent.")
1039 {
1040 if Self::is_locked_error(&e) {
1041 std::thread::sleep(std::time::Duration::from_micros(500));
1042 continue;
1043 } else {
1044 return Err(e);
1045 }
1046 }
1047 break;
1048 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001049
Matthew Maurer4fb19112021-05-06 15:40:44 -07001050 // Drop the cache size from default (2M) to 0.5M
1051 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1052 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001053
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001054 Ok(conn)
1055 }
1056
Seth Moore78c091f2021-04-09 21:38:30 +00001057 fn do_table_size_query(
1058 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001059 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001060 query: &str,
1061 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001062 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001063 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001064 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001065 .with_context(|| {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001066 format!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001067 })
1068 .no_gc()
1069 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001070 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001071 }
1072
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001073 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001074 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001075 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001076 "SELECT page_count * page_size, freelist_count * page_size
1077 FROM pragma_page_count('persistent'),
1078 pragma_page_size('persistent'),
1079 persistent.pragma_freelist_count();",
1080 &[],
1081 )
1082 }
1083
1084 fn get_table_size(
1085 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001086 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001087 schema: &str,
1088 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001089 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001090 self.do_table_size_query(
1091 storage_type,
1092 "SELECT pgsize,unused FROM dbstat(?1)
1093 WHERE name=?2 AND aggregate=TRUE;",
1094 &[schema, table],
1095 )
1096 }
1097
1098 /// Fetches a storage statisitics atom for a given storage type. For storage
1099 /// types that map to a table, information about the table's storage is
1100 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001101 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001102 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1103
Seth Moore78c091f2021-04-09 21:38:30 +00001104 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001105 MetricsStorage::DATABASE => self.get_total_size(),
1106 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001107 self.get_table_size(storage_type, "persistent", "keyentry")
1108 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001109 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001110 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1111 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001112 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001113 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1114 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001115 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001116 self.get_table_size(storage_type, "persistent", "blobentry")
1117 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001118 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001119 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1120 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001121 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001122 self.get_table_size(storage_type, "persistent", "keyparameter")
1123 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001124 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001125 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1126 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001127 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001128 self.get_table_size(storage_type, "persistent", "keymetadata")
1129 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001130 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001131 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1132 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001133 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1134 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001135 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1136 // reportable
1137 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001138 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001139 storage_type,
1140 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001141 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001142 unused_size: 0,
1143 })
Seth Moore78c091f2021-04-09 21:38:30 +00001144 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001145 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001146 self.get_table_size(storage_type, "persistent", "blobmetadata")
1147 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001148 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001149 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1150 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001151 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001152 }
1153 }
1154
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001155 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001156 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1157 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001158 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1159 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001160 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001162 blob_ids_to_delete: &[i64],
1163 max_blobs: usize,
1164 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001165 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001166 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001167 // Delete the given blobs.
1168 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001169 tx.execute(
1170 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001171 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001172 )
1173 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001174 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1175 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001176 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001177
1178 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1179
Janis Danisevskis3395f862021-05-06 10:54:17 -07001180 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1181 let result: Vec<(i64, Vec<u8>)> = {
1182 let mut stmt = tx
1183 .prepare(
1184 "SELECT id, blob FROM persistent.blobentry
1185 WHERE subcomponent_type = ?
1186 AND (
1187 id NOT IN (
1188 SELECT MAX(id) FROM persistent.blobentry
1189 WHERE subcomponent_type = ?
1190 GROUP BY keyentryid, subcomponent_type
1191 )
1192 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1193 ) LIMIT ?;",
1194 )
1195 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001196
Janis Danisevskis3395f862021-05-06 10:54:17 -07001197 let rows = stmt
1198 .query_map(
1199 params![
1200 SubComponentType::KEY_BLOB,
1201 SubComponentType::KEY_BLOB,
1202 max_blobs as i64,
1203 ],
1204 |row| Ok((row.get(0)?, row.get(1)?)),
1205 )
1206 .context("Trying to query superseded blob.")?;
1207
1208 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1209 .context("Trying to extract superseded blobs.")?
1210 };
1211
1212 let result = result
1213 .into_iter()
1214 .map(|(blob_id, blob)| {
1215 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1216 })
1217 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1218 .context("Trying to load blob metadata.")?;
1219 if !result.is_empty() {
1220 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001221 }
1222
1223 // We did not find any superseded key blob, so let's remove other superseded blob in
1224 // one transaction.
1225 tx.execute(
1226 "DELETE FROM persistent.blobentry
1227 WHERE NOT subcomponent_type = ?
1228 AND (
1229 id NOT IN (
1230 SELECT MAX(id) FROM persistent.blobentry
1231 WHERE NOT subcomponent_type = ?
1232 GROUP BY keyentryid, subcomponent_type
1233 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1234 );",
1235 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1236 )
1237 .context("Trying to purge superseded blobs.")?;
1238
Janis Danisevskis3395f862021-05-06 10:54:17 -07001239 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001240 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001241 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001242 }
1243
1244 /// This maintenance function should be called only once before the database is used for the
1245 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1246 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1247 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1248 /// Keystore crashed at some point during key generation. Callers may want to log such
1249 /// occurrences.
1250 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1251 /// it to `KeyLifeCycle::Live` may have grants.
1252 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001253 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1254
Janis Danisevskis66784c42021-01-27 08:40:25 -08001255 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1256 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001257 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1258 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1259 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001260 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001261 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001262 })
1263 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001264 }
1265
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001266 /// Checks if a key exists with given key type and key descriptor properties.
1267 pub fn key_exists(
1268 &mut self,
1269 domain: Domain,
1270 nspace: i64,
1271 alias: &str,
1272 key_type: KeyType,
1273 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001274 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1275
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001276 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1277 let key_descriptor =
1278 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001279 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001280 match result {
1281 Ok(_) => Ok(true),
1282 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1283 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1284 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1285 },
1286 }
1287 .no_gc()
1288 })
1289 .context("In key_exists.")
1290 }
1291
Hasini Gunasingheda895552021-01-27 19:34:37 +00001292 /// Stores a super key in the database.
1293 pub fn store_super_key(
1294 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001295 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001296 key_type: &SuperKeyType,
1297 blob: &[u8],
1298 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001299 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001300 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001301 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1302
Hasini Gunasingheda895552021-01-27 19:34:37 +00001303 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1304 let key_id = Self::insert_with_retry(|id| {
1305 tx.execute(
1306 "INSERT into persistent.keyentry
1307 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001308 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001309 params![
1310 id,
1311 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001312 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001313 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001314 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001315 KeyLifeCycle::Live,
1316 &KEYSTORE_UUID,
1317 ],
1318 )
1319 })
1320 .context("Failed to insert into keyentry table.")?;
1321
Paul Crowley8d5b2532021-03-19 10:53:07 -07001322 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1323
Hasini Gunasingheda895552021-01-27 19:34:37 +00001324 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001325 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001326 key_id,
1327 SubComponentType::KEY_BLOB,
1328 Some(blob),
1329 Some(blob_metadata),
1330 )
1331 .context("Failed to store key blob.")?;
1332
1333 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1334 .context("Trying to load key components.")
1335 .no_gc()
1336 })
1337 .context("In store_super_key.")
1338 }
1339
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001340 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001341 pub fn load_super_key(
1342 &mut self,
1343 key_type: &SuperKeyType,
1344 user_id: u32,
1345 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001346 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1347
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001348 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1349 let key_descriptor = KeyDescriptor {
1350 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001351 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001352 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001353 blob: None,
1354 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001355 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001356 match id {
1357 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001358 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001359 .context("In load_super_key. Failed to load key entry.")?;
1360 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1361 }
1362 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1363 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1364 _ => Err(error).context("In load_super_key."),
1365 },
1366 }
1367 .no_gc()
1368 })
1369 .context("In load_super_key.")
1370 }
1371
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001372 /// Atomically loads a key entry and associated metadata or creates it using the
1373 /// callback create_new_key callback. The callback is called during a database
1374 /// transaction. This means that implementers should be mindful about using
1375 /// blocking operations such as IPC or grabbing mutexes.
1376 pub fn get_or_create_key_with<F>(
1377 &mut self,
1378 domain: Domain,
1379 namespace: i64,
1380 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001381 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001382 create_new_key: F,
1383 ) -> Result<(KeyIdGuard, KeyEntry)>
1384 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001385 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001386 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001387 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1388
Janis Danisevskis66784c42021-01-27 08:40:25 -08001389 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1390 let id = {
1391 let mut stmt = tx
1392 .prepare(
1393 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001394 WHERE
1395 key_type = ?
1396 AND domain = ?
1397 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001398 AND alias = ?
1399 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 )
1401 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1402 let mut rows = stmt
1403 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1404 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001405
Janis Danisevskis66784c42021-01-27 08:40:25 -08001406 db_utils::with_rows_extract_one(&mut rows, |row| {
1407 Ok(match row {
1408 Some(r) => r.get(0).context("Failed to unpack id.")?,
1409 None => None,
1410 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001411 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 .context("In get_or_create_key_with.")?
1413 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001414
Janis Danisevskis66784c42021-01-27 08:40:25 -08001415 let (id, entry) = match id {
1416 Some(id) => (
1417 id,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001418 Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 .context("In get_or_create_key_with.")?,
1420 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001421
Janis Danisevskis66784c42021-01-27 08:40:25 -08001422 None => {
1423 let id = Self::insert_with_retry(|id| {
1424 tx.execute(
1425 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001426 (id, key_type, domain, namespace, alias, state, km_uuid)
1427 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001428 params![
1429 id,
1430 KeyType::Super,
1431 domain.0,
1432 namespace,
1433 alias,
1434 KeyLifeCycle::Live,
1435 km_uuid,
1436 ],
1437 )
1438 })
1439 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001440
Janis Danisevskis66784c42021-01-27 08:40:25 -08001441 let (blob, metadata) =
1442 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001443 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001444 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001445 id,
1446 SubComponentType::KEY_BLOB,
1447 Some(&blob),
1448 Some(&metadata),
1449 )
Paul Crowley7a658392021-03-18 17:08:20 -07001450 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001451 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001452 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001453 KeyEntry {
1454 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001455 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001456 pure_cert: false,
1457 ..Default::default()
1458 },
1459 )
1460 }
1461 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001462 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001463 })
1464 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001465 }
1466
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001467 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001468 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1469 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001470 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1471 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001472 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001473 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001474 loop {
1475 match self
1476 .conn
1477 .transaction_with_behavior(behavior)
1478 .context("In with_transaction.")
1479 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1480 .and_then(|(result, tx)| {
1481 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1482 Ok(result)
1483 }) {
1484 Ok(result) => break Ok(result),
1485 Err(e) => {
1486 if Self::is_locked_error(&e) {
1487 std::thread::sleep(std::time::Duration::from_micros(500));
1488 continue;
1489 } else {
1490 return Err(e).context("In with_transaction.");
1491 }
1492 }
1493 }
1494 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001495 .map(|(need_gc, result)| {
1496 if need_gc {
1497 if let Some(ref gc) = self.gc {
1498 gc.notify_gc();
1499 }
1500 }
1501 result
1502 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001503 }
1504
1505 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001506 matches!(
1507 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1508 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1509 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1510 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001511 }
1512
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001513 /// Creates a new key entry and allocates a new randomized id for the new key.
1514 /// The key id gets associated with a domain and namespace but not with an alias.
1515 /// To complete key generation `rebind_alias` should be called after all of the
1516 /// key artifacts, i.e., blobs and parameters have been associated with the new
1517 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1518 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001519 pub fn create_key_entry(
1520 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001521 domain: &Domain,
1522 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001523 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001524 km_uuid: &Uuid,
1525 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001526 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1527
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001529 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001530 })
1531 .context("In create_key_entry.")
1532 }
1533
1534 fn create_key_entry_internal(
1535 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001536 domain: &Domain,
1537 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001538 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001539 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001540 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001541 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001542 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001543 _ => {
1544 return Err(KsError::sys())
1545 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1546 }
1547 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001548 Ok(KEY_ID_LOCK.get(
1549 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001550 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001551 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001552 (id, key_type, domain, namespace, alias, state, km_uuid)
1553 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001554 params![
1555 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001556 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001557 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001558 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001559 KeyLifeCycle::Existing,
1560 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001561 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001562 )
1563 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001564 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001565 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001566 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001567
Max Bires2b2e6562020-09-22 11:22:36 -07001568 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1569 /// The key id gets associated with a domain and namespace later but not with an alias. The
1570 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1571 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1572 /// a key.
1573 pub fn create_attestation_key_entry(
1574 &mut self,
1575 maced_public_key: &[u8],
1576 raw_public_key: &[u8],
1577 private_key: &[u8],
1578 km_uuid: &Uuid,
1579 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001580 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1581
Max Bires2b2e6562020-09-22 11:22:36 -07001582 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1583 let key_id = KEY_ID_LOCK.get(
1584 Self::insert_with_retry(|id| {
1585 tx.execute(
1586 "INSERT into persistent.keyentry
1587 (id, key_type, domain, namespace, alias, state, km_uuid)
1588 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1589 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1590 )
1591 })
1592 .context("In create_key_entry")?,
1593 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001594 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001595 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001596 key_id.0,
1597 SubComponentType::KEY_BLOB,
1598 Some(private_key),
1599 None,
1600 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001601 let mut metadata = KeyMetaData::new();
1602 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1603 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001604 metadata.store_in_db(key_id.0, tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001605 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001606 })
1607 .context("In create_attestation_key_entry")
1608 }
1609
Janis Danisevskis377d1002021-01-27 19:07:48 -08001610 /// Set a new blob and associates it with the given key id. Each blob
1611 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001612 /// Each key can have one of each sub component type associated. If more
1613 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001614 /// will get garbage collected.
1615 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1616 /// removed by setting blob to None.
1617 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001618 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001619 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001620 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001621 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001622 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001623 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001624 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1625
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001626 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001627 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001628 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001629 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001630 }
1631
Janis Danisevskiseed69842021-02-18 20:04:10 -08001632 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1633 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1634 /// We use this to insert key blobs into the database which can then be garbage collected
1635 /// lazily by the key garbage collector.
1636 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001637 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1638
Janis Danisevskiseed69842021-02-18 20:04:10 -08001639 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1640 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001641 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001642 Self::UNASSIGNED_KEY_ID,
1643 SubComponentType::KEY_BLOB,
1644 Some(blob),
1645 Some(blob_metadata),
1646 )
1647 .need_gc()
1648 })
1649 .context("In set_deleted_blob.")
1650 }
1651
Janis Danisevskis377d1002021-01-27 19:07:48 -08001652 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001653 tx: &Transaction,
1654 key_id: i64,
1655 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001656 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001657 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001658 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001659 match (blob, sc_type) {
1660 (Some(blob), _) => {
1661 tx.execute(
1662 "INSERT INTO persistent.blobentry
1663 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1664 params![sc_type, key_id, blob],
1665 )
1666 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001667 if let Some(blob_metadata) = blob_metadata {
1668 let blob_id = tx
1669 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1670 row.get(0)
1671 })
1672 .context("In set_blob_internal: Failed to get new blob id.")?;
1673 blob_metadata
1674 .store_in_db(blob_id, tx)
1675 .context("In set_blob_internal: Trying to store blob metadata.")?;
1676 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001677 }
1678 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1679 tx.execute(
1680 "DELETE FROM persistent.blobentry
1681 WHERE subcomponent_type = ? AND keyentryid = ?;",
1682 params![sc_type, key_id],
1683 )
1684 .context("In set_blob_internal: Failed to delete blob.")?;
1685 }
1686 (None, _) => {
1687 return Err(KsError::sys())
1688 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1689 }
1690 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001691 Ok(())
1692 }
1693
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001694 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1695 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001696 #[cfg(test)]
1697 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001698 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001699 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001700 })
1701 .context("In insert_keyparameter.")
1702 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001703
Janis Danisevskis66784c42021-01-27 08:40:25 -08001704 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001705 tx: &Transaction,
1706 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001707 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001708 ) -> Result<()> {
1709 let mut stmt = tx
1710 .prepare(
1711 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1712 VALUES (?, ?, ?, ?);",
1713 )
1714 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1715
Janis Danisevskis66784c42021-01-27 08:40:25 -08001716 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001717 stmt.insert(params![
1718 key_id.0,
1719 p.get_tag().0,
1720 p.key_parameter_value(),
1721 p.security_level().0
1722 ])
1723 .with_context(|| {
1724 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1725 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001726 }
1727 Ok(())
1728 }
1729
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001730 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001731 #[cfg(test)]
1732 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001734 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001735 })
1736 .context("In insert_key_metadata.")
1737 }
1738
Max Bires2b2e6562020-09-22 11:22:36 -07001739 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1740 /// on the public key.
1741 pub fn store_signed_attestation_certificate_chain(
1742 &mut self,
1743 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001744 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001745 cert_chain: &[u8],
1746 expiration_date: i64,
1747 km_uuid: &Uuid,
1748 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001749 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1750
Max Bires2b2e6562020-09-22 11:22:36 -07001751 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1752 let mut stmt = tx
1753 .prepare(
1754 "SELECT keyentryid
1755 FROM persistent.keymetadata
1756 WHERE tag = ? AND data = ? AND keyentryid IN
1757 (SELECT id
1758 FROM persistent.keyentry
1759 WHERE
1760 alias IS NULL AND
1761 domain IS NULL AND
1762 namespace IS NULL AND
1763 key_type = ? AND
1764 km_uuid = ?);",
1765 )
1766 .context("Failed to store attestation certificate chain.")?;
1767 let mut rows = stmt
1768 .query(params![
1769 KeyMetaData::AttestationRawPubKey,
1770 raw_public_key,
1771 KeyType::Attestation,
1772 km_uuid
1773 ])
1774 .context("Failed to fetch keyid")?;
1775 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1776 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1777 .get(0)
1778 .context("Failed to unpack id.")
1779 })
1780 .context("Failed to get key_id.")?;
1781 let num_updated = tx
1782 .execute(
1783 "UPDATE persistent.keyentry
1784 SET alias = ?
1785 WHERE id = ?;",
1786 params!["signed", key_id],
1787 )
1788 .context("Failed to update alias.")?;
1789 if num_updated != 1 {
1790 return Err(KsError::sys()).context("Alias not updated for the key.");
1791 }
1792 let mut metadata = KeyMetaData::new();
1793 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1794 expiration_date,
1795 )));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001796 metadata.store_in_db(key_id, tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001797 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001798 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001799 key_id,
1800 SubComponentType::CERT_CHAIN,
1801 Some(cert_chain),
1802 None,
1803 )
1804 .context("Failed to insert cert chain")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001805 Self::set_blob_internal(tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
Max Biresb2e1d032021-02-08 21:35:05 -08001806 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001807 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001808 })
1809 .context("In store_signed_attestation_certificate_chain: ")
1810 }
1811
1812 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1813 /// currently have a key assigned to it.
1814 pub fn assign_attestation_key(
1815 &mut self,
1816 domain: Domain,
1817 namespace: i64,
1818 km_uuid: &Uuid,
1819 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001820 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1821
Max Bires2b2e6562020-09-22 11:22:36 -07001822 match domain {
1823 Domain::APP | Domain::SELINUX => {}
1824 _ => {
1825 return Err(KsError::sys()).context(format!(
1826 concat!(
1827 "In assign_attestation_key: Domain {:?} ",
1828 "must be either App or SELinux.",
1829 ),
1830 domain
1831 ));
1832 }
1833 }
1834 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1835 let result = tx
1836 .execute(
1837 "UPDATE persistent.keyentry
1838 SET domain=?1, namespace=?2
1839 WHERE
1840 id =
1841 (SELECT MIN(id)
1842 FROM persistent.keyentry
1843 WHERE ALIAS IS NOT NULL
1844 AND domain IS NULL
1845 AND key_type IS ?3
1846 AND state IS ?4
1847 AND km_uuid IS ?5)
1848 AND
1849 (SELECT COUNT(*)
1850 FROM persistent.keyentry
1851 WHERE domain=?1
1852 AND namespace=?2
1853 AND key_type IS ?3
1854 AND state IS ?4
1855 AND km_uuid IS ?5) = 0;",
1856 params![
1857 domain.0 as u32,
1858 namespace,
1859 KeyType::Attestation,
1860 KeyLifeCycle::Live,
1861 km_uuid,
1862 ],
1863 )
1864 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001865 if result == 0 {
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +00001866 log_rkp_error_stats(MetricsRkpError::OUT_OF_KEYS);
Max Bires01f8af22021-03-02 23:24:50 -08001867 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1868 } else if result > 1 {
1869 return Err(KsError::sys())
1870 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001871 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001872 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001873 })
1874 .context("In assign_attestation_key: ")
1875 }
1876
1877 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1878 /// provisioning server, or the maximum number available if there are not num_keys number of
1879 /// entries in the table.
1880 pub fn fetch_unsigned_attestation_keys(
1881 &mut self,
1882 num_keys: i32,
1883 km_uuid: &Uuid,
1884 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001885 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1886
Max Bires2b2e6562020-09-22 11:22:36 -07001887 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1888 let mut stmt = tx
1889 .prepare(
1890 "SELECT data
1891 FROM persistent.keymetadata
1892 WHERE tag = ? AND keyentryid IN
1893 (SELECT id
1894 FROM persistent.keyentry
1895 WHERE
1896 alias IS NULL AND
1897 domain IS NULL AND
1898 namespace IS NULL AND
1899 key_type = ? AND
1900 km_uuid = ?
1901 LIMIT ?);",
1902 )
1903 .context("Failed to prepare statement")?;
1904 let rows = stmt
1905 .query_map(
1906 params![
1907 KeyMetaData::AttestationMacedPublicKey,
1908 KeyType::Attestation,
1909 km_uuid,
1910 num_keys
1911 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001912 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001913 )?
1914 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1915 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001916 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001917 })
1918 .context("In fetch_unsigned_attestation_keys")
1919 }
1920
1921 /// Removes any keys that have expired as of the current time. Returns the number of keys
1922 /// marked unreferenced that are bound to be garbage collected.
1923 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001924 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1925
Max Bires2b2e6562020-09-22 11:22:36 -07001926 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1927 let mut stmt = tx
1928 .prepare(
1929 "SELECT keyentryid, data
1930 FROM persistent.keymetadata
1931 WHERE tag = ? AND keyentryid IN
1932 (SELECT id
1933 FROM persistent.keyentry
1934 WHERE key_type = ?);",
1935 )
1936 .context("Failed to prepare query")?;
1937 let key_ids_to_check = stmt
1938 .query_map(
1939 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1940 |row| Ok((row.get(0)?, row.get(1)?)),
1941 )?
1942 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1943 .context("Failed to get date metadata")?;
Max Birescd7f7412022-02-11 13:47:36 -08001944 // Calculate curr_time with a discount factor to avoid a key that's milliseconds away
1945 // from expiration dodging this delete call.
Max Bires2b2e6562020-09-22 11:22:36 -07001946 let curr_time = DateTime::from_millis_epoch(
Max Birescd7f7412022-02-11 13:47:36 -08001947 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
1948 + EXPIRATION_BUFFER_MS,
Max Bires2b2e6562020-09-22 11:22:36 -07001949 );
1950 let mut num_deleted = 0;
1951 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 -07001952 if Self::mark_unreferenced(tx, id)? {
Max Bires2b2e6562020-09-22 11:22:36 -07001953 num_deleted += 1;
1954 }
1955 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001956 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001957 })
1958 .context("In delete_expired_attestation_keys: ")
1959 }
1960
Max Bires60d7ed12021-03-05 15:59:22 -08001961 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1962 /// they are in. This is useful primarily as a testing mechanism.
1963 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001964 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1965
Max Bires60d7ed12021-03-05 15:59:22 -08001966 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1967 let mut stmt = tx
1968 .prepare(
1969 "SELECT id FROM persistent.keyentry
1970 WHERE key_type IS ?;",
1971 )
1972 .context("Failed to prepare statement")?;
1973 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001974 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001975 .collect::<rusqlite::Result<Vec<i64>>>()
1976 .context("Failed to execute statement")?;
1977 let num_deleted = keys_to_delete
1978 .iter()
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001979 .map(|id| Self::mark_unreferenced(tx, *id))
Max Bires60d7ed12021-03-05 15:59:22 -08001980 .collect::<Result<Vec<bool>>>()
1981 .context("Failed to execute mark_unreferenced on a keyid")?
1982 .into_iter()
1983 .filter(|result| *result)
1984 .count() as i64;
1985 Ok(num_deleted).do_gc(num_deleted != 0)
1986 })
1987 .context("In delete_all_attestation_keys: ")
1988 }
1989
Max Bires2b2e6562020-09-22 11:22:36 -07001990 /// Counts the number of keys that will expire by the provided epoch date and the number of
1991 /// keys not currently assigned to a domain.
1992 pub fn get_attestation_pool_status(
1993 &mut self,
1994 date: i64,
1995 km_uuid: &Uuid,
1996 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001997 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1998
Max Bires2b2e6562020-09-22 11:22:36 -07001999 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2000 let mut stmt = tx.prepare(
2001 "SELECT data
2002 FROM persistent.keymetadata
2003 WHERE tag = ? AND keyentryid IN
2004 (SELECT id
2005 FROM persistent.keyentry
2006 WHERE alias IS NOT NULL
2007 AND key_type = ?
2008 AND km_uuid = ?
2009 AND state = ?);",
2010 )?;
2011 let times = stmt
2012 .query_map(
2013 params![
2014 KeyMetaData::AttestationExpirationDate,
2015 KeyType::Attestation,
2016 km_uuid,
2017 KeyLifeCycle::Live
2018 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002019 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002020 )?
2021 .collect::<rusqlite::Result<Vec<DateTime>>>()
2022 .context("Failed to execute metadata statement")?;
2023 let expiring =
2024 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2025 as i32;
2026 stmt = tx.prepare(
2027 "SELECT alias, domain
2028 FROM persistent.keyentry
2029 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2030 )?;
2031 let rows = stmt
2032 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2033 Ok((row.get(0)?, row.get(1)?))
2034 })?
2035 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2036 .context("Failed to execute keyentry statement")?;
2037 let mut unassigned = 0i32;
2038 let mut attested = 0i32;
2039 let total = rows.len() as i32;
2040 for (alias, domain) in rows {
2041 match (alias, domain) {
2042 (Some(_alias), None) => {
2043 attested += 1;
2044 unassigned += 1;
2045 }
2046 (Some(_alias), Some(_domain)) => {
2047 attested += 1;
2048 }
2049 _ => {}
2050 }
2051 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002052 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002053 })
2054 .context("In get_attestation_pool_status: ")
2055 }
2056
Max Bires55620ff2022-02-11 13:34:15 -08002057 fn query_kid_for_attestation_key_and_cert_chain(
2058 &self,
2059 tx: &Transaction,
2060 domain: Domain,
2061 namespace: i64,
2062 km_uuid: &Uuid,
2063 ) -> Result<Option<i64>> {
2064 let mut stmt = tx.prepare(
2065 "SELECT id
2066 FROM persistent.keyentry
2067 WHERE key_type = ?
2068 AND domain = ?
2069 AND namespace = ?
2070 AND state = ?
2071 AND km_uuid = ?;",
2072 )?;
2073 let rows = stmt
2074 .query_map(
2075 params![
2076 KeyType::Attestation,
2077 domain.0 as u32,
2078 namespace,
2079 KeyLifeCycle::Live,
2080 km_uuid
2081 ],
2082 |row| row.get(0),
2083 )?
2084 .collect::<rusqlite::Result<Vec<i64>>>()
2085 .context("query failed.")?;
2086 if rows.is_empty() {
2087 return Ok(None);
2088 }
2089 Ok(Some(rows[0]))
2090 }
2091
Max Bires2b2e6562020-09-22 11:22:36 -07002092 /// Fetches the private key and corresponding certificate chain assigned to a
2093 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2094 /// not assigned, or one CertificateChain.
2095 pub fn retrieve_attestation_key_and_cert_chain(
2096 &mut self,
2097 domain: Domain,
2098 namespace: i64,
2099 km_uuid: &Uuid,
Max Bires55620ff2022-02-11 13:34:15 -08002100 ) -> Result<Option<(KeyIdGuard, CertificateChain)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002101 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2102
Max Bires2b2e6562020-09-22 11:22:36 -07002103 match domain {
2104 Domain::APP | Domain::SELINUX => {}
2105 _ => {
2106 return Err(KsError::sys())
2107 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2108 }
2109 }
Max Bires55620ff2022-02-11 13:34:15 -08002110
Max Birescd7f7412022-02-11 13:47:36 -08002111 self.delete_expired_attestation_keys().context(
2112 "In retrieve_attestation_key_and_cert_chain: failed to prune expired attestation keys",
2113 )?;
Max Bires55620ff2022-02-11 13:34:15 -08002114 let tx = self.conn.unchecked_transaction().context(
2115 "In retrieve_attestation_key_and_cert_chain: Failed to initialize transaction.",
2116 )?;
2117 let key_id: i64;
2118 match self.query_kid_for_attestation_key_and_cert_chain(&tx, domain, namespace, km_uuid)? {
2119 None => return Ok(None),
2120 Some(kid) => key_id = kid,
2121 }
2122 tx.commit()
2123 .context("In retrieve_attestation_key_and_cert_chain: Failed to commit keyid query")?;
2124 let key_id_guard = KEY_ID_LOCK.get(key_id);
2125 let tx = self.conn.unchecked_transaction().context(
2126 "In retrieve_attestation_key_and_cert_chain: Failed to initialize transaction.",
2127 )?;
2128 let mut stmt = tx.prepare(
2129 "SELECT subcomponent_type, blob
2130 FROM persistent.blobentry
2131 WHERE keyentryid = ?;",
2132 )?;
2133 let rows = stmt
2134 .query_map(params![key_id_guard.id()], |row| Ok((row.get(0)?, row.get(1)?)))?
2135 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
2136 .context("query failed.")?;
2137 if rows.is_empty() {
2138 return Ok(None);
2139 } else if rows.len() != 3 {
2140 return Err(KsError::sys()).context(format!(
2141 concat!(
2142 "Expected to get a single attestation",
2143 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2144 ),
2145 rows.len()
2146 ));
2147 }
2148 let mut km_blob: Vec<u8> = Vec::new();
2149 let mut cert_chain_blob: Vec<u8> = Vec::new();
2150 let mut batch_cert_blob: Vec<u8> = Vec::new();
2151 for row in rows {
2152 let sub_type: SubComponentType = row.0;
2153 match sub_type {
2154 SubComponentType::KEY_BLOB => {
2155 km_blob = row.1;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002156 }
Max Bires55620ff2022-02-11 13:34:15 -08002157 SubComponentType::CERT_CHAIN => {
2158 cert_chain_blob = row.1;
2159 }
2160 SubComponentType::CERT => {
2161 batch_cert_blob = row.1;
2162 }
2163 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002164 }
Max Bires55620ff2022-02-11 13:34:15 -08002165 }
2166 Ok(Some((
2167 key_id_guard,
2168 CertificateChain {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002169 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002170 batch_cert: batch_cert_blob,
2171 cert_chain: cert_chain_blob,
Max Bires55620ff2022-02-11 13:34:15 -08002172 },
2173 )))
Max Bires2b2e6562020-09-22 11:22:36 -07002174 }
2175
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002176 /// Updates the alias column of the given key id `newid` with the given alias,
2177 /// and atomically, removes the alias, domain, and namespace from another row
2178 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002179 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2180 /// collector.
2181 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002182 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002183 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002184 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002185 domain: &Domain,
2186 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002187 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002188 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002189 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002190 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002191 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002192 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002193 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002194 domain
2195 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002196 }
2197 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002198 let updated = tx
2199 .execute(
2200 "UPDATE persistent.keyentry
2201 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002202 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2203 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002204 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002205 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002206 let result = tx
2207 .execute(
2208 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002209 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002210 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002211 params![
2212 alias,
2213 KeyLifeCycle::Live,
2214 newid.0,
2215 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002216 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002217 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002218 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002219 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002220 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002221 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002222 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002223 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002224 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002225 result
2226 ));
2227 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002228 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002229 }
2230
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002231 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2232 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2233 pub fn migrate_key_namespace(
2234 &mut self,
2235 key_id_guard: KeyIdGuard,
2236 destination: &KeyDescriptor,
2237 caller_uid: u32,
2238 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2239 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002240 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2241
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002242 let destination = match destination.domain {
2243 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2244 Domain::SELINUX => (*destination).clone(),
2245 domain => {
2246 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2247 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2248 }
2249 };
2250
2251 // Security critical: Must return immediately on failure. Do not remove the '?';
2252 check_permission(&destination)
2253 .context("In migrate_key_namespace: Trying to check permission.")?;
2254
2255 let alias = destination
2256 .alias
2257 .as_ref()
2258 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2259 .context("In migrate_key_namespace: Alias must be specified.")?;
2260
2261 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2262 // Query the destination location. If there is a key, the migration request fails.
2263 if tx
2264 .query_row(
2265 "SELECT id FROM persistent.keyentry
2266 WHERE alias = ? AND domain = ? AND namespace = ?;",
2267 params![alias, destination.domain.0, destination.nspace],
2268 |_| Ok(()),
2269 )
2270 .optional()
2271 .context("Failed to query destination.")?
2272 .is_some()
2273 {
2274 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2275 .context("Target already exists.");
2276 }
2277
2278 let updated = tx
2279 .execute(
2280 "UPDATE persistent.keyentry
2281 SET alias = ?, domain = ?, namespace = ?
2282 WHERE id = ?;",
2283 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2284 )
2285 .context("Failed to update key entry.")?;
2286
2287 if updated != 1 {
2288 return Err(KsError::sys())
2289 .context(format!("Update succeeded, but {} rows were updated.", updated));
2290 }
2291 Ok(()).no_gc()
2292 })
2293 .context("In migrate_key_namespace:")
2294 }
2295
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002296 /// Store a new key in a single transaction.
2297 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2298 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002299 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2300 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07002301 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002302 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002303 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002304 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002305 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002306 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002307 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08002308 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002309 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002310 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002311 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002312 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2313
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002314 let (alias, domain, namespace) = match key {
2315 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2316 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2317 (alias, key.domain, nspace)
2318 }
2319 _ => {
2320 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2321 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2322 }
2323 };
2324 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002325 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002326 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002327 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
2328
2329 // In some occasions the key blob is already upgraded during the import.
2330 // In order to make sure it gets properly deleted it is inserted into the
2331 // database here and then immediately replaced by the superseding blob.
2332 // The garbage collector will then subject the blob to deleteKey of the
2333 // KM back end to permanently invalidate the key.
2334 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
2335 Self::set_blob_internal(
2336 tx,
2337 key_id.id(),
2338 SubComponentType::KEY_BLOB,
2339 Some(blob),
2340 Some(blob_metadata),
2341 )
2342 .context("Trying to insert superseded key blob.")?;
2343 true
2344 } else {
2345 false
2346 };
2347
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002348 Self::set_blob_internal(
2349 tx,
2350 key_id.id(),
2351 SubComponentType::KEY_BLOB,
2352 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002353 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002354 )
2355 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002356 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002357 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002358 .context("Trying to insert the certificate.")?;
2359 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002360 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002361 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002362 tx,
2363 key_id.id(),
2364 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002365 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002366 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002367 )
2368 .context("Trying to insert the certificate chain.")?;
2369 }
2370 Self::insert_keyparameter_internal(tx, &key_id, params)
2371 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002372 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002373 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002374 .context("Trying to rebind alias.")?
2375 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002376 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002377 })
2378 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002379 }
2380
Janis Danisevskis377d1002021-01-27 19:07:48 -08002381 /// Store a new certificate
2382 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2383 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002384 pub fn store_new_certificate(
2385 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002386 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002387 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002388 cert: &[u8],
2389 km_uuid: &Uuid,
2390 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002391 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2392
Janis Danisevskis377d1002021-01-27 19:07:48 -08002393 let (alias, domain, namespace) = match key {
2394 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2395 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2396 (alias, key.domain, nspace)
2397 }
2398 _ => {
2399 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2400 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2401 )
2402 }
2403 };
2404 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002405 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002406 .context("Trying to create new key entry.")?;
2407
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002408 Self::set_blob_internal(
2409 tx,
2410 key_id.id(),
2411 SubComponentType::CERT_CHAIN,
2412 Some(cert),
2413 None,
2414 )
2415 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002416
2417 let mut metadata = KeyMetaData::new();
2418 metadata.add(KeyMetaEntry::CreationDate(
2419 DateTime::now().context("Trying to make creation time.")?,
2420 ));
2421
2422 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2423
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002424 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002425 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002426 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002427 })
2428 .context("In store_new_certificate.")
2429 }
2430
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002431 // Helper function loading the key_id given the key descriptor
2432 // tuple comprising domain, namespace, and alias.
2433 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002434 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002435 let alias = key
2436 .alias
2437 .as_ref()
2438 .map_or_else(|| Err(KsError::sys()), Ok)
2439 .context("In load_key_entry_id: Alias must be specified.")?;
2440 let mut stmt = tx
2441 .prepare(
2442 "SELECT id FROM persistent.keyentry
2443 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002444 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002445 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002446 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002447 AND alias = ?
2448 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002449 )
2450 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2451 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002452 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002453 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002454 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002455 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002456 .get(0)
2457 .context("Failed to unpack id.")
2458 })
2459 .context("In load_key_entry_id.")
2460 }
2461
2462 /// This helper function completes the access tuple of a key, which is required
2463 /// to perform access control. The strategy depends on the `domain` field in the
2464 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002465 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002466 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002467 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002468 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002469 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002470 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002471 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002472 /// `namespace`.
2473 /// In each case the information returned is sufficient to perform the access
2474 /// check and the key id can be used to load further key artifacts.
2475 fn load_access_tuple(
2476 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002477 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002478 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002479 caller_uid: u32,
2480 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2481 match key.domain {
2482 // Domain App or SELinux. In this case we load the key_id from
2483 // the keyentry database for further loading of key components.
2484 // We already have the full access tuple to perform access control.
2485 // The only distinction is that we use the caller_uid instead
2486 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002487 // Domain::APP.
2488 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002489 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002490 if access_key.domain == Domain::APP {
2491 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002492 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002493 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002494 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002495
2496 Ok((key_id, access_key, None))
2497 }
2498
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002499 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002500 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002501 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002502 let mut stmt = tx
2503 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002504 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002505 WHERE grantee = ? AND id = ? AND
2506 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002507 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002508 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002509 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002510 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002511 .context("Domain:Grant: query failed.")?;
2512 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002513 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002514 let r =
2515 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002516 Ok((
2517 r.get(0).context("Failed to unpack key_id.")?,
2518 r.get(1).context("Failed to unpack access_vector.")?,
2519 ))
2520 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002521 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002522 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002523 }
2524
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002525 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002526 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002527 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002528 let (domain, namespace): (Domain, i64) = {
2529 let mut stmt = tx
2530 .prepare(
2531 "SELECT domain, namespace FROM persistent.keyentry
2532 WHERE
2533 id = ?
2534 AND state = ?;",
2535 )
2536 .context("Domain::KEY_ID: prepare statement failed")?;
2537 let mut rows = stmt
2538 .query(params![key.nspace, KeyLifeCycle::Live])
2539 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002540 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002541 let r =
2542 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002543 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002544 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002545 r.get(1).context("Failed to unpack namespace.")?,
2546 ))
2547 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002548 .context("Domain::KEY_ID.")?
2549 };
2550
2551 // We may use a key by id after loading it by grant.
2552 // In this case we have to check if the caller has a grant for this particular
2553 // key. We can skip this if we already know that the caller is the owner.
2554 // But we cannot know this if domain is anything but App. E.g. in the case
2555 // of Domain::SELINUX we have to speculatively check for grants because we have to
2556 // consult the SEPolicy before we know if the caller is the owner.
2557 let access_vector: Option<KeyPermSet> =
2558 if domain != Domain::APP || namespace != caller_uid as i64 {
2559 let access_vector: Option<i32> = tx
2560 .query_row(
2561 "SELECT access_vector FROM persistent.grant
2562 WHERE grantee = ? AND keyentryid = ?;",
2563 params![caller_uid as i64, key.nspace],
2564 |row| row.get(0),
2565 )
2566 .optional()
2567 .context("Domain::KEY_ID: query grant failed.")?;
2568 access_vector.map(|p| p.into())
2569 } else {
2570 None
2571 };
2572
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002573 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002574 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002575 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002576 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002577
Janis Danisevskis45760022021-01-19 16:34:10 -08002578 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002579 }
2580 _ => Err(anyhow!(KsError::sys())),
2581 }
2582 }
2583
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002584 fn load_blob_components(
2585 key_id: i64,
2586 load_bits: KeyEntryLoadBits,
2587 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002588 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002589 let mut stmt = tx
2590 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002591 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002592 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2593 )
2594 .context("In load_blob_components: prepare statement failed.")?;
2595
2596 let mut rows =
2597 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2598
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002599 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002600 let mut cert_blob: Option<Vec<u8>> = None;
2601 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002602 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002603 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002604 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002605 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002606 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002607 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2608 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002609 key_blob = Some((
2610 row.get(0).context("Failed to extract key blob id.")?,
2611 row.get(2).context("Failed to extract key blob.")?,
2612 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002613 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002614 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002615 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002616 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002617 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002618 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002619 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002620 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002621 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002622 (SubComponentType::CERT, _, _)
2623 | (SubComponentType::CERT_CHAIN, _, _)
2624 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002625 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2626 }
2627 Ok(())
2628 })
2629 .context("In load_blob_components.")?;
2630
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002631 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2632 Ok(Some((
2633 blob,
2634 BlobMetaData::load_from_db(blob_id, tx)
2635 .context("In load_blob_components: Trying to load blob_metadata.")?,
2636 )))
2637 })?;
2638
2639 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002640 }
2641
2642 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2643 let mut stmt = tx
2644 .prepare(
2645 "SELECT tag, data, security_level from persistent.keyparameter
2646 WHERE keyentryid = ?;",
2647 )
2648 .context("In load_key_parameters: prepare statement failed.")?;
2649
2650 let mut parameters: Vec<KeyParameter> = Vec::new();
2651
2652 let mut rows =
2653 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002654 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002655 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2656 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002657 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002658 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002659 .context("Failed to read KeyParameter.")?,
2660 );
2661 Ok(())
2662 })
2663 .context("In load_key_parameters.")?;
2664
2665 Ok(parameters)
2666 }
2667
Qi Wub9433b52020-12-01 14:52:46 +08002668 /// Decrements the usage count of a limited use key. This function first checks whether the
2669 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2670 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2671 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002672 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002673 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2674
Qi Wub9433b52020-12-01 14:52:46 +08002675 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2676 let limit: Option<i32> = tx
2677 .query_row(
2678 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2679 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2680 |row| row.get(0),
2681 )
2682 .optional()
2683 .context("Trying to load usage count")?;
2684
2685 let limit = limit
2686 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2687 .context("The Key no longer exists. Key is exhausted.")?;
2688
2689 tx.execute(
2690 "UPDATE persistent.keyparameter
2691 SET data = data - 1
2692 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2693 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2694 )
2695 .context("Failed to update key usage count.")?;
2696
2697 match limit {
2698 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002699 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002700 .context("Trying to mark limited use key for deletion."),
2701 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002702 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002703 }
2704 })
2705 .context("In check_and_update_key_usage_count.")
2706 }
2707
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002708 /// Load a key entry by the given key descriptor.
2709 /// It uses the `check_permission` callback to verify if the access is allowed
2710 /// given the key access tuple read from the database using `load_access_tuple`.
2711 /// With `load_bits` the caller may specify which blobs shall be loaded from
2712 /// the blob database.
2713 pub fn load_key_entry(
2714 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002715 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002716 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002717 load_bits: KeyEntryLoadBits,
2718 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002719 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2720 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002721 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2722
Janis Danisevskis66784c42021-01-27 08:40:25 -08002723 loop {
2724 match self.load_key_entry_internal(
2725 key,
2726 key_type,
2727 load_bits,
2728 caller_uid,
2729 &check_permission,
2730 ) {
2731 Ok(result) => break Ok(result),
2732 Err(e) => {
2733 if Self::is_locked_error(&e) {
2734 std::thread::sleep(std::time::Duration::from_micros(500));
2735 continue;
2736 } else {
2737 return Err(e).context("In load_key_entry.");
2738 }
2739 }
2740 }
2741 }
2742 }
2743
2744 fn load_key_entry_internal(
2745 &mut self,
2746 key: &KeyDescriptor,
2747 key_type: KeyType,
2748 load_bits: KeyEntryLoadBits,
2749 caller_uid: u32,
2750 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002751 ) -> Result<(KeyIdGuard, KeyEntry)> {
2752 // KEY ID LOCK 1/2
2753 // If we got a key descriptor with a key id we can get the lock right away.
2754 // Otherwise we have to defer it until we know the key id.
2755 let key_id_guard = match key.domain {
2756 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2757 _ => None,
2758 };
2759
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002760 let tx = self
2761 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002762 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002763 .context("In load_key_entry: Failed to initialize transaction.")?;
2764
2765 // Load the key_id and complete the access control tuple.
2766 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002767 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2768 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002769
2770 // Perform access control. It is vital that we return here if the permission is denied.
2771 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002772 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002773
Janis Danisevskisaec14592020-11-12 09:41:49 -08002774 // KEY ID LOCK 2/2
2775 // If we did not get a key id lock by now, it was because we got a key descriptor
2776 // without a key id. At this point we got the key id, so we can try and get a lock.
2777 // However, we cannot block here, because we are in the middle of the transaction.
2778 // So first we try to get the lock non blocking. If that fails, we roll back the
2779 // transaction and block until we get the lock. After we successfully got the lock,
2780 // we start a new transaction and load the access tuple again.
2781 //
2782 // We don't need to perform access control again, because we already established
2783 // that the caller had access to the given key. But we need to make sure that the
2784 // key id still exists. So we have to load the key entry by key id this time.
2785 let (key_id_guard, tx) = match key_id_guard {
2786 None => match KEY_ID_LOCK.try_get(key_id) {
2787 None => {
2788 // Roll back the transaction.
2789 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002790
Janis Danisevskisaec14592020-11-12 09:41:49 -08002791 // Block until we have a key id lock.
2792 let key_id_guard = KEY_ID_LOCK.get(key_id);
2793
2794 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002795 let tx = self
2796 .conn
2797 .unchecked_transaction()
2798 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002799
2800 Self::load_access_tuple(
2801 &tx,
2802 // This time we have to load the key by the retrieved key id, because the
2803 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002804 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002805 domain: Domain::KEY_ID,
2806 nspace: key_id,
2807 ..Default::default()
2808 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002809 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002810 caller_uid,
2811 )
2812 .context("In load_key_entry. (deferred key lock)")?;
2813 (key_id_guard, tx)
2814 }
2815 Some(l) => (l, tx),
2816 },
2817 Some(key_id_guard) => (key_id_guard, tx),
2818 };
2819
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002820 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2821 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002822
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002823 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2824
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002825 Ok((key_id_guard, key_entry))
2826 }
2827
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002828 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002829 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002830 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2831 .context("Trying to delete keyentry.")?;
2832 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2833 .context("Trying to delete keymetadata.")?;
2834 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2835 .context("Trying to delete keyparameters.")?;
2836 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2837 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002838 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002839 }
2840
2841 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002842 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002843 pub fn unbind_key(
2844 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002845 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002846 key_type: KeyType,
2847 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002848 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002849 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002850 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2851
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002852 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2853 let (key_id, access_key_descriptor, access_vector) =
2854 Self::load_access_tuple(tx, key, key_type, caller_uid)
2855 .context("Trying to get access tuple.")?;
2856
2857 // Perform access control. It is vital that we return here if the permission is denied.
2858 // So do not touch that '?' at the end.
2859 check_permission(&access_key_descriptor, access_vector)
2860 .context("While checking permission.")?;
2861
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002862 Self::mark_unreferenced(tx, key_id)
2863 .map(|need_gc| (need_gc, ()))
2864 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002865 })
2866 .context("In unbind_key.")
2867 }
2868
Max Bires8e93d2b2021-01-14 13:17:59 -08002869 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2870 tx.query_row(
2871 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2872 params![key_id],
2873 |row| row.get(0),
2874 )
2875 .context("In get_key_km_uuid.")
2876 }
2877
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002878 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2879 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2880 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002881 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2882
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002883 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2884 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2885 .context("In unbind_keys_for_namespace.");
2886 }
2887 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2888 tx.execute(
2889 "DELETE FROM persistent.keymetadata
2890 WHERE keyentryid IN (
2891 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002892 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002893 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002894 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002895 )
2896 .context("Trying to delete keymetadata.")?;
2897 tx.execute(
2898 "DELETE FROM persistent.keyparameter
2899 WHERE keyentryid IN (
2900 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002901 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002902 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002903 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002904 )
2905 .context("Trying to delete keyparameters.")?;
2906 tx.execute(
2907 "DELETE FROM persistent.grant
2908 WHERE keyentryid IN (
2909 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002910 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002911 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002912 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002913 )
2914 .context("Trying to delete grants.")?;
2915 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002916 "DELETE FROM persistent.keyentry
2917 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2918 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002919 )
2920 .context("Trying to delete keyentry.")?;
2921 Ok(()).need_gc()
2922 })
2923 .context("In unbind_keys_for_namespace")
2924 }
2925
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002926 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2927 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2928 {
2929 tx.execute(
2930 "DELETE FROM persistent.keymetadata
2931 WHERE keyentryid IN (
2932 SELECT id FROM persistent.keyentry
2933 WHERE state = ?
2934 );",
2935 params![KeyLifeCycle::Unreferenced],
2936 )
2937 .context("Trying to delete keymetadata.")?;
2938 tx.execute(
2939 "DELETE FROM persistent.keyparameter
2940 WHERE keyentryid IN (
2941 SELECT id FROM persistent.keyentry
2942 WHERE state = ?
2943 );",
2944 params![KeyLifeCycle::Unreferenced],
2945 )
2946 .context("Trying to delete keyparameters.")?;
2947 tx.execute(
2948 "DELETE FROM persistent.grant
2949 WHERE keyentryid IN (
2950 SELECT id FROM persistent.keyentry
2951 WHERE state = ?
2952 );",
2953 params![KeyLifeCycle::Unreferenced],
2954 )
2955 .context("Trying to delete grants.")?;
2956 tx.execute(
2957 "DELETE FROM persistent.keyentry
2958 WHERE state = ?;",
2959 params![KeyLifeCycle::Unreferenced],
2960 )
2961 .context("Trying to delete keyentry.")?;
2962 Result::<()>::Ok(())
2963 }
2964 .context("In cleanup_unreferenced")
2965 }
2966
Hasini Gunasingheda895552021-01-27 19:34:37 +00002967 /// Delete the keys created on behalf of the user, denoted by the user id.
2968 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2969 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2970 /// The caller of this function should notify the gc if the returned value is true.
2971 pub fn unbind_keys_for_user(
2972 &mut self,
2973 user_id: u32,
2974 keep_non_super_encrypted_keys: bool,
2975 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002976 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2977
Hasini Gunasingheda895552021-01-27 19:34:37 +00002978 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2979 let mut stmt = tx
2980 .prepare(&format!(
2981 "SELECT id from persistent.keyentry
2982 WHERE (
2983 key_type = ?
2984 AND domain = ?
2985 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2986 AND state = ?
2987 ) OR (
2988 key_type = ?
2989 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002990 AND state = ?
2991 );",
2992 aid_user_offset = AID_USER_OFFSET
2993 ))
2994 .context(concat!(
2995 "In unbind_keys_for_user. ",
2996 "Failed to prepare the query to find the keys created by apps."
2997 ))?;
2998
2999 let mut rows = stmt
3000 .query(params![
3001 // WHERE client key:
3002 KeyType::Client,
3003 Domain::APP.0 as u32,
3004 user_id,
3005 KeyLifeCycle::Live,
3006 // OR super key:
3007 KeyType::Super,
3008 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00003009 KeyLifeCycle::Live
3010 ])
3011 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
3012
3013 let mut key_ids: Vec<i64> = Vec::new();
3014 db_utils::with_rows_extract_all(&mut rows, |row| {
3015 key_ids
3016 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
3017 Ok(())
3018 })
3019 .context("In unbind_keys_for_user.")?;
3020
3021 let mut notify_gc = false;
3022 for key_id in key_ids {
3023 if keep_non_super_encrypted_keys {
3024 // Load metadata and filter out non-super-encrypted keys.
3025 if let (_, Some((_, blob_metadata)), _, _) =
3026 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
3027 .context("In unbind_keys_for_user: Trying to load blob info.")?
3028 {
3029 if blob_metadata.encrypted_by().is_none() {
3030 continue;
3031 }
3032 }
3033 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003034 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00003035 .context("In unbind_keys_for_user.")?
3036 || notify_gc;
3037 }
3038 Ok(()).do_gc(notify_gc)
3039 })
3040 .context("In unbind_keys_for_user.")
3041 }
3042
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003043 fn load_key_components(
3044 tx: &Transaction,
3045 load_bits: KeyEntryLoadBits,
3046 key_id: i64,
3047 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003048 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003049
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003050 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003051 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003052
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003053 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08003054 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003055
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003056 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08003057 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003058
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003059 Ok(KeyEntry {
3060 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003061 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003062 cert: cert_blob,
3063 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003064 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003065 parameters,
3066 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003067 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003068 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003069 }
3070
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003071 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3072 /// The key descriptors will have the domain, nspace, and alias field set.
3073 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07003074 pub fn list(
3075 &mut self,
3076 domain: Domain,
3077 namespace: i64,
3078 key_type: KeyType,
3079 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003080 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3081
Janis Danisevskis66784c42021-01-27 08:40:25 -08003082 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3083 let mut stmt = tx
3084 .prepare(
3085 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07003086 WHERE domain = ?
3087 AND namespace = ?
3088 AND alias IS NOT NULL
3089 AND state = ?
3090 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003091 )
3092 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003093
Janis Danisevskis66784c42021-01-27 08:40:25 -08003094 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003095 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08003096 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003097
Janis Danisevskis66784c42021-01-27 08:40:25 -08003098 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3099 db_utils::with_rows_extract_all(&mut rows, |row| {
3100 descriptors.push(KeyDescriptor {
3101 domain,
3102 nspace: namespace,
3103 alias: Some(row.get(0).context("Trying to extract alias.")?),
3104 blob: None,
3105 });
3106 Ok(())
3107 })
3108 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003109 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003110 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003111 }
3112
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003113 /// Adds a grant to the grant table.
3114 /// Like `load_key_entry` this function loads the access tuple before
3115 /// it uses the callback for a permission check. Upon success,
3116 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3117 /// grant table. The new row will have a randomized id, which is used as
3118 /// grant id in the namespace field of the resulting KeyDescriptor.
3119 pub fn grant(
3120 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003121 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003122 caller_uid: u32,
3123 grantee_uid: u32,
3124 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003125 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003126 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003127 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3128
Janis Danisevskis66784c42021-01-27 08:40:25 -08003129 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3130 // Load the key_id and complete the access control tuple.
3131 // We ignore the access vector here because grants cannot be granted.
3132 // The access vector returned here expresses the permissions the
3133 // grantee has if key.domain == Domain::GRANT. But this vector
3134 // cannot include the grant permission by design, so there is no way the
3135 // subsequent permission check can pass.
3136 // We could check key.domain == Domain::GRANT and fail early.
3137 // But even if we load the access tuple by grant here, the permission
3138 // check denies the attempt to create a grant by grant descriptor.
3139 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003140 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003141 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003142
Janis Danisevskis66784c42021-01-27 08:40:25 -08003143 // Perform access control. It is vital that we return here if the permission
3144 // was denied. So do not touch that '?' at the end of the line.
3145 // This permission check checks if the caller has the grant permission
3146 // for the given key and in addition to all of the permissions
3147 // expressed in `access_vector`.
3148 check_permission(&access_key_descriptor, &access_vector)
3149 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003150
Janis Danisevskis66784c42021-01-27 08:40:25 -08003151 let grant_id = if let Some(grant_id) = tx
3152 .query_row(
3153 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003154 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003155 params![key_id, grantee_uid],
3156 |row| row.get(0),
3157 )
3158 .optional()
3159 .context("In grant: Failed get optional existing grant id.")?
3160 {
3161 tx.execute(
3162 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003163 SET access_vector = ?
3164 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003165 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003166 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003167 .context("In grant: Failed to update existing grant.")?;
3168 grant_id
3169 } else {
3170 Self::insert_with_retry(|id| {
3171 tx.execute(
3172 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3173 VALUES (?, ?, ?, ?);",
3174 params![id, grantee_uid, key_id, i32::from(access_vector)],
3175 )
3176 })
3177 .context("In grant")?
3178 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003179
Janis Danisevskis66784c42021-01-27 08:40:25 -08003180 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003181 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003182 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003183 }
3184
3185 /// This function checks permissions like `grant` and `load_key_entry`
3186 /// before removing a grant from the grant table.
3187 pub fn ungrant(
3188 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003189 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003190 caller_uid: u32,
3191 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003192 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003193 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003194 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3195
Janis Danisevskis66784c42021-01-27 08:40:25 -08003196 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3197 // Load the key_id and complete the access control tuple.
3198 // We ignore the access vector here because grants cannot be granted.
3199 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003200 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003201 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003202
Janis Danisevskis66784c42021-01-27 08:40:25 -08003203 // Perform access control. We must return here if the permission
3204 // was denied. So do not touch the '?' at the end of this line.
3205 check_permission(&access_key_descriptor)
3206 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003207
Janis Danisevskis66784c42021-01-27 08:40:25 -08003208 tx.execute(
3209 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003210 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003211 params![key_id, grantee_uid],
3212 )
3213 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003214
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003215 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003216 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003217 }
3218
Joel Galenson845f74b2020-09-09 14:11:55 -07003219 // Generates a random id and passes it to the given function, which will
3220 // try to insert it into a database. If that insertion fails, retry;
3221 // otherwise return the id.
3222 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3223 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003224 let newid: i64 = match random() {
3225 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3226 i => i,
3227 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003228 match inserter(newid) {
3229 // If the id already existed, try again.
3230 Err(rusqlite::Error::SqliteFailure(
3231 libsqlite3_sys::Error {
3232 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3233 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3234 },
3235 _,
3236 )) => (),
3237 Err(e) => {
3238 return Err(e).context("In insert_with_retry: failed to insert into database.")
3239 }
3240 _ => return Ok(newid),
3241 }
3242 }
3243 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003244
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003245 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3246 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3247 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3248 auth_token.clone(),
3249 MonotonicRawTime::now(),
3250 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003251 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003252
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003253 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003254 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003255 where
3256 F: Fn(&AuthTokenEntry) -> bool,
3257 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003258 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003259 }
3260
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003261 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003262 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3263 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003264 }
3265
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003266 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003267 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3268 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003269 }
3270
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003271 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003272 fn get_last_off_body(&self) -> MonotonicRawTime {
3273 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003274 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003275
3276 /// Load descriptor of a key by key id
3277 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3278 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3279
3280 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3281 tx.query_row(
3282 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3283 params![key_id],
3284 |row| {
3285 Ok(KeyDescriptor {
3286 domain: Domain(row.get(0)?),
3287 nspace: row.get(1)?,
3288 alias: row.get(2)?,
3289 blob: None,
3290 })
3291 },
3292 )
3293 .optional()
3294 .context("Trying to load key descriptor")
3295 .no_gc()
3296 })
3297 .context("In load_key_descriptor.")
3298 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003299}
3300
3301#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08003302pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07003303
3304 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003305 use crate::key_parameter::{
3306 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3307 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3308 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003309 use crate::key_perm_set;
3310 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08003311 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003312 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003313 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3314 HardwareAuthToken::HardwareAuthToken,
3315 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003316 };
3317 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003318 Timestamp::Timestamp,
3319 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003320 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003321 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003322 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003323 use std::collections::BTreeMap;
3324 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003325 use std::sync::atomic::{AtomicU8, Ordering};
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003326 use std::sync::{Arc, RwLock};
Janis Danisevskisaec14592020-11-12 09:41:49 -08003327 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003328 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003329 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003330 #[cfg(disabled)]
3331 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003332
Seth Moore7ee79f92021-12-07 11:42:49 -08003333 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003334 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003335
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003336 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003337 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003338 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003339 })?;
3340 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003341 }
3342
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003343 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3344 where
3345 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3346 {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003347 let super_key: Arc<RwLock<SuperKeyManager>> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003348
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003349 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003350 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003351
Janis Danisevskis3395f862021-05-06 10:54:17 -07003352 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003353 }
3354
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003355 fn rebind_alias(
3356 db: &mut KeystoreDB,
3357 newid: &KeyIdGuard,
3358 alias: &str,
3359 domain: Domain,
3360 namespace: i64,
3361 ) -> Result<bool> {
3362 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003363 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003364 })
3365 .context("In rebind_alias.")
3366 }
3367
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003368 #[test]
3369 fn datetime() -> Result<()> {
3370 let conn = Connection::open_in_memory()?;
3371 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3372 let now = SystemTime::now();
3373 let duration = Duration::from_secs(1000);
3374 let then = now.checked_sub(duration).unwrap();
3375 let soon = now.checked_add(duration).unwrap();
3376 conn.execute(
3377 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3378 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3379 )?;
3380 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3381 let mut rows = stmt.query(NO_PARAMS)?;
3382 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3383 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3384 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3385 assert!(rows.next()?.is_none());
3386 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3387 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3388 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3389 Ok(())
3390 }
3391
Joel Galenson0891bc12020-07-20 10:37:03 -07003392 // Ensure that we're using the "injected" random function, not the real one.
3393 #[test]
3394 fn test_mocked_random() {
3395 let rand1 = random();
3396 let rand2 = random();
3397 let rand3 = random();
3398 if rand1 == rand2 {
3399 assert_eq!(rand2 + 1, rand3);
3400 } else {
3401 assert_eq!(rand1 + 1, rand2);
3402 assert_eq!(rand2, rand3);
3403 }
3404 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003405
Joel Galenson26f4d012020-07-17 14:57:21 -07003406 // Test that we have the correct tables.
3407 #[test]
3408 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003409 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003410 let tables = db
3411 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003412 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003413 .query_map(params![], |row| row.get(0))?
3414 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003415 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003416 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003417 assert_eq!(tables[1], "blobmetadata");
3418 assert_eq!(tables[2], "grant");
3419 assert_eq!(tables[3], "keyentry");
3420 assert_eq!(tables[4], "keymetadata");
3421 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003422 Ok(())
3423 }
3424
3425 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003426 fn test_auth_token_table_invariant() -> Result<()> {
3427 let mut db = new_test_db()?;
3428 let auth_token1 = HardwareAuthToken {
3429 challenge: i64::MAX,
3430 userId: 200,
3431 authenticatorId: 200,
3432 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3433 timestamp: Timestamp { milliSeconds: 500 },
3434 mac: String::from("mac").into_bytes(),
3435 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003436 db.insert_auth_token(&auth_token1);
3437 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003438 assert_eq!(auth_tokens_returned.len(), 1);
3439
3440 // insert another auth token with the same values for the columns in the UNIQUE constraint
3441 // of the auth token table and different value for timestamp
3442 let auth_token2 = HardwareAuthToken {
3443 challenge: i64::MAX,
3444 userId: 200,
3445 authenticatorId: 200,
3446 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3447 timestamp: Timestamp { milliSeconds: 600 },
3448 mac: String::from("mac").into_bytes(),
3449 };
3450
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003451 db.insert_auth_token(&auth_token2);
3452 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003453 assert_eq!(auth_tokens_returned.len(), 1);
3454
3455 if let Some(auth_token) = auth_tokens_returned.pop() {
3456 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3457 }
3458
3459 // insert another auth token with the different values for the columns in the UNIQUE
3460 // constraint of the auth token table
3461 let auth_token3 = HardwareAuthToken {
3462 challenge: i64::MAX,
3463 userId: 201,
3464 authenticatorId: 200,
3465 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3466 timestamp: Timestamp { milliSeconds: 600 },
3467 mac: String::from("mac").into_bytes(),
3468 };
3469
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003470 db.insert_auth_token(&auth_token3);
3471 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003472 assert_eq!(auth_tokens_returned.len(), 2);
3473
3474 Ok(())
3475 }
3476
3477 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003478 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3479 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003480 }
3481
3482 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003483 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003484 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003485 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003486
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003487 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003488 let entries = get_keyentry(&db)?;
3489 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003490
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003491 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003492
3493 let entries_new = get_keyentry(&db)?;
3494 assert_eq!(entries, entries_new);
3495 Ok(())
3496 }
3497
3498 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003499 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003500 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3501 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003502 }
3503
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003504 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003505
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003506 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3507 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003508
3509 let entries = get_keyentry(&db)?;
3510 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003511 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3512 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003513
3514 // Test that we must pass in a valid Domain.
3515 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003516 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003517 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003518 );
3519 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003520 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003521 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003522 );
3523 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003524 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003525 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003526 );
3527
3528 Ok(())
3529 }
3530
Joel Galenson33c04ad2020-08-03 11:04:38 -07003531 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003532 fn test_add_unsigned_key() -> Result<()> {
3533 let mut db = new_test_db()?;
3534 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3535 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3536 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3537 db.create_attestation_key_entry(
3538 &public_key,
3539 &raw_public_key,
3540 &private_key,
3541 &KEYSTORE_UUID,
3542 )?;
3543 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3544 assert_eq!(keys.len(), 1);
3545 assert_eq!(keys[0], public_key);
3546 Ok(())
3547 }
3548
3549 #[test]
3550 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3551 let mut db = new_test_db()?;
Max Birescd7f7412022-02-11 13:47:36 -08003552 let expiration_date: i64 =
3553 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3554 + EXPIRATION_BUFFER_MS
3555 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003556 let namespace: i64 = 30;
3557 let base_byte: u8 = 1;
3558 let loaded_values =
3559 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3560 let chain =
3561 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Chris Wailes3877f292021-07-26 19:24:18 -07003562 assert!(chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003563 let (_, cert_chain) = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003564 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003565 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3566 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003567 Ok(())
3568 }
3569
3570 #[test]
3571 fn test_get_attestation_pool_status() -> Result<()> {
3572 let mut db = new_test_db()?;
3573 let namespace: i64 = 30;
3574 load_attestation_key_pool(
3575 &mut db, 10, /* expiration */
3576 namespace, 0x01, /* base_byte */
3577 )?;
3578 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3579 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3580 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3581 assert_eq!(status.expiring, 0);
3582 assert_eq!(status.attested, 3);
3583 assert_eq!(status.unassigned, 0);
3584 assert_eq!(status.total, 3);
3585 assert_eq!(
3586 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3587 1
3588 );
3589 assert_eq!(
3590 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3591 2
3592 );
3593 assert_eq!(
3594 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3595 3
3596 );
3597 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3598 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3599 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3600 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003601 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003602 db.create_attestation_key_entry(
3603 &public_key,
3604 &raw_public_key,
3605 &private_key,
3606 &KEYSTORE_UUID,
3607 )?;
3608 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3609 assert_eq!(status.attested, 3);
3610 assert_eq!(status.unassigned, 0);
3611 assert_eq!(status.total, 4);
3612 db.store_signed_attestation_certificate_chain(
3613 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003614 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003615 &cert_chain,
3616 20,
3617 &KEYSTORE_UUID,
3618 )?;
3619 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3620 assert_eq!(status.attested, 4);
3621 assert_eq!(status.unassigned, 1);
3622 assert_eq!(status.total, 4);
3623 Ok(())
3624 }
3625
3626 #[test]
3627 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003628 let temp_dir =
3629 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3630 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003631 let expiration_date: i64 =
Max Birescd7f7412022-02-11 13:47:36 -08003632 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3633 + EXPIRATION_BUFFER_MS
3634 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003635 let namespace: i64 = 30;
3636 let namespace_del1: i64 = 45;
3637 let namespace_del2: i64 = 60;
3638 let entry_values = load_attestation_key_pool(
3639 &mut db,
3640 expiration_date,
3641 namespace,
3642 0x01, /* base_byte */
3643 )?;
3644 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
Max Birescd7f7412022-02-11 13:47:36 -08003645 load_attestation_key_pool(&mut db, expiration_date - 10001, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003646
3647 let blob_entry_row_count: u32 = db
3648 .conn
3649 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3650 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003651 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3652 // one key, one certificate chain, and one certificate.
3653 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003654
Max Bires2b2e6562020-09-22 11:22:36 -07003655 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3656
3657 let mut cert_chain =
3658 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003659 assert!(cert_chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003660 let (_, value) = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003661 assert_eq!(entry_values.batch_cert, value.batch_cert);
3662 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003663 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003664
3665 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3666 Domain::APP,
3667 namespace_del1,
3668 &KEYSTORE_UUID,
3669 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003670 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003671 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3672 Domain::APP,
3673 namespace_del2,
3674 &KEYSTORE_UUID,
3675 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003676 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003677
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003678 // Give the garbage collector half a second to catch up.
3679 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003680
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003681 let blob_entry_row_count: u32 = db
3682 .conn
3683 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3684 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003685 // There shound be 3 blob entries left, because we deleted two of the attestation
3686 // key entries with three blobs each.
3687 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003688
Max Bires2b2e6562020-09-22 11:22:36 -07003689 Ok(())
3690 }
3691
Max Birescd7f7412022-02-11 13:47:36 -08003692 fn compare_rem_prov_values(
3693 expected: &RemoteProvValues,
3694 actual: Option<(KeyIdGuard, CertificateChain)>,
3695 ) {
3696 assert!(actual.is_some());
3697 let (_, value) = actual.unwrap();
3698 assert_eq!(expected.batch_cert, value.batch_cert);
3699 assert_eq!(expected.cert_chain, value.cert_chain);
3700 assert_eq!(expected.priv_key, value.private_key.to_vec());
3701 }
3702
3703 #[test]
3704 fn test_dont_remove_valid_certs() -> Result<()> {
3705 let temp_dir =
3706 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3707 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
3708 let expiration_date: i64 =
3709 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3710 + EXPIRATION_BUFFER_MS
3711 + 10000;
3712 let namespace1: i64 = 30;
3713 let namespace2: i64 = 45;
3714 let namespace3: i64 = 60;
3715 let entry_values1 = load_attestation_key_pool(
3716 &mut db,
3717 expiration_date,
3718 namespace1,
3719 0x01, /* base_byte */
3720 )?;
3721 let entry_values2 =
3722 load_attestation_key_pool(&mut db, expiration_date + 40000, namespace2, 0x02)?;
3723 let entry_values3 =
3724 load_attestation_key_pool(&mut db, expiration_date - 9000, namespace3, 0x03)?;
3725
3726 let blob_entry_row_count: u32 = db
3727 .conn
3728 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3729 .expect("Failed to get blob entry row count.");
3730 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3731 // one key, one certificate chain, and one certificate.
3732 assert_eq!(blob_entry_row_count, 9);
3733
3734 let mut cert_chain =
3735 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace1, &KEYSTORE_UUID)?;
3736 compare_rem_prov_values(&entry_values1, cert_chain);
3737
3738 cert_chain =
3739 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace2, &KEYSTORE_UUID)?;
3740 compare_rem_prov_values(&entry_values2, cert_chain);
3741
3742 cert_chain =
3743 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace3, &KEYSTORE_UUID)?;
3744 compare_rem_prov_values(&entry_values3, cert_chain);
3745
3746 // Give the garbage collector half a second to catch up.
3747 std::thread::sleep(Duration::from_millis(500));
3748
3749 let blob_entry_row_count: u32 = db
3750 .conn
3751 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3752 .expect("Failed to get blob entry row count.");
3753 // There shound be 9 blob entries left, because all three keys are valid with
3754 // three blobs each.
3755 assert_eq!(blob_entry_row_count, 9);
3756
3757 Ok(())
3758 }
Max Bires2b2e6562020-09-22 11:22:36 -07003759 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003760 fn test_delete_all_attestation_keys() -> Result<()> {
3761 let mut db = new_test_db()?;
3762 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3763 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003764 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003765 let result = db.delete_all_attestation_keys()?;
3766
3767 // Give the garbage collector half a second to catch up.
3768 std::thread::sleep(Duration::from_millis(500));
3769
3770 // Attestation keys should be deleted, and the regular key should remain.
3771 assert_eq!(result, 2);
3772
3773 Ok(())
3774 }
3775
3776 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003777 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003778 fn extractor(
3779 ke: &KeyEntryRow,
3780 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3781 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003782 }
3783
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003784 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003785 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3786 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003787 let entries = get_keyentry(&db)?;
3788 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003789 assert_eq!(
3790 extractor(&entries[0]),
3791 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3792 );
3793 assert_eq!(
3794 extractor(&entries[1]),
3795 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3796 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003797
3798 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003799 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003800 let entries = get_keyentry(&db)?;
3801 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003802 assert_eq!(
3803 extractor(&entries[0]),
3804 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3805 );
3806 assert_eq!(
3807 extractor(&entries[1]),
3808 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3809 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003810
3811 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003812 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003813 let entries = get_keyentry(&db)?;
3814 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003815 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3816 assert_eq!(
3817 extractor(&entries[1]),
3818 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3819 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003820
3821 // Test that we must pass in a valid Domain.
3822 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003823 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003824 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003825 );
3826 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003827 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003828 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003829 );
3830 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003831 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003832 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003833 );
3834
3835 // Test that we correctly handle setting an alias for something that does not exist.
3836 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003837 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003838 "Expected to update a single entry but instead updated 0",
3839 );
3840 // Test that we correctly abort the transaction in this case.
3841 let entries = get_keyentry(&db)?;
3842 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003843 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3844 assert_eq!(
3845 extractor(&entries[1]),
3846 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3847 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003848
3849 Ok(())
3850 }
3851
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003852 #[test]
3853 fn test_grant_ungrant() -> Result<()> {
3854 const CALLER_UID: u32 = 15;
3855 const GRANTEE_UID: u32 = 12;
3856 const SELINUX_NAMESPACE: i64 = 7;
3857
3858 let mut db = new_test_db()?;
3859 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003860 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3861 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3862 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003863 )?;
3864 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003865 domain: super::Domain::APP,
3866 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003867 alias: Some("key".to_string()),
3868 blob: None,
3869 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003870 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3871 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003872
3873 // Reset totally predictable random number generator in case we
3874 // are not the first test running on this thread.
3875 reset_random();
3876 let next_random = 0i64;
3877
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003878 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003879 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003880 assert_eq!(*a, PVEC1);
3881 assert_eq!(
3882 *k,
3883 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003884 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003885 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003886 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003887 alias: Some("key".to_string()),
3888 blob: None,
3889 }
3890 );
3891 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003892 })
3893 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003894
3895 assert_eq!(
3896 app_granted_key,
3897 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003898 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003899 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003900 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003901 alias: None,
3902 blob: None,
3903 }
3904 );
3905
3906 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003907 domain: super::Domain::SELINUX,
3908 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003909 alias: Some("yek".to_string()),
3910 blob: None,
3911 };
3912
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003913 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003914 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003915 assert_eq!(*a, PVEC1);
3916 assert_eq!(
3917 *k,
3918 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003919 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003920 // namespace must be the supplied SELinux
3921 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003922 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003923 alias: Some("yek".to_string()),
3924 blob: None,
3925 }
3926 );
3927 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003928 })
3929 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003930
3931 assert_eq!(
3932 selinux_granted_key,
3933 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003934 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003935 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003936 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003937 alias: None,
3938 blob: None,
3939 }
3940 );
3941
3942 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003943 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003944 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003945 assert_eq!(*a, PVEC2);
3946 assert_eq!(
3947 *k,
3948 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003949 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003950 // namespace must be the supplied SELinux
3951 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003952 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003953 alias: Some("yek".to_string()),
3954 blob: None,
3955 }
3956 );
3957 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003958 })
3959 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003960
3961 assert_eq!(
3962 selinux_granted_key,
3963 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003964 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003965 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003966 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003967 alias: None,
3968 blob: None,
3969 }
3970 );
3971
3972 {
3973 // Limiting scope of stmt, because it borrows db.
3974 let mut stmt = db
3975 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003976 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003977 let mut rows =
3978 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3979 Ok((
3980 row.get(0)?,
3981 row.get(1)?,
3982 row.get(2)?,
3983 KeyPermSet::from(row.get::<_, i32>(3)?),
3984 ))
3985 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003986
3987 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003988 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003989 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003990 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003991 assert!(rows.next().is_none());
3992 }
3993
3994 debug_dump_keyentry_table(&mut db)?;
3995 println!("app_key {:?}", app_key);
3996 println!("selinux_key {:?}", selinux_key);
3997
Janis Danisevskis66784c42021-01-27 08:40:25 -08003998 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3999 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004000
4001 Ok(())
4002 }
4003
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004004 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004005 static TEST_CERT_BLOB: &[u8] = b"my test cert";
4006 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
4007
4008 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004009 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004010 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004011 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004012 let mut blob_metadata = BlobMetaData::new();
4013 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4014 db.set_blob(
4015 &key_id,
4016 SubComponentType::KEY_BLOB,
4017 Some(TEST_KEY_BLOB),
4018 Some(&blob_metadata),
4019 )?;
4020 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4021 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004022 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004023
4024 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004025 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004026 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004027 )?;
4028 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004029 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
4030 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004031 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004032 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004033 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004034 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004035 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004036 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004037 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004038
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004039 drop(rows);
4040 drop(stmt);
4041
4042 assert_eq!(
4043 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4044 BlobMetaData::load_from_db(id, tx).no_gc()
4045 })
4046 .expect("Should find blob metadata."),
4047 blob_metadata
4048 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004049 Ok(())
4050 }
4051
4052 static TEST_ALIAS: &str = "my super duper key";
4053
4054 #[test]
4055 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
4056 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004057 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004058 .context("test_insert_and_load_full_keyentry_domain_app")?
4059 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004060 let (_key_guard, key_entry) = db
4061 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004062 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004063 domain: Domain::APP,
4064 nspace: 0,
4065 alias: Some(TEST_ALIAS.to_string()),
4066 blob: None,
4067 },
4068 KeyType::Client,
4069 KeyEntryLoadBits::BOTH,
4070 1,
4071 |_k, _av| Ok(()),
4072 )
4073 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004074 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004075
4076 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004077 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004078 domain: Domain::APP,
4079 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004080 alias: Some(TEST_ALIAS.to_string()),
4081 blob: None,
4082 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004083 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004084 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004085 |_, _| Ok(()),
4086 )
4087 .unwrap();
4088
4089 assert_eq!(
4090 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4091 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004092 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004093 domain: Domain::APP,
4094 nspace: 0,
4095 alias: Some(TEST_ALIAS.to_string()),
4096 blob: None,
4097 },
4098 KeyType::Client,
4099 KeyEntryLoadBits::NONE,
4100 1,
4101 |_k, _av| Ok(()),
4102 )
4103 .unwrap_err()
4104 .root_cause()
4105 .downcast_ref::<KsError>()
4106 );
4107
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004108 Ok(())
4109 }
4110
4111 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004112 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4113 let mut db = new_test_db()?;
4114
4115 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004116 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004117 domain: Domain::APP,
4118 nspace: 1,
4119 alias: Some(TEST_ALIAS.to_string()),
4120 blob: None,
4121 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004122 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004123 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004124 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004125 )
4126 .expect("Trying to insert cert.");
4127
4128 let (_key_guard, mut key_entry) = db
4129 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004130 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004131 domain: Domain::APP,
4132 nspace: 1,
4133 alias: Some(TEST_ALIAS.to_string()),
4134 blob: None,
4135 },
4136 KeyType::Client,
4137 KeyEntryLoadBits::PUBLIC,
4138 1,
4139 |_k, _av| Ok(()),
4140 )
4141 .expect("Trying to read certificate entry.");
4142
4143 assert!(key_entry.pure_cert());
4144 assert!(key_entry.cert().is_none());
4145 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4146
4147 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004148 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004149 domain: Domain::APP,
4150 nspace: 1,
4151 alias: Some(TEST_ALIAS.to_string()),
4152 blob: None,
4153 },
4154 KeyType::Client,
4155 1,
4156 |_, _| Ok(()),
4157 )
4158 .unwrap();
4159
4160 assert_eq!(
4161 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4162 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004163 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004164 domain: Domain::APP,
4165 nspace: 1,
4166 alias: Some(TEST_ALIAS.to_string()),
4167 blob: None,
4168 },
4169 KeyType::Client,
4170 KeyEntryLoadBits::NONE,
4171 1,
4172 |_k, _av| Ok(()),
4173 )
4174 .unwrap_err()
4175 .root_cause()
4176 .downcast_ref::<KsError>()
4177 );
4178
4179 Ok(())
4180 }
4181
4182 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004183 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4184 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004185 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004186 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4187 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004188 let (_key_guard, key_entry) = db
4189 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004190 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004191 domain: Domain::SELINUX,
4192 nspace: 1,
4193 alias: Some(TEST_ALIAS.to_string()),
4194 blob: None,
4195 },
4196 KeyType::Client,
4197 KeyEntryLoadBits::BOTH,
4198 1,
4199 |_k, _av| Ok(()),
4200 )
4201 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004202 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004203
4204 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004205 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004206 domain: Domain::SELINUX,
4207 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004208 alias: Some(TEST_ALIAS.to_string()),
4209 blob: None,
4210 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004211 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004212 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004213 |_, _| Ok(()),
4214 )
4215 .unwrap();
4216
4217 assert_eq!(
4218 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4219 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004220 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004221 domain: Domain::SELINUX,
4222 nspace: 1,
4223 alias: Some(TEST_ALIAS.to_string()),
4224 blob: None,
4225 },
4226 KeyType::Client,
4227 KeyEntryLoadBits::NONE,
4228 1,
4229 |_k, _av| Ok(()),
4230 )
4231 .unwrap_err()
4232 .root_cause()
4233 .downcast_ref::<KsError>()
4234 );
4235
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004236 Ok(())
4237 }
4238
4239 #[test]
4240 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4241 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004242 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004243 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4244 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004245 let (_, key_entry) = db
4246 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004247 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004248 KeyType::Client,
4249 KeyEntryLoadBits::BOTH,
4250 1,
4251 |_k, _av| Ok(()),
4252 )
4253 .unwrap();
4254
Qi Wub9433b52020-12-01 14:52:46 +08004255 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004256
4257 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004258 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004259 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004260 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004261 |_, _| Ok(()),
4262 )
4263 .unwrap();
4264
4265 assert_eq!(
4266 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4267 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004268 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004269 KeyType::Client,
4270 KeyEntryLoadBits::NONE,
4271 1,
4272 |_k, _av| Ok(()),
4273 )
4274 .unwrap_err()
4275 .root_cause()
4276 .downcast_ref::<KsError>()
4277 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004278
4279 Ok(())
4280 }
4281
4282 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004283 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4284 let mut db = new_test_db()?;
4285 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4286 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4287 .0;
4288 // Update the usage count of the limited use key.
4289 db.check_and_update_key_usage_count(key_id)?;
4290
4291 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004292 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004293 KeyType::Client,
4294 KeyEntryLoadBits::BOTH,
4295 1,
4296 |_k, _av| Ok(()),
4297 )?;
4298
4299 // The usage count is decremented now.
4300 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4301
4302 Ok(())
4303 }
4304
4305 #[test]
4306 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4307 let mut db = new_test_db()?;
4308 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4309 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4310 .0;
4311 // Update the usage count of the limited use key.
4312 db.check_and_update_key_usage_count(key_id).expect(concat!(
4313 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4314 "This should succeed."
4315 ));
4316
4317 // Try to update the exhausted limited use key.
4318 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4319 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4320 "This should fail."
4321 ));
4322 assert_eq!(
4323 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4324 e.root_cause().downcast_ref::<KsError>().unwrap()
4325 );
4326
4327 Ok(())
4328 }
4329
4330 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004331 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4332 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004333 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004334 .context("test_insert_and_load_full_keyentry_from_grant")?
4335 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004336
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004337 let granted_key = db
4338 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004339 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004340 domain: Domain::APP,
4341 nspace: 0,
4342 alias: Some(TEST_ALIAS.to_string()),
4343 blob: None,
4344 },
4345 1,
4346 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004347 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004348 |_k, _av| Ok(()),
4349 )
4350 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004351
4352 debug_dump_grant_table(&mut db)?;
4353
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004354 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004355 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4356 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004357 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08004358 Ok(())
4359 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004360 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004361
Qi Wub9433b52020-12-01 14:52:46 +08004362 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004363
Janis Danisevskis66784c42021-01-27 08:40:25 -08004364 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004365
4366 assert_eq!(
4367 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4368 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004369 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004370 KeyType::Client,
4371 KeyEntryLoadBits::NONE,
4372 2,
4373 |_k, _av| Ok(()),
4374 )
4375 .unwrap_err()
4376 .root_cause()
4377 .downcast_ref::<KsError>()
4378 );
4379
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004380 Ok(())
4381 }
4382
Janis Danisevskis45760022021-01-19 16:34:10 -08004383 // This test attempts to load a key by key id while the caller is not the owner
4384 // but a grant exists for the given key and the caller.
4385 #[test]
4386 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4387 let mut db = new_test_db()?;
4388 const OWNER_UID: u32 = 1u32;
4389 const GRANTEE_UID: u32 = 2u32;
4390 const SOMEONE_ELSE_UID: u32 = 3u32;
4391 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4392 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4393 .0;
4394
4395 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004396 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004397 domain: Domain::APP,
4398 nspace: 0,
4399 alias: Some(TEST_ALIAS.to_string()),
4400 blob: None,
4401 },
4402 OWNER_UID,
4403 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004404 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08004405 |_k, _av| Ok(()),
4406 )
4407 .unwrap();
4408
4409 debug_dump_grant_table(&mut db)?;
4410
4411 let id_descriptor =
4412 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4413
4414 let (_, key_entry) = db
4415 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004416 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004417 KeyType::Client,
4418 KeyEntryLoadBits::BOTH,
4419 GRANTEE_UID,
4420 |k, av| {
4421 assert_eq!(Domain::APP, k.domain);
4422 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004423 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08004424 Ok(())
4425 },
4426 )
4427 .unwrap();
4428
4429 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4430
4431 let (_, key_entry) = db
4432 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004433 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004434 KeyType::Client,
4435 KeyEntryLoadBits::BOTH,
4436 SOMEONE_ELSE_UID,
4437 |k, av| {
4438 assert_eq!(Domain::APP, k.domain);
4439 assert_eq!(OWNER_UID as i64, k.nspace);
4440 assert!(av.is_none());
4441 Ok(())
4442 },
4443 )
4444 .unwrap();
4445
4446 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4447
Janis Danisevskis66784c42021-01-27 08:40:25 -08004448 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004449
4450 assert_eq!(
4451 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4452 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004453 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004454 KeyType::Client,
4455 KeyEntryLoadBits::NONE,
4456 GRANTEE_UID,
4457 |_k, _av| Ok(()),
4458 )
4459 .unwrap_err()
4460 .root_cause()
4461 .downcast_ref::<KsError>()
4462 );
4463
4464 Ok(())
4465 }
4466
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004467 // Creates a key migrates it to a different location and then tries to access it by the old
4468 // and new location.
4469 #[test]
4470 fn test_migrate_key_app_to_app() -> Result<()> {
4471 let mut db = new_test_db()?;
4472 const SOURCE_UID: u32 = 1u32;
4473 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004474 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4475 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004476 let key_id_guard =
4477 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4478 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4479
4480 let source_descriptor: KeyDescriptor = KeyDescriptor {
4481 domain: Domain::APP,
4482 nspace: -1,
4483 alias: Some(SOURCE_ALIAS.to_string()),
4484 blob: None,
4485 };
4486
4487 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4488 domain: Domain::APP,
4489 nspace: -1,
4490 alias: Some(DESTINATION_ALIAS.to_string()),
4491 blob: None,
4492 };
4493
4494 let key_id = key_id_guard.id();
4495
4496 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4497 Ok(())
4498 })
4499 .unwrap();
4500
4501 let (_, key_entry) = db
4502 .load_key_entry(
4503 &destination_descriptor,
4504 KeyType::Client,
4505 KeyEntryLoadBits::BOTH,
4506 DESTINATION_UID,
4507 |k, av| {
4508 assert_eq!(Domain::APP, k.domain);
4509 assert_eq!(DESTINATION_UID as i64, k.nspace);
4510 assert!(av.is_none());
4511 Ok(())
4512 },
4513 )
4514 .unwrap();
4515
4516 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4517
4518 assert_eq!(
4519 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4520 db.load_key_entry(
4521 &source_descriptor,
4522 KeyType::Client,
4523 KeyEntryLoadBits::NONE,
4524 SOURCE_UID,
4525 |_k, _av| Ok(()),
4526 )
4527 .unwrap_err()
4528 .root_cause()
4529 .downcast_ref::<KsError>()
4530 );
4531
4532 Ok(())
4533 }
4534
4535 // Creates a key migrates it to a different location and then tries to access it by the old
4536 // and new location.
4537 #[test]
4538 fn test_migrate_key_app_to_selinux() -> Result<()> {
4539 let mut db = new_test_db()?;
4540 const SOURCE_UID: u32 = 1u32;
4541 const DESTINATION_UID: u32 = 2u32;
4542 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004543 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4544 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004545 let key_id_guard =
4546 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4547 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4548
4549 let source_descriptor: KeyDescriptor = KeyDescriptor {
4550 domain: Domain::APP,
4551 nspace: -1,
4552 alias: Some(SOURCE_ALIAS.to_string()),
4553 blob: None,
4554 };
4555
4556 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4557 domain: Domain::SELINUX,
4558 nspace: DESTINATION_NAMESPACE,
4559 alias: Some(DESTINATION_ALIAS.to_string()),
4560 blob: None,
4561 };
4562
4563 let key_id = key_id_guard.id();
4564
4565 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4566 Ok(())
4567 })
4568 .unwrap();
4569
4570 let (_, key_entry) = db
4571 .load_key_entry(
4572 &destination_descriptor,
4573 KeyType::Client,
4574 KeyEntryLoadBits::BOTH,
4575 DESTINATION_UID,
4576 |k, av| {
4577 assert_eq!(Domain::SELINUX, k.domain);
4578 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4579 assert!(av.is_none());
4580 Ok(())
4581 },
4582 )
4583 .unwrap();
4584
4585 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4586
4587 assert_eq!(
4588 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4589 db.load_key_entry(
4590 &source_descriptor,
4591 KeyType::Client,
4592 KeyEntryLoadBits::NONE,
4593 SOURCE_UID,
4594 |_k, _av| Ok(()),
4595 )
4596 .unwrap_err()
4597 .root_cause()
4598 .downcast_ref::<KsError>()
4599 );
4600
4601 Ok(())
4602 }
4603
4604 // Creates two keys and tries to migrate the first to the location of the second which
4605 // is expected to fail.
4606 #[test]
4607 fn test_migrate_key_destination_occupied() -> Result<()> {
4608 let mut db = new_test_db()?;
4609 const SOURCE_UID: u32 = 1u32;
4610 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004611 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4612 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004613 let key_id_guard =
4614 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4615 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4616 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4617 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4618
4619 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4620 domain: Domain::APP,
4621 nspace: -1,
4622 alias: Some(DESTINATION_ALIAS.to_string()),
4623 blob: None,
4624 };
4625
4626 assert_eq!(
4627 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4628 db.migrate_key_namespace(
4629 key_id_guard,
4630 &destination_descriptor,
4631 DESTINATION_UID,
4632 |_k| Ok(())
4633 )
4634 .unwrap_err()
4635 .root_cause()
4636 .downcast_ref::<KsError>()
4637 );
4638
4639 Ok(())
4640 }
4641
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004642 #[test]
4643 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004644 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4645 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4646 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004647 const UID: u32 = 33;
4648 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4649 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4650 let key_id_untouched1 =
4651 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4652 let key_id_untouched2 =
4653 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4654 let key_id_deleted =
4655 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4656
4657 let (_, key_entry) = db
4658 .load_key_entry(
4659 &KeyDescriptor {
4660 domain: Domain::APP,
4661 nspace: -1,
4662 alias: Some(ALIAS1.to_string()),
4663 blob: None,
4664 },
4665 KeyType::Client,
4666 KeyEntryLoadBits::BOTH,
4667 UID,
4668 |k, av| {
4669 assert_eq!(Domain::APP, k.domain);
4670 assert_eq!(UID as i64, k.nspace);
4671 assert!(av.is_none());
4672 Ok(())
4673 },
4674 )
4675 .unwrap();
4676 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4677 let (_, key_entry) = db
4678 .load_key_entry(
4679 &KeyDescriptor {
4680 domain: Domain::APP,
4681 nspace: -1,
4682 alias: Some(ALIAS2.to_string()),
4683 blob: None,
4684 },
4685 KeyType::Client,
4686 KeyEntryLoadBits::BOTH,
4687 UID,
4688 |k, av| {
4689 assert_eq!(Domain::APP, k.domain);
4690 assert_eq!(UID as i64, k.nspace);
4691 assert!(av.is_none());
4692 Ok(())
4693 },
4694 )
4695 .unwrap();
4696 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4697 let (_, key_entry) = db
4698 .load_key_entry(
4699 &KeyDescriptor {
4700 domain: Domain::APP,
4701 nspace: -1,
4702 alias: Some(ALIAS3.to_string()),
4703 blob: None,
4704 },
4705 KeyType::Client,
4706 KeyEntryLoadBits::BOTH,
4707 UID,
4708 |k, av| {
4709 assert_eq!(Domain::APP, k.domain);
4710 assert_eq!(UID as i64, k.nspace);
4711 assert!(av.is_none());
4712 Ok(())
4713 },
4714 )
4715 .unwrap();
4716 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4717
4718 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4719 KeystoreDB::from_0_to_1(tx).no_gc()
4720 })
4721 .unwrap();
4722
4723 let (_, key_entry) = db
4724 .load_key_entry(
4725 &KeyDescriptor {
4726 domain: Domain::APP,
4727 nspace: -1,
4728 alias: Some(ALIAS1.to_string()),
4729 blob: None,
4730 },
4731 KeyType::Client,
4732 KeyEntryLoadBits::BOTH,
4733 UID,
4734 |k, av| {
4735 assert_eq!(Domain::APP, k.domain);
4736 assert_eq!(UID as i64, k.nspace);
4737 assert!(av.is_none());
4738 Ok(())
4739 },
4740 )
4741 .unwrap();
4742 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4743 let (_, key_entry) = db
4744 .load_key_entry(
4745 &KeyDescriptor {
4746 domain: Domain::APP,
4747 nspace: -1,
4748 alias: Some(ALIAS2.to_string()),
4749 blob: None,
4750 },
4751 KeyType::Client,
4752 KeyEntryLoadBits::BOTH,
4753 UID,
4754 |k, av| {
4755 assert_eq!(Domain::APP, k.domain);
4756 assert_eq!(UID as i64, k.nspace);
4757 assert!(av.is_none());
4758 Ok(())
4759 },
4760 )
4761 .unwrap();
4762 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4763 assert_eq!(
4764 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4765 db.load_key_entry(
4766 &KeyDescriptor {
4767 domain: Domain::APP,
4768 nspace: -1,
4769 alias: Some(ALIAS3.to_string()),
4770 blob: None,
4771 },
4772 KeyType::Client,
4773 KeyEntryLoadBits::BOTH,
4774 UID,
4775 |k, av| {
4776 assert_eq!(Domain::APP, k.domain);
4777 assert_eq!(UID as i64, k.nspace);
4778 assert!(av.is_none());
4779 Ok(())
4780 },
4781 )
4782 .unwrap_err()
4783 .root_cause()
4784 .downcast_ref::<KsError>()
4785 );
4786 }
4787
Janis Danisevskisaec14592020-11-12 09:41:49 -08004788 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4789
Janis Danisevskisaec14592020-11-12 09:41:49 -08004790 #[test]
4791 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4792 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004793 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4794 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004795 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004796 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004797 .context("test_insert_and_load_full_keyentry_domain_app")?
4798 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004799 let (_key_guard, key_entry) = db
4800 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004801 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004802 domain: Domain::APP,
4803 nspace: 0,
4804 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4805 blob: None,
4806 },
4807 KeyType::Client,
4808 KeyEntryLoadBits::BOTH,
4809 33,
4810 |_k, _av| Ok(()),
4811 )
4812 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004813 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004814 let state = Arc::new(AtomicU8::new(1));
4815 let state2 = state.clone();
4816
4817 // Spawning a second thread that attempts to acquire the key id lock
4818 // for the same key as the primary thread. The primary thread then
4819 // waits, thereby forcing the secondary thread into the second stage
4820 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4821 // The test succeeds if the secondary thread observes the transition
4822 // of `state` from 1 to 2, despite having a whole second to overtake
4823 // the primary thread.
4824 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004825 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004826 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004827 assert!(db
4828 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004829 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004830 domain: Domain::APP,
4831 nspace: 0,
4832 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4833 blob: None,
4834 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004835 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004836 KeyEntryLoadBits::BOTH,
4837 33,
4838 |_k, _av| Ok(()),
4839 )
4840 .is_ok());
4841 // We should only see a 2 here because we can only return
4842 // from load_key_entry when the `_key_guard` expires,
4843 // which happens at the end of the scope.
4844 assert_eq!(2, state2.load(Ordering::Relaxed));
4845 });
4846
4847 thread::sleep(std::time::Duration::from_millis(1000));
4848
4849 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4850
4851 // Return the handle from this scope so we can join with the
4852 // secondary thread after the key id lock has expired.
4853 handle
4854 // This is where the `_key_guard` goes out of scope,
4855 // which is the reason for concurrent load_key_entry on the same key
4856 // to unblock.
4857 };
4858 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4859 // main test thread. We will not see failing asserts in secondary threads otherwise.
4860 handle.join().unwrap();
4861 Ok(())
4862 }
4863
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004864 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004865 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004866 let temp_dir =
4867 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4868
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004869 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4870 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004871
4872 let _tx1 = db1
4873 .conn
4874 .transaction_with_behavior(TransactionBehavior::Immediate)
4875 .expect("Failed to create first transaction.");
4876
4877 let error = db2
4878 .conn
4879 .transaction_with_behavior(TransactionBehavior::Immediate)
4880 .context("Transaction begin failed.")
4881 .expect_err("This should fail.");
4882 let root_cause = error.root_cause();
4883 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4884 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4885 {
4886 return;
4887 }
4888 panic!(
4889 "Unexpected error {:?} \n{:?} \n{:?}",
4890 error,
4891 root_cause,
4892 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4893 )
4894 }
4895
4896 #[cfg(disabled)]
4897 #[test]
4898 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4899 let temp_dir = Arc::new(
4900 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4901 .expect("Failed to create temp dir."),
4902 );
4903
4904 let test_begin = Instant::now();
4905
Janis Danisevskis66784c42021-01-27 08:40:25 -08004906 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004907 let mut db =
4908 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004909 const OPEN_DB_COUNT: u32 = 50u32;
4910
4911 let mut actual_key_count = KEY_COUNT;
4912 // First insert KEY_COUNT keys.
4913 for count in 0..KEY_COUNT {
4914 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4915 actual_key_count = count;
4916 break;
4917 }
4918 let alias = format!("test_alias_{}", count);
4919 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4920 .expect("Failed to make key entry.");
4921 }
4922
4923 // Insert more keys from a different thread and into a different namespace.
4924 let temp_dir1 = temp_dir.clone();
4925 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004926 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4927 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004928
4929 for count in 0..actual_key_count {
4930 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4931 return;
4932 }
4933 let alias = format!("test_alias_{}", count);
4934 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4935 .expect("Failed to make key entry.");
4936 }
4937
4938 // then unbind them again.
4939 for count in 0..actual_key_count {
4940 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4941 return;
4942 }
4943 let key = KeyDescriptor {
4944 domain: Domain::APP,
4945 nspace: -1,
4946 alias: Some(format!("test_alias_{}", count)),
4947 blob: None,
4948 };
4949 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4950 }
4951 });
4952
4953 // And start unbinding the first set of keys.
4954 let temp_dir2 = temp_dir.clone();
4955 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004956 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4957 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004958
4959 for count in 0..actual_key_count {
4960 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4961 return;
4962 }
4963 let key = KeyDescriptor {
4964 domain: Domain::APP,
4965 nspace: -1,
4966 alias: Some(format!("test_alias_{}", count)),
4967 blob: None,
4968 };
4969 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4970 }
4971 });
4972
Janis Danisevskis66784c42021-01-27 08:40:25 -08004973 // While a lot of inserting and deleting is going on we have to open database connections
4974 // successfully and use them.
4975 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4976 // out of scope.
4977 #[allow(clippy::redundant_clone)]
4978 let temp_dir4 = temp_dir.clone();
4979 let handle4 = thread::spawn(move || {
4980 for count in 0..OPEN_DB_COUNT {
4981 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4982 return;
4983 }
Seth Moore444b51a2021-06-11 09:49:49 -07004984 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4985 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004986
4987 let alias = format!("test_alias_{}", count);
4988 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4989 .expect("Failed to make key entry.");
4990 let key = KeyDescriptor {
4991 domain: Domain::APP,
4992 nspace: -1,
4993 alias: Some(alias),
4994 blob: None,
4995 };
4996 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4997 }
4998 });
4999
5000 handle1.join().expect("Thread 1 panicked.");
5001 handle2.join().expect("Thread 2 panicked.");
5002 handle4.join().expect("Thread 4 panicked.");
5003
Janis Danisevskis66784c42021-01-27 08:40:25 -08005004 Ok(())
5005 }
5006
5007 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005008 fn list() -> Result<()> {
5009 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005010 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005011 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
5012 (Domain::APP, 1, "test1"),
5013 (Domain::APP, 1, "test2"),
5014 (Domain::APP, 1, "test3"),
5015 (Domain::APP, 1, "test4"),
5016 (Domain::APP, 1, "test5"),
5017 (Domain::APP, 1, "test6"),
5018 (Domain::APP, 1, "test7"),
5019 (Domain::APP, 2, "test1"),
5020 (Domain::APP, 2, "test2"),
5021 (Domain::APP, 2, "test3"),
5022 (Domain::APP, 2, "test4"),
5023 (Domain::APP, 2, "test5"),
5024 (Domain::APP, 2, "test6"),
5025 (Domain::APP, 2, "test8"),
5026 (Domain::SELINUX, 100, "test1"),
5027 (Domain::SELINUX, 100, "test2"),
5028 (Domain::SELINUX, 100, "test3"),
5029 (Domain::SELINUX, 100, "test4"),
5030 (Domain::SELINUX, 100, "test5"),
5031 (Domain::SELINUX, 100, "test6"),
5032 (Domain::SELINUX, 100, "test9"),
5033 ];
5034
5035 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
5036 .iter()
5037 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08005038 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
5039 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005040 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
5041 });
5042 (entry.id(), *ns)
5043 })
5044 .collect();
5045
5046 for (domain, namespace) in
5047 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
5048 {
5049 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
5050 .iter()
5051 .filter_map(|(domain, ns, alias)| match ns {
5052 ns if *ns == *namespace => Some(KeyDescriptor {
5053 domain: *domain,
5054 nspace: *ns,
5055 alias: Some(alias.to_string()),
5056 blob: None,
5057 }),
5058 _ => None,
5059 })
5060 .collect();
5061 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07005062 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005063 list_result.sort();
5064 assert_eq!(list_o_descriptors, list_result);
5065
5066 let mut list_o_ids: Vec<i64> = list_o_descriptors
5067 .into_iter()
5068 .map(|d| {
5069 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005070 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08005071 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005072 KeyType::Client,
5073 KeyEntryLoadBits::NONE,
5074 *namespace as u32,
5075 |_, _| Ok(()),
5076 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005077 .unwrap();
5078 entry.id()
5079 })
5080 .collect();
5081 list_o_ids.sort_unstable();
5082 let mut loaded_entries: Vec<i64> = list_o_keys
5083 .iter()
5084 .filter_map(|(id, ns)| match ns {
5085 ns if *ns == *namespace => Some(*id),
5086 _ => None,
5087 })
5088 .collect();
5089 loaded_entries.sort_unstable();
5090 assert_eq!(list_o_ids, loaded_entries);
5091 }
Janis Danisevskis18313832021-05-17 13:30:32 -07005092 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005093
5094 Ok(())
5095 }
5096
Joel Galenson0891bc12020-07-20 10:37:03 -07005097 // Helpers
5098
5099 // Checks that the given result is an error containing the given string.
5100 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
5101 let error_str = format!(
5102 "{:#?}",
5103 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
5104 );
5105 assert!(
5106 error_str.contains(target),
5107 "The string \"{}\" should contain \"{}\"",
5108 error_str,
5109 target
5110 );
5111 }
5112
Joel Galenson2aab4432020-07-22 15:27:57 -07005113 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07005114 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005115 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005116 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005117 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005118 namespace: Option<i64>,
5119 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005120 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08005121 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005122 }
5123
5124 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
5125 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07005126 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07005127 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07005128 Ok(KeyEntryRow {
5129 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005130 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07005131 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07005132 namespace: row.get(3)?,
5133 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005134 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08005135 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07005136 })
5137 })?
5138 .map(|r| r.context("Could not read keyentry row."))
5139 .collect::<Result<Vec<_>>>()
5140 }
5141
Max Biresb2e1d032021-02-08 21:35:05 -08005142 struct RemoteProvValues {
5143 cert_chain: Vec<u8>,
5144 priv_key: Vec<u8>,
5145 batch_cert: Vec<u8>,
5146 }
5147
Max Bires2b2e6562020-09-22 11:22:36 -07005148 fn load_attestation_key_pool(
5149 db: &mut KeystoreDB,
5150 expiration_date: i64,
5151 namespace: i64,
5152 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08005153 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07005154 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
5155 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
5156 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5157 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005158 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005159 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5160 db.store_signed_attestation_certificate_chain(
5161 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005162 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005163 &cert_chain,
5164 expiration_date,
5165 &KEYSTORE_UUID,
5166 )?;
5167 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005168 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005169 }
5170
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005171 // Note: The parameters and SecurityLevel associations are nonsensical. This
5172 // collection is only used to check if the parameters are preserved as expected by the
5173 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005174 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5175 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005176 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5177 KeyParameter::new(
5178 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5179 SecurityLevel::TRUSTED_ENVIRONMENT,
5180 ),
5181 KeyParameter::new(
5182 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5183 SecurityLevel::TRUSTED_ENVIRONMENT,
5184 ),
5185 KeyParameter::new(
5186 KeyParameterValue::Algorithm(Algorithm::RSA),
5187 SecurityLevel::TRUSTED_ENVIRONMENT,
5188 ),
5189 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5190 KeyParameter::new(
5191 KeyParameterValue::BlockMode(BlockMode::ECB),
5192 SecurityLevel::TRUSTED_ENVIRONMENT,
5193 ),
5194 KeyParameter::new(
5195 KeyParameterValue::BlockMode(BlockMode::GCM),
5196 SecurityLevel::TRUSTED_ENVIRONMENT,
5197 ),
5198 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5199 KeyParameter::new(
5200 KeyParameterValue::Digest(Digest::MD5),
5201 SecurityLevel::TRUSTED_ENVIRONMENT,
5202 ),
5203 KeyParameter::new(
5204 KeyParameterValue::Digest(Digest::SHA_2_224),
5205 SecurityLevel::TRUSTED_ENVIRONMENT,
5206 ),
5207 KeyParameter::new(
5208 KeyParameterValue::Digest(Digest::SHA_2_256),
5209 SecurityLevel::STRONGBOX,
5210 ),
5211 KeyParameter::new(
5212 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5213 SecurityLevel::TRUSTED_ENVIRONMENT,
5214 ),
5215 KeyParameter::new(
5216 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5217 SecurityLevel::TRUSTED_ENVIRONMENT,
5218 ),
5219 KeyParameter::new(
5220 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5221 SecurityLevel::STRONGBOX,
5222 ),
5223 KeyParameter::new(
5224 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5225 SecurityLevel::TRUSTED_ENVIRONMENT,
5226 ),
5227 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5228 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5229 KeyParameter::new(
5230 KeyParameterValue::EcCurve(EcCurve::P_224),
5231 SecurityLevel::TRUSTED_ENVIRONMENT,
5232 ),
5233 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5234 KeyParameter::new(
5235 KeyParameterValue::EcCurve(EcCurve::P_384),
5236 SecurityLevel::TRUSTED_ENVIRONMENT,
5237 ),
5238 KeyParameter::new(
5239 KeyParameterValue::EcCurve(EcCurve::P_521),
5240 SecurityLevel::TRUSTED_ENVIRONMENT,
5241 ),
5242 KeyParameter::new(
5243 KeyParameterValue::RSAPublicExponent(3),
5244 SecurityLevel::TRUSTED_ENVIRONMENT,
5245 ),
5246 KeyParameter::new(
5247 KeyParameterValue::IncludeUniqueID,
5248 SecurityLevel::TRUSTED_ENVIRONMENT,
5249 ),
5250 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5251 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5252 KeyParameter::new(
5253 KeyParameterValue::ActiveDateTime(1234567890),
5254 SecurityLevel::STRONGBOX,
5255 ),
5256 KeyParameter::new(
5257 KeyParameterValue::OriginationExpireDateTime(1234567890),
5258 SecurityLevel::TRUSTED_ENVIRONMENT,
5259 ),
5260 KeyParameter::new(
5261 KeyParameterValue::UsageExpireDateTime(1234567890),
5262 SecurityLevel::TRUSTED_ENVIRONMENT,
5263 ),
5264 KeyParameter::new(
5265 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5266 SecurityLevel::TRUSTED_ENVIRONMENT,
5267 ),
5268 KeyParameter::new(
5269 KeyParameterValue::MaxUsesPerBoot(1234567890),
5270 SecurityLevel::TRUSTED_ENVIRONMENT,
5271 ),
5272 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5273 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5274 KeyParameter::new(
5275 KeyParameterValue::NoAuthRequired,
5276 SecurityLevel::TRUSTED_ENVIRONMENT,
5277 ),
5278 KeyParameter::new(
5279 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5280 SecurityLevel::TRUSTED_ENVIRONMENT,
5281 ),
5282 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5283 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5284 KeyParameter::new(
5285 KeyParameterValue::TrustedUserPresenceRequired,
5286 SecurityLevel::TRUSTED_ENVIRONMENT,
5287 ),
5288 KeyParameter::new(
5289 KeyParameterValue::TrustedConfirmationRequired,
5290 SecurityLevel::TRUSTED_ENVIRONMENT,
5291 ),
5292 KeyParameter::new(
5293 KeyParameterValue::UnlockedDeviceRequired,
5294 SecurityLevel::TRUSTED_ENVIRONMENT,
5295 ),
5296 KeyParameter::new(
5297 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5298 SecurityLevel::SOFTWARE,
5299 ),
5300 KeyParameter::new(
5301 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5302 SecurityLevel::SOFTWARE,
5303 ),
5304 KeyParameter::new(
5305 KeyParameterValue::CreationDateTime(12345677890),
5306 SecurityLevel::SOFTWARE,
5307 ),
5308 KeyParameter::new(
5309 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5310 SecurityLevel::TRUSTED_ENVIRONMENT,
5311 ),
5312 KeyParameter::new(
5313 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5314 SecurityLevel::TRUSTED_ENVIRONMENT,
5315 ),
5316 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5317 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5318 KeyParameter::new(
5319 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5320 SecurityLevel::SOFTWARE,
5321 ),
5322 KeyParameter::new(
5323 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5324 SecurityLevel::TRUSTED_ENVIRONMENT,
5325 ),
5326 KeyParameter::new(
5327 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5328 SecurityLevel::TRUSTED_ENVIRONMENT,
5329 ),
5330 KeyParameter::new(
5331 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5332 SecurityLevel::TRUSTED_ENVIRONMENT,
5333 ),
5334 KeyParameter::new(
5335 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5336 SecurityLevel::TRUSTED_ENVIRONMENT,
5337 ),
5338 KeyParameter::new(
5339 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5340 SecurityLevel::TRUSTED_ENVIRONMENT,
5341 ),
5342 KeyParameter::new(
5343 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5344 SecurityLevel::TRUSTED_ENVIRONMENT,
5345 ),
5346 KeyParameter::new(
5347 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5348 SecurityLevel::TRUSTED_ENVIRONMENT,
5349 ),
5350 KeyParameter::new(
5351 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5352 SecurityLevel::TRUSTED_ENVIRONMENT,
5353 ),
5354 KeyParameter::new(
5355 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5356 SecurityLevel::TRUSTED_ENVIRONMENT,
5357 ),
5358 KeyParameter::new(
5359 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5360 SecurityLevel::TRUSTED_ENVIRONMENT,
5361 ),
5362 KeyParameter::new(
5363 KeyParameterValue::VendorPatchLevel(3),
5364 SecurityLevel::TRUSTED_ENVIRONMENT,
5365 ),
5366 KeyParameter::new(
5367 KeyParameterValue::BootPatchLevel(4),
5368 SecurityLevel::TRUSTED_ENVIRONMENT,
5369 ),
5370 KeyParameter::new(
5371 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5372 SecurityLevel::TRUSTED_ENVIRONMENT,
5373 ),
5374 KeyParameter::new(
5375 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5376 SecurityLevel::TRUSTED_ENVIRONMENT,
5377 ),
5378 KeyParameter::new(
5379 KeyParameterValue::MacLength(256),
5380 SecurityLevel::TRUSTED_ENVIRONMENT,
5381 ),
5382 KeyParameter::new(
5383 KeyParameterValue::ResetSinceIdRotation,
5384 SecurityLevel::TRUSTED_ENVIRONMENT,
5385 ),
5386 KeyParameter::new(
5387 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5388 SecurityLevel::TRUSTED_ENVIRONMENT,
5389 ),
Qi Wub9433b52020-12-01 14:52:46 +08005390 ];
5391 if let Some(value) = max_usage_count {
5392 params.push(KeyParameter::new(
5393 KeyParameterValue::UsageCountLimit(value),
5394 SecurityLevel::SOFTWARE,
5395 ));
5396 }
5397 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005398 }
5399
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005400 fn make_test_key_entry(
5401 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005402 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005403 namespace: i64,
5404 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005405 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005406 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005407 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005408 let mut blob_metadata = BlobMetaData::new();
5409 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5410 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5411 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5412 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5413 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5414
5415 db.set_blob(
5416 &key_id,
5417 SubComponentType::KEY_BLOB,
5418 Some(TEST_KEY_BLOB),
5419 Some(&blob_metadata),
5420 )?;
5421 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5422 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005423
5424 let params = make_test_params(max_usage_count);
5425 db.insert_keyparameter(&key_id, &params)?;
5426
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005427 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005428 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005429 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005430 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005431 Ok(key_id)
5432 }
5433
Qi Wub9433b52020-12-01 14:52:46 +08005434 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5435 let params = make_test_params(max_usage_count);
5436
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005437 let mut blob_metadata = BlobMetaData::new();
5438 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5439 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5440 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5441 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5442 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5443
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005444 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005445 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005446
5447 KeyEntry {
5448 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005449 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005450 cert: Some(TEST_CERT_BLOB.to_vec()),
5451 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005452 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005453 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005454 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005455 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005456 }
5457 }
5458
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005459 fn make_bootlevel_key_entry(
5460 db: &mut KeystoreDB,
5461 domain: Domain,
5462 namespace: i64,
5463 alias: &str,
5464 logical_only: bool,
5465 ) -> Result<KeyIdGuard> {
5466 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5467 let mut blob_metadata = BlobMetaData::new();
5468 if !logical_only {
5469 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5470 }
5471 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5472
5473 db.set_blob(
5474 &key_id,
5475 SubComponentType::KEY_BLOB,
5476 Some(TEST_KEY_BLOB),
5477 Some(&blob_metadata),
5478 )?;
5479 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5480 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5481
5482 let mut params = make_test_params(None);
5483 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5484
5485 db.insert_keyparameter(&key_id, &params)?;
5486
5487 let mut metadata = KeyMetaData::new();
5488 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5489 db.insert_key_metadata(&key_id, &metadata)?;
5490 rebind_alias(db, &key_id, alias, domain, namespace)?;
5491 Ok(key_id)
5492 }
5493
5494 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5495 let mut params = make_test_params(None);
5496 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5497
5498 let mut blob_metadata = BlobMetaData::new();
5499 if !logical_only {
5500 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5501 }
5502 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5503
5504 let mut metadata = KeyMetaData::new();
5505 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5506
5507 KeyEntry {
5508 id: key_id,
5509 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5510 cert: Some(TEST_CERT_BLOB.to_vec()),
5511 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5512 km_uuid: KEYSTORE_UUID,
5513 parameters: params,
5514 metadata,
5515 pure_cert: false,
5516 }
5517 }
5518
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005519 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005520 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005521 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005522 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005523 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005524 NO_PARAMS,
5525 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005526 Ok((
5527 row.get(0)?,
5528 row.get(1)?,
5529 row.get(2)?,
5530 row.get(3)?,
5531 row.get(4)?,
5532 row.get(5)?,
5533 row.get(6)?,
5534 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005535 },
5536 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005537
5538 println!("Key entry table rows:");
5539 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005540 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005541 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005542 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5543 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005544 );
5545 }
5546 Ok(())
5547 }
5548
5549 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005550 let mut stmt = db
5551 .conn
5552 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005553 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5554 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5555 })?;
5556
5557 println!("Grant table rows:");
5558 for r in rows {
5559 let (id, gt, ki, av) = r.unwrap();
5560 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5561 }
5562 Ok(())
5563 }
5564
Joel Galenson0891bc12020-07-20 10:37:03 -07005565 // Use a custom random number generator that repeats each number once.
5566 // This allows us to test repeated elements.
5567
5568 thread_local! {
5569 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5570 }
5571
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005572 fn reset_random() {
5573 RANDOM_COUNTER.with(|counter| {
5574 *counter.borrow_mut() = 0;
5575 })
5576 }
5577
Joel Galenson0891bc12020-07-20 10:37:03 -07005578 pub fn random() -> i64 {
5579 RANDOM_COUNTER.with(|counter| {
5580 let result = *counter.borrow() / 2;
5581 *counter.borrow_mut() += 1;
5582 result
5583 })
5584 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005585
5586 #[test]
5587 fn test_last_off_body() -> Result<()> {
5588 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005589 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005590 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005591 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005592 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005593 let one_second = Duration::from_secs(1);
5594 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005595 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005596 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005597 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005598 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005599 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005600 Ok(())
5601 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005602
5603 #[test]
5604 fn test_unbind_keys_for_user() -> Result<()> {
5605 let mut db = new_test_db()?;
5606 db.unbind_keys_for_user(1, false)?;
5607
5608 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5609 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5610 db.unbind_keys_for_user(2, false)?;
5611
Janis Danisevskis18313832021-05-17 13:30:32 -07005612 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5613 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005614
5615 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005616 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005617
5618 Ok(())
5619 }
5620
5621 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005622 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5623 let mut db = new_test_db()?;
5624 let super_key = keystore2_crypto::generate_aes256_key()?;
5625 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5626 let (encrypted_super_key, metadata) =
5627 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5628
5629 let key_name_enc = SuperKeyType {
5630 alias: "test_super_key_1",
5631 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5632 };
5633
5634 let key_name_nonenc = SuperKeyType {
5635 alias: "test_super_key_2",
5636 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5637 };
5638
5639 // Install two super keys.
5640 db.store_super_key(
5641 1,
5642 &key_name_nonenc,
5643 &super_key,
5644 &BlobMetaData::new(),
5645 &KeyMetaData::new(),
5646 )?;
5647 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5648
5649 // Check that both can be found in the database.
5650 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5651 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5652
5653 // Install the same keys for a different user.
5654 db.store_super_key(
5655 2,
5656 &key_name_nonenc,
5657 &super_key,
5658 &BlobMetaData::new(),
5659 &KeyMetaData::new(),
5660 )?;
5661 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5662
5663 // Check that the second pair of keys can be found in the database.
5664 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5665 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5666
5667 // Delete only encrypted keys.
5668 db.unbind_keys_for_user(1, true)?;
5669
5670 // The encrypted superkey should be gone now.
5671 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5672 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5673
5674 // Reinsert the encrypted key.
5675 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5676
5677 // Check that both can be found in the database, again..
5678 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5679 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5680
5681 // Delete all even unencrypted keys.
5682 db.unbind_keys_for_user(1, false)?;
5683
5684 // Both should be gone now.
5685 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5686 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5687
5688 // Check that the second pair of keys was untouched.
5689 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5690 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5691
5692 Ok(())
5693 }
5694
5695 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005696 fn test_store_super_key() -> Result<()> {
5697 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005698 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005699 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005700 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005701 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005702 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005703
5704 let (encrypted_super_key, metadata) =
5705 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005706 db.store_super_key(
5707 1,
5708 &USER_SUPER_KEY,
5709 &encrypted_super_key,
5710 &metadata,
5711 &KeyMetaData::new(),
5712 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005713
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005714 // Check if super key exists.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005715 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005716
Paul Crowley7a658392021-03-18 17:08:20 -07005717 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005718 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5719 USER_SUPER_KEY.algorithm,
5720 key_entry,
5721 &pw,
5722 None,
5723 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005724
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005725 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005726 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005727
Hasini Gunasingheda895552021-01-27 19:34:37 +00005728 Ok(())
5729 }
Seth Moore78c091f2021-04-09 21:38:30 +00005730
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005731 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005732 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005733 MetricsStorage::KEY_ENTRY,
5734 MetricsStorage::KEY_ENTRY_ID_INDEX,
5735 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5736 MetricsStorage::BLOB_ENTRY,
5737 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5738 MetricsStorage::KEY_PARAMETER,
5739 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5740 MetricsStorage::KEY_METADATA,
5741 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5742 MetricsStorage::GRANT,
5743 MetricsStorage::AUTH_TOKEN,
5744 MetricsStorage::BLOB_METADATA,
5745 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005746 ]
5747 }
5748
5749 /// Perform a simple check to ensure that we can query all the storage types
5750 /// that are supported by the DB. Check for reasonable values.
5751 #[test]
5752 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005753 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005754
5755 let mut db = new_test_db()?;
5756
5757 for t in get_valid_statsd_storage_types() {
5758 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005759 // AuthToken can be less than a page since it's in a btree, not sqlite
5760 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005761 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005762 } else {
5763 assert!(stat.size >= PAGE_SIZE);
5764 }
Seth Moore78c091f2021-04-09 21:38:30 +00005765 assert!(stat.size >= stat.unused_size);
5766 }
5767
5768 Ok(())
5769 }
5770
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005771 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005772 get_valid_statsd_storage_types()
5773 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005774 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005775 .collect()
5776 }
5777
5778 fn assert_storage_increased(
5779 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005780 increased_storage_types: Vec<MetricsStorage>,
5781 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005782 ) {
5783 for storage in increased_storage_types {
5784 // Verify the expected storage increased.
5785 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005786 let storage = storage;
5787 let old = &baseline[&storage.0];
5788 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005789 assert!(
5790 new.unused_size <= old.unused_size,
5791 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005792 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005793 new.unused_size,
5794 old.unused_size
5795 );
5796
5797 // Update the baseline with the new value so that it succeeds in the
5798 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005799 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005800 }
5801
5802 // Get an updated map of the storage and verify there were no unexpected changes.
5803 let updated_stats = get_storage_stats_map(db);
5804 assert_eq!(updated_stats.len(), baseline.len());
5805
5806 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005807 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005808 let mut s = String::new();
5809 for &k in map.keys() {
5810 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5811 .expect("string concat failed");
5812 }
5813 s
5814 };
5815
5816 assert!(
5817 updated_stats[&k].size == baseline[&k].size
5818 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5819 "updated_stats:\n{}\nbaseline:\n{}",
5820 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005821 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005822 );
5823 }
5824 }
5825
5826 #[test]
5827 fn test_verify_key_table_size_reporting() -> Result<()> {
5828 let mut db = new_test_db()?;
5829 let mut working_stats = get_storage_stats_map(&mut db);
5830
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005831 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005832 assert_storage_increased(
5833 &mut db,
5834 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005835 MetricsStorage::KEY_ENTRY,
5836 MetricsStorage::KEY_ENTRY_ID_INDEX,
5837 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005838 ],
5839 &mut working_stats,
5840 );
5841
5842 let mut blob_metadata = BlobMetaData::new();
5843 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5844 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5845 assert_storage_increased(
5846 &mut db,
5847 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005848 MetricsStorage::BLOB_ENTRY,
5849 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5850 MetricsStorage::BLOB_METADATA,
5851 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005852 ],
5853 &mut working_stats,
5854 );
5855
5856 let params = make_test_params(None);
5857 db.insert_keyparameter(&key_id, &params)?;
5858 assert_storage_increased(
5859 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005860 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005861 &mut working_stats,
5862 );
5863
5864 let mut metadata = KeyMetaData::new();
5865 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5866 db.insert_key_metadata(&key_id, &metadata)?;
5867 assert_storage_increased(
5868 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005869 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005870 &mut working_stats,
5871 );
5872
5873 let mut sum = 0;
5874 for stat in working_stats.values() {
5875 sum += stat.size;
5876 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005877 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005878 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5879
5880 Ok(())
5881 }
5882
5883 #[test]
5884 fn test_verify_auth_table_size_reporting() -> Result<()> {
5885 let mut db = new_test_db()?;
5886 let mut working_stats = get_storage_stats_map(&mut db);
5887 db.insert_auth_token(&HardwareAuthToken {
5888 challenge: 123,
5889 userId: 456,
5890 authenticatorId: 789,
5891 authenticatorType: kmhw_authenticator_type::ANY,
5892 timestamp: Timestamp { milliSeconds: 10 },
5893 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005894 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005895 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005896 Ok(())
5897 }
5898
5899 #[test]
5900 fn test_verify_grant_table_size_reporting() -> Result<()> {
5901 const OWNER: i64 = 1;
5902 let mut db = new_test_db()?;
5903 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5904
5905 let mut working_stats = get_storage_stats_map(&mut db);
5906 db.grant(
5907 &KeyDescriptor {
5908 domain: Domain::APP,
5909 nspace: 0,
5910 alias: Some(TEST_ALIAS.to_string()),
5911 blob: None,
5912 },
5913 OWNER as u32,
5914 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005915 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005916 |_, _| Ok(()),
5917 )?;
5918
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005919 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005920
5921 Ok(())
5922 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005923
5924 #[test]
5925 fn find_auth_token_entry_returns_latest() -> Result<()> {
5926 let mut db = new_test_db()?;
5927 db.insert_auth_token(&HardwareAuthToken {
5928 challenge: 123,
5929 userId: 456,
5930 authenticatorId: 789,
5931 authenticatorType: kmhw_authenticator_type::ANY,
5932 timestamp: Timestamp { milliSeconds: 10 },
5933 mac: b"mac0".to_vec(),
5934 });
5935 std::thread::sleep(std::time::Duration::from_millis(1));
5936 db.insert_auth_token(&HardwareAuthToken {
5937 challenge: 123,
5938 userId: 457,
5939 authenticatorId: 789,
5940 authenticatorType: kmhw_authenticator_type::ANY,
5941 timestamp: Timestamp { milliSeconds: 12 },
5942 mac: b"mac1".to_vec(),
5943 });
5944 std::thread::sleep(std::time::Duration::from_millis(1));
5945 db.insert_auth_token(&HardwareAuthToken {
5946 challenge: 123,
5947 userId: 458,
5948 authenticatorId: 789,
5949 authenticatorType: kmhw_authenticator_type::ANY,
5950 timestamp: Timestamp { milliSeconds: 3 },
5951 mac: b"mac2".to_vec(),
5952 });
5953 // All three entries are in the database
5954 assert_eq!(db.perboot.auth_tokens_len(), 3);
5955 // It selected the most recent timestamp
5956 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5957 Ok(())
5958 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005959
5960 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005961 fn test_load_key_descriptor() -> Result<()> {
5962 let mut db = new_test_db()?;
5963 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5964
5965 let key = db.load_key_descriptor(key_id)?.unwrap();
5966
5967 assert_eq!(key.domain, Domain::APP);
5968 assert_eq!(key.nspace, 1);
5969 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5970
5971 // No such id
5972 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5973 Ok(())
5974 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005975}