blob: 771361886cecd23b88745e7009a32c418c8df84b [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 )?;
Chariseea1e1c482022-02-26 01:26:35 +00002117 let key_id: i64 = match self
2118 .query_kid_for_attestation_key_and_cert_chain(&tx, domain, namespace, km_uuid)?
2119 {
Max Bires55620ff2022-02-11 13:34:15 -08002120 None => return Ok(None),
Chariseea1e1c482022-02-26 01:26:35 +00002121 Some(kid) => kid,
2122 };
Max Bires55620ff2022-02-11 13:34:15 -08002123 tx.commit()
2124 .context("In retrieve_attestation_key_and_cert_chain: Failed to commit keyid query")?;
2125 let key_id_guard = KEY_ID_LOCK.get(key_id);
2126 let tx = self.conn.unchecked_transaction().context(
2127 "In retrieve_attestation_key_and_cert_chain: Failed to initialize transaction.",
2128 )?;
2129 let mut stmt = tx.prepare(
2130 "SELECT subcomponent_type, blob
2131 FROM persistent.blobentry
2132 WHERE keyentryid = ?;",
2133 )?;
2134 let rows = stmt
2135 .query_map(params![key_id_guard.id()], |row| Ok((row.get(0)?, row.get(1)?)))?
2136 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
2137 .context("query failed.")?;
2138 if rows.is_empty() {
2139 return Ok(None);
2140 } else if rows.len() != 3 {
2141 return Err(KsError::sys()).context(format!(
2142 concat!(
2143 "Expected to get a single attestation",
2144 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2145 ),
2146 rows.len()
2147 ));
2148 }
2149 let mut km_blob: Vec<u8> = Vec::new();
2150 let mut cert_chain_blob: Vec<u8> = Vec::new();
2151 let mut batch_cert_blob: Vec<u8> = Vec::new();
2152 for row in rows {
2153 let sub_type: SubComponentType = row.0;
2154 match sub_type {
2155 SubComponentType::KEY_BLOB => {
2156 km_blob = row.1;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002157 }
Max Bires55620ff2022-02-11 13:34:15 -08002158 SubComponentType::CERT_CHAIN => {
2159 cert_chain_blob = row.1;
2160 }
2161 SubComponentType::CERT => {
2162 batch_cert_blob = row.1;
2163 }
2164 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002165 }
Max Bires55620ff2022-02-11 13:34:15 -08002166 }
2167 Ok(Some((
2168 key_id_guard,
2169 CertificateChain {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002170 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002171 batch_cert: batch_cert_blob,
2172 cert_chain: cert_chain_blob,
Max Bires55620ff2022-02-11 13:34:15 -08002173 },
2174 )))
Max Bires2b2e6562020-09-22 11:22:36 -07002175 }
2176
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002177 /// Updates the alias column of the given key id `newid` with the given alias,
2178 /// and atomically, removes the alias, domain, and namespace from another row
2179 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002180 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2181 /// collector.
2182 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002183 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002184 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002185 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002186 domain: &Domain,
2187 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002188 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002189 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002190 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002191 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002192 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002193 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002194 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002195 domain
2196 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002197 }
2198 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002199 let updated = tx
2200 .execute(
2201 "UPDATE persistent.keyentry
2202 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002203 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2204 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002205 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002206 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002207 let result = tx
2208 .execute(
2209 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002210 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002211 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002212 params![
2213 alias,
2214 KeyLifeCycle::Live,
2215 newid.0,
2216 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002217 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002218 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002219 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002220 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002221 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002222 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002223 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002224 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002225 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002226 result
2227 ));
2228 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002229 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002230 }
2231
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002232 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2233 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2234 pub fn migrate_key_namespace(
2235 &mut self,
2236 key_id_guard: KeyIdGuard,
2237 destination: &KeyDescriptor,
2238 caller_uid: u32,
2239 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2240 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002241 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2242
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002243 let destination = match destination.domain {
2244 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2245 Domain::SELINUX => (*destination).clone(),
2246 domain => {
2247 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2248 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2249 }
2250 };
2251
2252 // Security critical: Must return immediately on failure. Do not remove the '?';
2253 check_permission(&destination)
2254 .context("In migrate_key_namespace: Trying to check permission.")?;
2255
2256 let alias = destination
2257 .alias
2258 .as_ref()
2259 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2260 .context("In migrate_key_namespace: Alias must be specified.")?;
2261
2262 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2263 // Query the destination location. If there is a key, the migration request fails.
2264 if tx
2265 .query_row(
2266 "SELECT id FROM persistent.keyentry
2267 WHERE alias = ? AND domain = ? AND namespace = ?;",
2268 params![alias, destination.domain.0, destination.nspace],
2269 |_| Ok(()),
2270 )
2271 .optional()
2272 .context("Failed to query destination.")?
2273 .is_some()
2274 {
2275 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2276 .context("Target already exists.");
2277 }
2278
2279 let updated = tx
2280 .execute(
2281 "UPDATE persistent.keyentry
2282 SET alias = ?, domain = ?, namespace = ?
2283 WHERE id = ?;",
2284 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2285 )
2286 .context("Failed to update key entry.")?;
2287
2288 if updated != 1 {
2289 return Err(KsError::sys())
2290 .context(format!("Update succeeded, but {} rows were updated.", updated));
2291 }
2292 Ok(()).no_gc()
2293 })
2294 .context("In migrate_key_namespace:")
2295 }
2296
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002297 /// Store a new key in a single transaction.
2298 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2299 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002300 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2301 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07002302 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002303 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002304 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002305 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002306 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002307 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002308 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08002309 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002310 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002311 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002312 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002313 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2314
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002315 let (alias, domain, namespace) = match key {
2316 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2317 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2318 (alias, key.domain, nspace)
2319 }
2320 _ => {
2321 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2322 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2323 }
2324 };
2325 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002326 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002327 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002328 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
2329
2330 // In some occasions the key blob is already upgraded during the import.
2331 // In order to make sure it gets properly deleted it is inserted into the
2332 // database here and then immediately replaced by the superseding blob.
2333 // The garbage collector will then subject the blob to deleteKey of the
2334 // KM back end to permanently invalidate the key.
2335 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
2336 Self::set_blob_internal(
2337 tx,
2338 key_id.id(),
2339 SubComponentType::KEY_BLOB,
2340 Some(blob),
2341 Some(blob_metadata),
2342 )
2343 .context("Trying to insert superseded key blob.")?;
2344 true
2345 } else {
2346 false
2347 };
2348
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002349 Self::set_blob_internal(
2350 tx,
2351 key_id.id(),
2352 SubComponentType::KEY_BLOB,
2353 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002354 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002355 )
2356 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002357 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002358 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002359 .context("Trying to insert the certificate.")?;
2360 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002361 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002362 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002363 tx,
2364 key_id.id(),
2365 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002366 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002367 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002368 )
2369 .context("Trying to insert the certificate chain.")?;
2370 }
2371 Self::insert_keyparameter_internal(tx, &key_id, params)
2372 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002373 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002374 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002375 .context("Trying to rebind alias.")?
2376 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002377 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002378 })
2379 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002380 }
2381
Janis Danisevskis377d1002021-01-27 19:07:48 -08002382 /// Store a new certificate
2383 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2384 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002385 pub fn store_new_certificate(
2386 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002387 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002388 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002389 cert: &[u8],
2390 km_uuid: &Uuid,
2391 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002392 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2393
Janis Danisevskis377d1002021-01-27 19:07:48 -08002394 let (alias, domain, namespace) = match key {
2395 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2396 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2397 (alias, key.domain, nspace)
2398 }
2399 _ => {
2400 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2401 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2402 )
2403 }
2404 };
2405 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002406 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002407 .context("Trying to create new key entry.")?;
2408
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002409 Self::set_blob_internal(
2410 tx,
2411 key_id.id(),
2412 SubComponentType::CERT_CHAIN,
2413 Some(cert),
2414 None,
2415 )
2416 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002417
2418 let mut metadata = KeyMetaData::new();
2419 metadata.add(KeyMetaEntry::CreationDate(
2420 DateTime::now().context("Trying to make creation time.")?,
2421 ));
2422
2423 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2424
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002425 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002426 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002427 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002428 })
2429 .context("In store_new_certificate.")
2430 }
2431
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002432 // Helper function loading the key_id given the key descriptor
2433 // tuple comprising domain, namespace, and alias.
2434 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002435 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002436 let alias = key
2437 .alias
2438 .as_ref()
2439 .map_or_else(|| Err(KsError::sys()), Ok)
2440 .context("In load_key_entry_id: Alias must be specified.")?;
2441 let mut stmt = tx
2442 .prepare(
2443 "SELECT id FROM persistent.keyentry
2444 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002445 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002446 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002447 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002448 AND alias = ?
2449 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002450 )
2451 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2452 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002453 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002454 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002455 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002456 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002457 .get(0)
2458 .context("Failed to unpack id.")
2459 })
2460 .context("In load_key_entry_id.")
2461 }
2462
2463 /// This helper function completes the access tuple of a key, which is required
2464 /// to perform access control. The strategy depends on the `domain` field in the
2465 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002466 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002467 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002468 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002469 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002470 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002471 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002472 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002473 /// `namespace`.
2474 /// In each case the information returned is sufficient to perform the access
2475 /// check and the key id can be used to load further key artifacts.
2476 fn load_access_tuple(
2477 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002478 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002479 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002480 caller_uid: u32,
2481 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2482 match key.domain {
2483 // Domain App or SELinux. In this case we load the key_id from
2484 // the keyentry database for further loading of key components.
2485 // We already have the full access tuple to perform access control.
2486 // The only distinction is that we use the caller_uid instead
2487 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002488 // Domain::APP.
2489 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002490 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002491 if access_key.domain == Domain::APP {
2492 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002493 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002494 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002495 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002496
2497 Ok((key_id, access_key, None))
2498 }
2499
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002500 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002501 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002502 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002503 let mut stmt = tx
2504 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002505 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002506 WHERE grantee = ? AND id = ? AND
2507 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002508 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002509 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002510 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002511 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002512 .context("Domain:Grant: query failed.")?;
2513 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002514 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002515 let r =
2516 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002517 Ok((
2518 r.get(0).context("Failed to unpack key_id.")?,
2519 r.get(1).context("Failed to unpack access_vector.")?,
2520 ))
2521 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002522 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002523 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002524 }
2525
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002526 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002527 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002528 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002529 let (domain, namespace): (Domain, i64) = {
2530 let mut stmt = tx
2531 .prepare(
2532 "SELECT domain, namespace FROM persistent.keyentry
2533 WHERE
2534 id = ?
2535 AND state = ?;",
2536 )
2537 .context("Domain::KEY_ID: prepare statement failed")?;
2538 let mut rows = stmt
2539 .query(params![key.nspace, KeyLifeCycle::Live])
2540 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002541 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002542 let r =
2543 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002544 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002545 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002546 r.get(1).context("Failed to unpack namespace.")?,
2547 ))
2548 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002549 .context("Domain::KEY_ID.")?
2550 };
2551
2552 // We may use a key by id after loading it by grant.
2553 // In this case we have to check if the caller has a grant for this particular
2554 // key. We can skip this if we already know that the caller is the owner.
2555 // But we cannot know this if domain is anything but App. E.g. in the case
2556 // of Domain::SELINUX we have to speculatively check for grants because we have to
2557 // consult the SEPolicy before we know if the caller is the owner.
2558 let access_vector: Option<KeyPermSet> =
2559 if domain != Domain::APP || namespace != caller_uid as i64 {
2560 let access_vector: Option<i32> = tx
2561 .query_row(
2562 "SELECT access_vector FROM persistent.grant
2563 WHERE grantee = ? AND keyentryid = ?;",
2564 params![caller_uid as i64, key.nspace],
2565 |row| row.get(0),
2566 )
2567 .optional()
2568 .context("Domain::KEY_ID: query grant failed.")?;
2569 access_vector.map(|p| p.into())
2570 } else {
2571 None
2572 };
2573
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002574 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002575 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002576 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002577 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002578
Janis Danisevskis45760022021-01-19 16:34:10 -08002579 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002580 }
2581 _ => Err(anyhow!(KsError::sys())),
2582 }
2583 }
2584
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002585 fn load_blob_components(
2586 key_id: i64,
2587 load_bits: KeyEntryLoadBits,
2588 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002589 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002590 let mut stmt = tx
2591 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002592 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002593 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2594 )
2595 .context("In load_blob_components: prepare statement failed.")?;
2596
2597 let mut rows =
2598 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2599
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002600 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002601 let mut cert_blob: Option<Vec<u8>> = None;
2602 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002603 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002604 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002605 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002606 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002607 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002608 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2609 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002610 key_blob = Some((
2611 row.get(0).context("Failed to extract key blob id.")?,
2612 row.get(2).context("Failed to extract key blob.")?,
2613 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002614 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002615 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002616 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002617 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002618 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002619 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002620 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002621 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002622 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002623 (SubComponentType::CERT, _, _)
2624 | (SubComponentType::CERT_CHAIN, _, _)
2625 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002626 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2627 }
2628 Ok(())
2629 })
2630 .context("In load_blob_components.")?;
2631
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002632 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2633 Ok(Some((
2634 blob,
2635 BlobMetaData::load_from_db(blob_id, tx)
2636 .context("In load_blob_components: Trying to load blob_metadata.")?,
2637 )))
2638 })?;
2639
2640 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002641 }
2642
2643 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2644 let mut stmt = tx
2645 .prepare(
2646 "SELECT tag, data, security_level from persistent.keyparameter
2647 WHERE keyentryid = ?;",
2648 )
2649 .context("In load_key_parameters: prepare statement failed.")?;
2650
2651 let mut parameters: Vec<KeyParameter> = Vec::new();
2652
2653 let mut rows =
2654 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002655 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002656 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2657 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002658 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002659 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002660 .context("Failed to read KeyParameter.")?,
2661 );
2662 Ok(())
2663 })
2664 .context("In load_key_parameters.")?;
2665
2666 Ok(parameters)
2667 }
2668
Qi Wub9433b52020-12-01 14:52:46 +08002669 /// Decrements the usage count of a limited use key. This function first checks whether the
2670 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2671 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2672 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002673 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002674 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2675
Qi Wub9433b52020-12-01 14:52:46 +08002676 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2677 let limit: Option<i32> = tx
2678 .query_row(
2679 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2680 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2681 |row| row.get(0),
2682 )
2683 .optional()
2684 .context("Trying to load usage count")?;
2685
2686 let limit = limit
2687 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2688 .context("The Key no longer exists. Key is exhausted.")?;
2689
2690 tx.execute(
2691 "UPDATE persistent.keyparameter
2692 SET data = data - 1
2693 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2694 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2695 )
2696 .context("Failed to update key usage count.")?;
2697
2698 match limit {
2699 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002700 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002701 .context("Trying to mark limited use key for deletion."),
2702 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002703 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002704 }
2705 })
2706 .context("In check_and_update_key_usage_count.")
2707 }
2708
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002709 /// Load a key entry by the given key descriptor.
2710 /// It uses the `check_permission` callback to verify if the access is allowed
2711 /// given the key access tuple read from the database using `load_access_tuple`.
2712 /// With `load_bits` the caller may specify which blobs shall be loaded from
2713 /// the blob database.
2714 pub fn load_key_entry(
2715 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002716 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002717 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002718 load_bits: KeyEntryLoadBits,
2719 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002720 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2721 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002722 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2723
Janis Danisevskis66784c42021-01-27 08:40:25 -08002724 loop {
2725 match self.load_key_entry_internal(
2726 key,
2727 key_type,
2728 load_bits,
2729 caller_uid,
2730 &check_permission,
2731 ) {
2732 Ok(result) => break Ok(result),
2733 Err(e) => {
2734 if Self::is_locked_error(&e) {
2735 std::thread::sleep(std::time::Duration::from_micros(500));
2736 continue;
2737 } else {
2738 return Err(e).context("In load_key_entry.");
2739 }
2740 }
2741 }
2742 }
2743 }
2744
2745 fn load_key_entry_internal(
2746 &mut self,
2747 key: &KeyDescriptor,
2748 key_type: KeyType,
2749 load_bits: KeyEntryLoadBits,
2750 caller_uid: u32,
2751 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002752 ) -> Result<(KeyIdGuard, KeyEntry)> {
2753 // KEY ID LOCK 1/2
2754 // If we got a key descriptor with a key id we can get the lock right away.
2755 // Otherwise we have to defer it until we know the key id.
2756 let key_id_guard = match key.domain {
2757 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2758 _ => None,
2759 };
2760
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002761 let tx = self
2762 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002763 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002764 .context("In load_key_entry: Failed to initialize transaction.")?;
2765
2766 // Load the key_id and complete the access control tuple.
2767 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002768 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2769 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002770
2771 // Perform access control. It is vital that we return here if the permission is denied.
2772 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002773 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002774
Janis Danisevskisaec14592020-11-12 09:41:49 -08002775 // KEY ID LOCK 2/2
2776 // If we did not get a key id lock by now, it was because we got a key descriptor
2777 // without a key id. At this point we got the key id, so we can try and get a lock.
2778 // However, we cannot block here, because we are in the middle of the transaction.
2779 // So first we try to get the lock non blocking. If that fails, we roll back the
2780 // transaction and block until we get the lock. After we successfully got the lock,
2781 // we start a new transaction and load the access tuple again.
2782 //
2783 // We don't need to perform access control again, because we already established
2784 // that the caller had access to the given key. But we need to make sure that the
2785 // key id still exists. So we have to load the key entry by key id this time.
2786 let (key_id_guard, tx) = match key_id_guard {
2787 None => match KEY_ID_LOCK.try_get(key_id) {
2788 None => {
2789 // Roll back the transaction.
2790 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002791
Janis Danisevskisaec14592020-11-12 09:41:49 -08002792 // Block until we have a key id lock.
2793 let key_id_guard = KEY_ID_LOCK.get(key_id);
2794
2795 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002796 let tx = self
2797 .conn
2798 .unchecked_transaction()
2799 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002800
2801 Self::load_access_tuple(
2802 &tx,
2803 // This time we have to load the key by the retrieved key id, because the
2804 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002805 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002806 domain: Domain::KEY_ID,
2807 nspace: key_id,
2808 ..Default::default()
2809 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002810 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002811 caller_uid,
2812 )
2813 .context("In load_key_entry. (deferred key lock)")?;
2814 (key_id_guard, tx)
2815 }
2816 Some(l) => (l, tx),
2817 },
2818 Some(key_id_guard) => (key_id_guard, tx),
2819 };
2820
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002821 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2822 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002823
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002824 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2825
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002826 Ok((key_id_guard, key_entry))
2827 }
2828
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002829 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002830 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002831 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2832 .context("Trying to delete keyentry.")?;
2833 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2834 .context("Trying to delete keymetadata.")?;
2835 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2836 .context("Trying to delete keyparameters.")?;
2837 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2838 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002839 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002840 }
2841
2842 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002843 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002844 pub fn unbind_key(
2845 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002846 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002847 key_type: KeyType,
2848 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002849 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002850 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002851 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2852
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002853 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2854 let (key_id, access_key_descriptor, access_vector) =
2855 Self::load_access_tuple(tx, key, key_type, caller_uid)
2856 .context("Trying to get access tuple.")?;
2857
2858 // Perform access control. It is vital that we return here if the permission is denied.
2859 // So do not touch that '?' at the end.
2860 check_permission(&access_key_descriptor, access_vector)
2861 .context("While checking permission.")?;
2862
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002863 Self::mark_unreferenced(tx, key_id)
2864 .map(|need_gc| (need_gc, ()))
2865 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002866 })
2867 .context("In unbind_key.")
2868 }
2869
Max Bires8e93d2b2021-01-14 13:17:59 -08002870 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2871 tx.query_row(
2872 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2873 params![key_id],
2874 |row| row.get(0),
2875 )
2876 .context("In get_key_km_uuid.")
2877 }
2878
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002879 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2880 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2881 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002882 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2883
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002884 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2885 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2886 .context("In unbind_keys_for_namespace.");
2887 }
2888 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2889 tx.execute(
2890 "DELETE FROM persistent.keymetadata
2891 WHERE keyentryid IN (
2892 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002893 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002894 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002895 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002896 )
2897 .context("Trying to delete keymetadata.")?;
2898 tx.execute(
2899 "DELETE FROM persistent.keyparameter
2900 WHERE keyentryid IN (
2901 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002902 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002903 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002904 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002905 )
2906 .context("Trying to delete keyparameters.")?;
2907 tx.execute(
2908 "DELETE FROM persistent.grant
2909 WHERE keyentryid IN (
2910 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002911 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002912 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002913 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002914 )
2915 .context("Trying to delete grants.")?;
2916 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002917 "DELETE FROM persistent.keyentry
2918 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2919 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002920 )
2921 .context("Trying to delete keyentry.")?;
2922 Ok(()).need_gc()
2923 })
2924 .context("In unbind_keys_for_namespace")
2925 }
2926
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002927 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2928 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2929 {
2930 tx.execute(
2931 "DELETE FROM persistent.keymetadata
2932 WHERE keyentryid IN (
2933 SELECT id FROM persistent.keyentry
2934 WHERE state = ?
2935 );",
2936 params![KeyLifeCycle::Unreferenced],
2937 )
2938 .context("Trying to delete keymetadata.")?;
2939 tx.execute(
2940 "DELETE FROM persistent.keyparameter
2941 WHERE keyentryid IN (
2942 SELECT id FROM persistent.keyentry
2943 WHERE state = ?
2944 );",
2945 params![KeyLifeCycle::Unreferenced],
2946 )
2947 .context("Trying to delete keyparameters.")?;
2948 tx.execute(
2949 "DELETE FROM persistent.grant
2950 WHERE keyentryid IN (
2951 SELECT id FROM persistent.keyentry
2952 WHERE state = ?
2953 );",
2954 params![KeyLifeCycle::Unreferenced],
2955 )
2956 .context("Trying to delete grants.")?;
2957 tx.execute(
2958 "DELETE FROM persistent.keyentry
2959 WHERE state = ?;",
2960 params![KeyLifeCycle::Unreferenced],
2961 )
2962 .context("Trying to delete keyentry.")?;
2963 Result::<()>::Ok(())
2964 }
2965 .context("In cleanup_unreferenced")
2966 }
2967
Hasini Gunasingheda895552021-01-27 19:34:37 +00002968 /// Delete the keys created on behalf of the user, denoted by the user id.
2969 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2970 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2971 /// The caller of this function should notify the gc if the returned value is true.
2972 pub fn unbind_keys_for_user(
2973 &mut self,
2974 user_id: u32,
2975 keep_non_super_encrypted_keys: bool,
2976 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002977 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2978
Hasini Gunasingheda895552021-01-27 19:34:37 +00002979 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2980 let mut stmt = tx
2981 .prepare(&format!(
2982 "SELECT id from persistent.keyentry
2983 WHERE (
2984 key_type = ?
2985 AND domain = ?
2986 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2987 AND state = ?
2988 ) OR (
2989 key_type = ?
2990 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002991 AND state = ?
2992 );",
2993 aid_user_offset = AID_USER_OFFSET
2994 ))
2995 .context(concat!(
2996 "In unbind_keys_for_user. ",
2997 "Failed to prepare the query to find the keys created by apps."
2998 ))?;
2999
3000 let mut rows = stmt
3001 .query(params![
3002 // WHERE client key:
3003 KeyType::Client,
3004 Domain::APP.0 as u32,
3005 user_id,
3006 KeyLifeCycle::Live,
3007 // OR super key:
3008 KeyType::Super,
3009 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00003010 KeyLifeCycle::Live
3011 ])
3012 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
3013
3014 let mut key_ids: Vec<i64> = Vec::new();
3015 db_utils::with_rows_extract_all(&mut rows, |row| {
3016 key_ids
3017 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
3018 Ok(())
3019 })
3020 .context("In unbind_keys_for_user.")?;
3021
3022 let mut notify_gc = false;
3023 for key_id in key_ids {
3024 if keep_non_super_encrypted_keys {
3025 // Load metadata and filter out non-super-encrypted keys.
3026 if let (_, Some((_, blob_metadata)), _, _) =
3027 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
3028 .context("In unbind_keys_for_user: Trying to load blob info.")?
3029 {
3030 if blob_metadata.encrypted_by().is_none() {
3031 continue;
3032 }
3033 }
3034 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003035 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00003036 .context("In unbind_keys_for_user.")?
3037 || notify_gc;
3038 }
3039 Ok(()).do_gc(notify_gc)
3040 })
3041 .context("In unbind_keys_for_user.")
3042 }
3043
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003044 fn load_key_components(
3045 tx: &Transaction,
3046 load_bits: KeyEntryLoadBits,
3047 key_id: i64,
3048 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003049 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003050
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003051 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003052 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003053
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003054 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08003055 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003056
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003057 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08003058 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003059
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003060 Ok(KeyEntry {
3061 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003062 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003063 cert: cert_blob,
3064 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003065 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003066 parameters,
3067 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003068 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003069 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003070 }
3071
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003072 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3073 /// The key descriptors will have the domain, nspace, and alias field set.
3074 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07003075 pub fn list(
3076 &mut self,
3077 domain: Domain,
3078 namespace: i64,
3079 key_type: KeyType,
3080 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003081 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3082
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3084 let mut stmt = tx
3085 .prepare(
3086 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07003087 WHERE domain = ?
3088 AND namespace = ?
3089 AND alias IS NOT NULL
3090 AND state = ?
3091 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003092 )
3093 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003094
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003096 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08003097 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003098
Janis Danisevskis66784c42021-01-27 08:40:25 -08003099 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3100 db_utils::with_rows_extract_all(&mut rows, |row| {
3101 descriptors.push(KeyDescriptor {
3102 domain,
3103 nspace: namespace,
3104 alias: Some(row.get(0).context("Trying to extract alias.")?),
3105 blob: None,
3106 });
3107 Ok(())
3108 })
3109 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003110 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003111 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003112 }
3113
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003114 /// Adds a grant to the grant table.
3115 /// Like `load_key_entry` this function loads the access tuple before
3116 /// it uses the callback for a permission check. Upon success,
3117 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3118 /// grant table. The new row will have a randomized id, which is used as
3119 /// grant id in the namespace field of the resulting KeyDescriptor.
3120 pub fn grant(
3121 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003122 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003123 caller_uid: u32,
3124 grantee_uid: u32,
3125 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003126 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003127 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003128 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3129
Janis Danisevskis66784c42021-01-27 08:40:25 -08003130 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3131 // Load the key_id and complete the access control tuple.
3132 // We ignore the access vector here because grants cannot be granted.
3133 // The access vector returned here expresses the permissions the
3134 // grantee has if key.domain == Domain::GRANT. But this vector
3135 // cannot include the grant permission by design, so there is no way the
3136 // subsequent permission check can pass.
3137 // We could check key.domain == Domain::GRANT and fail early.
3138 // But even if we load the access tuple by grant here, the permission
3139 // check denies the attempt to create a grant by grant descriptor.
3140 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003141 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003142 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003143
Janis Danisevskis66784c42021-01-27 08:40:25 -08003144 // Perform access control. It is vital that we return here if the permission
3145 // was denied. So do not touch that '?' at the end of the line.
3146 // This permission check checks if the caller has the grant permission
3147 // for the given key and in addition to all of the permissions
3148 // expressed in `access_vector`.
3149 check_permission(&access_key_descriptor, &access_vector)
3150 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003151
Janis Danisevskis66784c42021-01-27 08:40:25 -08003152 let grant_id = if let Some(grant_id) = tx
3153 .query_row(
3154 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003155 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003156 params![key_id, grantee_uid],
3157 |row| row.get(0),
3158 )
3159 .optional()
3160 .context("In grant: Failed get optional existing grant id.")?
3161 {
3162 tx.execute(
3163 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003164 SET access_vector = ?
3165 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003166 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003167 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003168 .context("In grant: Failed to update existing grant.")?;
3169 grant_id
3170 } else {
3171 Self::insert_with_retry(|id| {
3172 tx.execute(
3173 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3174 VALUES (?, ?, ?, ?);",
3175 params![id, grantee_uid, key_id, i32::from(access_vector)],
3176 )
3177 })
3178 .context("In grant")?
3179 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003180
Janis Danisevskis66784c42021-01-27 08:40:25 -08003181 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003182 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003183 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003184 }
3185
3186 /// This function checks permissions like `grant` and `load_key_entry`
3187 /// before removing a grant from the grant table.
3188 pub fn ungrant(
3189 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003190 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003191 caller_uid: u32,
3192 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003193 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003194 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003195 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3196
Janis Danisevskis66784c42021-01-27 08:40:25 -08003197 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3198 // Load the key_id and complete the access control tuple.
3199 // We ignore the access vector here because grants cannot be granted.
3200 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003201 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003202 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003203
Janis Danisevskis66784c42021-01-27 08:40:25 -08003204 // Perform access control. We must return here if the permission
3205 // was denied. So do not touch the '?' at the end of this line.
3206 check_permission(&access_key_descriptor)
3207 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003208
Janis Danisevskis66784c42021-01-27 08:40:25 -08003209 tx.execute(
3210 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003211 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003212 params![key_id, grantee_uid],
3213 )
3214 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003215
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003216 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003217 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003218 }
3219
Joel Galenson845f74b2020-09-09 14:11:55 -07003220 // Generates a random id and passes it to the given function, which will
3221 // try to insert it into a database. If that insertion fails, retry;
3222 // otherwise return the id.
3223 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3224 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003225 let newid: i64 = match random() {
3226 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3227 i => i,
3228 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003229 match inserter(newid) {
3230 // If the id already existed, try again.
3231 Err(rusqlite::Error::SqliteFailure(
3232 libsqlite3_sys::Error {
3233 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3234 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3235 },
3236 _,
3237 )) => (),
3238 Err(e) => {
3239 return Err(e).context("In insert_with_retry: failed to insert into database.")
3240 }
3241 _ => return Ok(newid),
3242 }
3243 }
3244 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003245
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003246 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3247 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3248 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3249 auth_token.clone(),
3250 MonotonicRawTime::now(),
3251 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003252 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003253
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003254 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003255 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003256 where
3257 F: Fn(&AuthTokenEntry) -> bool,
3258 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003259 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003260 }
3261
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003262 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003263 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3264 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003265 }
3266
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003267 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003268 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3269 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003270 }
3271
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003272 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003273 fn get_last_off_body(&self) -> MonotonicRawTime {
3274 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003275 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003276
3277 /// Load descriptor of a key by key id
3278 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3279 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3280
3281 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3282 tx.query_row(
3283 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3284 params![key_id],
3285 |row| {
3286 Ok(KeyDescriptor {
3287 domain: Domain(row.get(0)?),
3288 nspace: row.get(1)?,
3289 alias: row.get(2)?,
3290 blob: None,
3291 })
3292 },
3293 )
3294 .optional()
3295 .context("Trying to load key descriptor")
3296 .no_gc()
3297 })
3298 .context("In load_key_descriptor.")
3299 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003300}
3301
3302#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08003303pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07003304
3305 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003306 use crate::key_parameter::{
3307 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3308 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3309 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003310 use crate::key_perm_set;
3311 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08003312 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003313 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003314 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3315 HardwareAuthToken::HardwareAuthToken,
3316 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003317 };
3318 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003319 Timestamp::Timestamp,
3320 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003321 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003322 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003323 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003324 use std::collections::BTreeMap;
3325 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003326 use std::sync::atomic::{AtomicU8, Ordering};
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003327 use std::sync::{Arc, RwLock};
Janis Danisevskisaec14592020-11-12 09:41:49 -08003328 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003329 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003330 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003331 #[cfg(disabled)]
3332 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003333
Seth Moore7ee79f92021-12-07 11:42:49 -08003334 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003335 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003336
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003337 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003338 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003339 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003340 })?;
3341 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003342 }
3343
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003344 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3345 where
3346 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3347 {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003348 let super_key: Arc<RwLock<SuperKeyManager>> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003349
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003350 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003351 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003352
Janis Danisevskis3395f862021-05-06 10:54:17 -07003353 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003354 }
3355
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003356 fn rebind_alias(
3357 db: &mut KeystoreDB,
3358 newid: &KeyIdGuard,
3359 alias: &str,
3360 domain: Domain,
3361 namespace: i64,
3362 ) -> Result<bool> {
3363 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003364 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003365 })
3366 .context("In rebind_alias.")
3367 }
3368
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003369 #[test]
3370 fn datetime() -> Result<()> {
3371 let conn = Connection::open_in_memory()?;
3372 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3373 let now = SystemTime::now();
3374 let duration = Duration::from_secs(1000);
3375 let then = now.checked_sub(duration).unwrap();
3376 let soon = now.checked_add(duration).unwrap();
3377 conn.execute(
3378 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3379 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3380 )?;
3381 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3382 let mut rows = stmt.query(NO_PARAMS)?;
3383 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3384 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3385 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3386 assert!(rows.next()?.is_none());
3387 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3388 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3389 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3390 Ok(())
3391 }
3392
Joel Galenson0891bc12020-07-20 10:37:03 -07003393 // Ensure that we're using the "injected" random function, not the real one.
3394 #[test]
3395 fn test_mocked_random() {
3396 let rand1 = random();
3397 let rand2 = random();
3398 let rand3 = random();
3399 if rand1 == rand2 {
3400 assert_eq!(rand2 + 1, rand3);
3401 } else {
3402 assert_eq!(rand1 + 1, rand2);
3403 assert_eq!(rand2, rand3);
3404 }
3405 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003406
Joel Galenson26f4d012020-07-17 14:57:21 -07003407 // Test that we have the correct tables.
3408 #[test]
3409 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003410 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003411 let tables = db
3412 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003413 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003414 .query_map(params![], |row| row.get(0))?
3415 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003416 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003417 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003418 assert_eq!(tables[1], "blobmetadata");
3419 assert_eq!(tables[2], "grant");
3420 assert_eq!(tables[3], "keyentry");
3421 assert_eq!(tables[4], "keymetadata");
3422 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003423 Ok(())
3424 }
3425
3426 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003427 fn test_auth_token_table_invariant() -> Result<()> {
3428 let mut db = new_test_db()?;
3429 let auth_token1 = HardwareAuthToken {
3430 challenge: i64::MAX,
3431 userId: 200,
3432 authenticatorId: 200,
3433 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3434 timestamp: Timestamp { milliSeconds: 500 },
3435 mac: String::from("mac").into_bytes(),
3436 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003437 db.insert_auth_token(&auth_token1);
3438 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003439 assert_eq!(auth_tokens_returned.len(), 1);
3440
3441 // insert another auth token with the same values for the columns in the UNIQUE constraint
3442 // of the auth token table and different value for timestamp
3443 let auth_token2 = HardwareAuthToken {
3444 challenge: i64::MAX,
3445 userId: 200,
3446 authenticatorId: 200,
3447 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3448 timestamp: Timestamp { milliSeconds: 600 },
3449 mac: String::from("mac").into_bytes(),
3450 };
3451
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003452 db.insert_auth_token(&auth_token2);
3453 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003454 assert_eq!(auth_tokens_returned.len(), 1);
3455
3456 if let Some(auth_token) = auth_tokens_returned.pop() {
3457 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3458 }
3459
3460 // insert another auth token with the different values for the columns in the UNIQUE
3461 // constraint of the auth token table
3462 let auth_token3 = HardwareAuthToken {
3463 challenge: i64::MAX,
3464 userId: 201,
3465 authenticatorId: 200,
3466 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3467 timestamp: Timestamp { milliSeconds: 600 },
3468 mac: String::from("mac").into_bytes(),
3469 };
3470
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003471 db.insert_auth_token(&auth_token3);
3472 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003473 assert_eq!(auth_tokens_returned.len(), 2);
3474
3475 Ok(())
3476 }
3477
3478 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003479 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3480 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003481 }
3482
3483 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003484 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003485 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003486 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003487
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003488 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003489 let entries = get_keyentry(&db)?;
3490 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003491
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003492 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003493
3494 let entries_new = get_keyentry(&db)?;
3495 assert_eq!(entries, entries_new);
3496 Ok(())
3497 }
3498
3499 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003500 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003501 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3502 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003503 }
3504
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003505 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003506
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003507 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3508 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003509
3510 let entries = get_keyentry(&db)?;
3511 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003512 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3513 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003514
3515 // Test that we must pass in a valid Domain.
3516 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003517 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003518 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003519 );
3520 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003521 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003522 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003523 );
3524 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003525 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003526 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003527 );
3528
3529 Ok(())
3530 }
3531
Joel Galenson33c04ad2020-08-03 11:04:38 -07003532 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003533 fn test_add_unsigned_key() -> Result<()> {
3534 let mut db = new_test_db()?;
3535 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3536 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3537 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3538 db.create_attestation_key_entry(
3539 &public_key,
3540 &raw_public_key,
3541 &private_key,
3542 &KEYSTORE_UUID,
3543 )?;
3544 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3545 assert_eq!(keys.len(), 1);
3546 assert_eq!(keys[0], public_key);
3547 Ok(())
3548 }
3549
3550 #[test]
3551 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3552 let mut db = new_test_db()?;
Max Birescd7f7412022-02-11 13:47:36 -08003553 let expiration_date: i64 =
3554 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3555 + EXPIRATION_BUFFER_MS
3556 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003557 let namespace: i64 = 30;
3558 let base_byte: u8 = 1;
3559 let loaded_values =
3560 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3561 let chain =
3562 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Chris Wailes3877f292021-07-26 19:24:18 -07003563 assert!(chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003564 let (_, cert_chain) = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003565 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003566 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3567 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003568 Ok(())
3569 }
3570
3571 #[test]
3572 fn test_get_attestation_pool_status() -> Result<()> {
3573 let mut db = new_test_db()?;
3574 let namespace: i64 = 30;
3575 load_attestation_key_pool(
3576 &mut db, 10, /* expiration */
3577 namespace, 0x01, /* base_byte */
3578 )?;
3579 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3580 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3581 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3582 assert_eq!(status.expiring, 0);
3583 assert_eq!(status.attested, 3);
3584 assert_eq!(status.unassigned, 0);
3585 assert_eq!(status.total, 3);
3586 assert_eq!(
3587 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3588 1
3589 );
3590 assert_eq!(
3591 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3592 2
3593 );
3594 assert_eq!(
3595 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3596 3
3597 );
3598 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3599 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3600 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3601 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003602 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003603 db.create_attestation_key_entry(
3604 &public_key,
3605 &raw_public_key,
3606 &private_key,
3607 &KEYSTORE_UUID,
3608 )?;
3609 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3610 assert_eq!(status.attested, 3);
3611 assert_eq!(status.unassigned, 0);
3612 assert_eq!(status.total, 4);
3613 db.store_signed_attestation_certificate_chain(
3614 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003615 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003616 &cert_chain,
3617 20,
3618 &KEYSTORE_UUID,
3619 )?;
3620 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3621 assert_eq!(status.attested, 4);
3622 assert_eq!(status.unassigned, 1);
3623 assert_eq!(status.total, 4);
3624 Ok(())
3625 }
3626
3627 #[test]
3628 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003629 let temp_dir =
3630 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3631 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003632 let expiration_date: i64 =
Max Birescd7f7412022-02-11 13:47:36 -08003633 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3634 + EXPIRATION_BUFFER_MS
3635 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003636 let namespace: i64 = 30;
3637 let namespace_del1: i64 = 45;
3638 let namespace_del2: i64 = 60;
3639 let entry_values = load_attestation_key_pool(
3640 &mut db,
3641 expiration_date,
3642 namespace,
3643 0x01, /* base_byte */
3644 )?;
3645 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
Max Birescd7f7412022-02-11 13:47:36 -08003646 load_attestation_key_pool(&mut db, expiration_date - 10001, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003647
3648 let blob_entry_row_count: u32 = db
3649 .conn
3650 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3651 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003652 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3653 // one key, one certificate chain, and one certificate.
3654 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003655
Max Bires2b2e6562020-09-22 11:22:36 -07003656 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3657
3658 let mut cert_chain =
3659 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003660 assert!(cert_chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003661 let (_, value) = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003662 assert_eq!(entry_values.batch_cert, value.batch_cert);
3663 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003664 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003665
3666 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3667 Domain::APP,
3668 namespace_del1,
3669 &KEYSTORE_UUID,
3670 )?;
Chariseea1e1c482022-02-26 01:26:35 +00003671 assert!(cert_chain.is_none());
Max Bires2b2e6562020-09-22 11:22:36 -07003672 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3673 Domain::APP,
3674 namespace_del2,
3675 &KEYSTORE_UUID,
3676 )?;
Chariseea1e1c482022-02-26 01:26:35 +00003677 assert!(cert_chain.is_none());
Max Bires2b2e6562020-09-22 11:22:36 -07003678
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003679 // Give the garbage collector half a second to catch up.
3680 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003681
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003682 let blob_entry_row_count: u32 = db
3683 .conn
3684 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3685 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003686 // There shound be 3 blob entries left, because we deleted two of the attestation
3687 // key entries with three blobs each.
3688 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003689
Max Bires2b2e6562020-09-22 11:22:36 -07003690 Ok(())
3691 }
3692
Max Birescd7f7412022-02-11 13:47:36 -08003693 fn compare_rem_prov_values(
3694 expected: &RemoteProvValues,
3695 actual: Option<(KeyIdGuard, CertificateChain)>,
3696 ) {
3697 assert!(actual.is_some());
3698 let (_, value) = actual.unwrap();
3699 assert_eq!(expected.batch_cert, value.batch_cert);
3700 assert_eq!(expected.cert_chain, value.cert_chain);
3701 assert_eq!(expected.priv_key, value.private_key.to_vec());
3702 }
3703
3704 #[test]
3705 fn test_dont_remove_valid_certs() -> Result<()> {
3706 let temp_dir =
3707 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3708 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
3709 let expiration_date: i64 =
3710 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3711 + EXPIRATION_BUFFER_MS
3712 + 10000;
3713 let namespace1: i64 = 30;
3714 let namespace2: i64 = 45;
3715 let namespace3: i64 = 60;
3716 let entry_values1 = load_attestation_key_pool(
3717 &mut db,
3718 expiration_date,
3719 namespace1,
3720 0x01, /* base_byte */
3721 )?;
3722 let entry_values2 =
3723 load_attestation_key_pool(&mut db, expiration_date + 40000, namespace2, 0x02)?;
3724 let entry_values3 =
3725 load_attestation_key_pool(&mut db, expiration_date - 9000, namespace3, 0x03)?;
3726
3727 let blob_entry_row_count: u32 = db
3728 .conn
3729 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3730 .expect("Failed to get blob entry row count.");
3731 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3732 // one key, one certificate chain, and one certificate.
3733 assert_eq!(blob_entry_row_count, 9);
3734
3735 let mut cert_chain =
3736 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace1, &KEYSTORE_UUID)?;
3737 compare_rem_prov_values(&entry_values1, cert_chain);
3738
3739 cert_chain =
3740 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace2, &KEYSTORE_UUID)?;
3741 compare_rem_prov_values(&entry_values2, cert_chain);
3742
3743 cert_chain =
3744 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace3, &KEYSTORE_UUID)?;
3745 compare_rem_prov_values(&entry_values3, cert_chain);
3746
3747 // Give the garbage collector half a second to catch up.
3748 std::thread::sleep(Duration::from_millis(500));
3749
3750 let blob_entry_row_count: u32 = db
3751 .conn
3752 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3753 .expect("Failed to get blob entry row count.");
3754 // There shound be 9 blob entries left, because all three keys are valid with
3755 // three blobs each.
3756 assert_eq!(blob_entry_row_count, 9);
3757
3758 Ok(())
3759 }
Max Bires2b2e6562020-09-22 11:22:36 -07003760 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003761 fn test_delete_all_attestation_keys() -> Result<()> {
3762 let mut db = new_test_db()?;
3763 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3764 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003765 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003766 let result = db.delete_all_attestation_keys()?;
3767
3768 // Give the garbage collector half a second to catch up.
3769 std::thread::sleep(Duration::from_millis(500));
3770
3771 // Attestation keys should be deleted, and the regular key should remain.
3772 assert_eq!(result, 2);
3773
3774 Ok(())
3775 }
3776
3777 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003778 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003779 fn extractor(
3780 ke: &KeyEntryRow,
3781 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3782 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003783 }
3784
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003785 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003786 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3787 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003788 let entries = get_keyentry(&db)?;
3789 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003790 assert_eq!(
3791 extractor(&entries[0]),
3792 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3793 );
3794 assert_eq!(
3795 extractor(&entries[1]),
3796 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3797 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003798
3799 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003800 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003801 let entries = get_keyentry(&db)?;
3802 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003803 assert_eq!(
3804 extractor(&entries[0]),
3805 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3806 );
3807 assert_eq!(
3808 extractor(&entries[1]),
3809 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3810 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003811
3812 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003813 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003814 let entries = get_keyentry(&db)?;
3815 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003816 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3817 assert_eq!(
3818 extractor(&entries[1]),
3819 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3820 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003821
3822 // Test that we must pass in a valid Domain.
3823 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003824 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003825 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003826 );
3827 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003828 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003829 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003830 );
3831 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003832 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003833 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003834 );
3835
3836 // Test that we correctly handle setting an alias for something that does not exist.
3837 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003838 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003839 "Expected to update a single entry but instead updated 0",
3840 );
3841 // Test that we correctly abort the transaction in this case.
3842 let entries = get_keyentry(&db)?;
3843 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003844 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3845 assert_eq!(
3846 extractor(&entries[1]),
3847 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3848 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003849
3850 Ok(())
3851 }
3852
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003853 #[test]
3854 fn test_grant_ungrant() -> Result<()> {
3855 const CALLER_UID: u32 = 15;
3856 const GRANTEE_UID: u32 = 12;
3857 const SELINUX_NAMESPACE: i64 = 7;
3858
3859 let mut db = new_test_db()?;
3860 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003861 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3862 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3863 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003864 )?;
3865 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003866 domain: super::Domain::APP,
3867 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003868 alias: Some("key".to_string()),
3869 blob: None,
3870 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003871 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3872 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003873
3874 // Reset totally predictable random number generator in case we
3875 // are not the first test running on this thread.
3876 reset_random();
3877 let next_random = 0i64;
3878
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003879 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003880 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003881 assert_eq!(*a, PVEC1);
3882 assert_eq!(
3883 *k,
3884 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003885 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003886 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003887 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003888 alias: Some("key".to_string()),
3889 blob: None,
3890 }
3891 );
3892 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003893 })
3894 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003895
3896 assert_eq!(
3897 app_granted_key,
3898 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003899 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003900 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003901 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003902 alias: None,
3903 blob: None,
3904 }
3905 );
3906
3907 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003908 domain: super::Domain::SELINUX,
3909 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003910 alias: Some("yek".to_string()),
3911 blob: None,
3912 };
3913
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003914 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003915 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003916 assert_eq!(*a, PVEC1);
3917 assert_eq!(
3918 *k,
3919 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003920 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003921 // namespace must be the supplied SELinux
3922 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003923 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003924 alias: Some("yek".to_string()),
3925 blob: None,
3926 }
3927 );
3928 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003929 })
3930 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003931
3932 assert_eq!(
3933 selinux_granted_key,
3934 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003935 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003936 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003937 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003938 alias: None,
3939 blob: None,
3940 }
3941 );
3942
3943 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003944 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003945 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003946 assert_eq!(*a, PVEC2);
3947 assert_eq!(
3948 *k,
3949 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003950 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003951 // namespace must be the supplied SELinux
3952 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003953 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003954 alias: Some("yek".to_string()),
3955 blob: None,
3956 }
3957 );
3958 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003959 })
3960 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003961
3962 assert_eq!(
3963 selinux_granted_key,
3964 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003965 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003966 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003967 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003968 alias: None,
3969 blob: None,
3970 }
3971 );
3972
3973 {
3974 // Limiting scope of stmt, because it borrows db.
3975 let mut stmt = db
3976 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003977 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003978 let mut rows =
3979 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3980 Ok((
3981 row.get(0)?,
3982 row.get(1)?,
3983 row.get(2)?,
3984 KeyPermSet::from(row.get::<_, i32>(3)?),
3985 ))
3986 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003987
3988 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003989 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003990 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003991 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003992 assert!(rows.next().is_none());
3993 }
3994
3995 debug_dump_keyentry_table(&mut db)?;
3996 println!("app_key {:?}", app_key);
3997 println!("selinux_key {:?}", selinux_key);
3998
Janis Danisevskis66784c42021-01-27 08:40:25 -08003999 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
4000 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004001
4002 Ok(())
4003 }
4004
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004005 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004006 static TEST_CERT_BLOB: &[u8] = b"my test cert";
4007 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
4008
4009 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004010 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004011 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004012 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004013 let mut blob_metadata = BlobMetaData::new();
4014 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4015 db.set_blob(
4016 &key_id,
4017 SubComponentType::KEY_BLOB,
4018 Some(TEST_KEY_BLOB),
4019 Some(&blob_metadata),
4020 )?;
4021 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4022 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004023 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004024
4025 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004026 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004027 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004028 )?;
4029 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004030 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
4031 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004032 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004033 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004034 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004035 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004036 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004037 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004038 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004039
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004040 drop(rows);
4041 drop(stmt);
4042
4043 assert_eq!(
4044 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4045 BlobMetaData::load_from_db(id, tx).no_gc()
4046 })
4047 .expect("Should find blob metadata."),
4048 blob_metadata
4049 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004050 Ok(())
4051 }
4052
4053 static TEST_ALIAS: &str = "my super duper key";
4054
4055 #[test]
4056 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
4057 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004058 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004059 .context("test_insert_and_load_full_keyentry_domain_app")?
4060 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004061 let (_key_guard, key_entry) = db
4062 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004063 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004064 domain: Domain::APP,
4065 nspace: 0,
4066 alias: Some(TEST_ALIAS.to_string()),
4067 blob: None,
4068 },
4069 KeyType::Client,
4070 KeyEntryLoadBits::BOTH,
4071 1,
4072 |_k, _av| Ok(()),
4073 )
4074 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004075 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004076
4077 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004078 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004079 domain: Domain::APP,
4080 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004081 alias: Some(TEST_ALIAS.to_string()),
4082 blob: None,
4083 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004084 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004085 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004086 |_, _| Ok(()),
4087 )
4088 .unwrap();
4089
4090 assert_eq!(
4091 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4092 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004093 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004094 domain: Domain::APP,
4095 nspace: 0,
4096 alias: Some(TEST_ALIAS.to_string()),
4097 blob: None,
4098 },
4099 KeyType::Client,
4100 KeyEntryLoadBits::NONE,
4101 1,
4102 |_k, _av| Ok(()),
4103 )
4104 .unwrap_err()
4105 .root_cause()
4106 .downcast_ref::<KsError>()
4107 );
4108
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004109 Ok(())
4110 }
4111
4112 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004113 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4114 let mut db = new_test_db()?;
4115
4116 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004117 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004118 domain: Domain::APP,
4119 nspace: 1,
4120 alias: Some(TEST_ALIAS.to_string()),
4121 blob: None,
4122 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004123 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004124 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004125 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004126 )
4127 .expect("Trying to insert cert.");
4128
4129 let (_key_guard, mut key_entry) = db
4130 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004131 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004132 domain: Domain::APP,
4133 nspace: 1,
4134 alias: Some(TEST_ALIAS.to_string()),
4135 blob: None,
4136 },
4137 KeyType::Client,
4138 KeyEntryLoadBits::PUBLIC,
4139 1,
4140 |_k, _av| Ok(()),
4141 )
4142 .expect("Trying to read certificate entry.");
4143
4144 assert!(key_entry.pure_cert());
4145 assert!(key_entry.cert().is_none());
4146 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4147
4148 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004149 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004150 domain: Domain::APP,
4151 nspace: 1,
4152 alias: Some(TEST_ALIAS.to_string()),
4153 blob: None,
4154 },
4155 KeyType::Client,
4156 1,
4157 |_, _| Ok(()),
4158 )
4159 .unwrap();
4160
4161 assert_eq!(
4162 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4163 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004164 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004165 domain: Domain::APP,
4166 nspace: 1,
4167 alias: Some(TEST_ALIAS.to_string()),
4168 blob: None,
4169 },
4170 KeyType::Client,
4171 KeyEntryLoadBits::NONE,
4172 1,
4173 |_k, _av| Ok(()),
4174 )
4175 .unwrap_err()
4176 .root_cause()
4177 .downcast_ref::<KsError>()
4178 );
4179
4180 Ok(())
4181 }
4182
4183 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004184 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4185 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004186 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004187 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4188 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004189 let (_key_guard, key_entry) = db
4190 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004191 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004192 domain: Domain::SELINUX,
4193 nspace: 1,
4194 alias: Some(TEST_ALIAS.to_string()),
4195 blob: None,
4196 },
4197 KeyType::Client,
4198 KeyEntryLoadBits::BOTH,
4199 1,
4200 |_k, _av| Ok(()),
4201 )
4202 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004203 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004204
4205 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004206 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004207 domain: Domain::SELINUX,
4208 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004209 alias: Some(TEST_ALIAS.to_string()),
4210 blob: None,
4211 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004212 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004213 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004214 |_, _| Ok(()),
4215 )
4216 .unwrap();
4217
4218 assert_eq!(
4219 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4220 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004221 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004222 domain: Domain::SELINUX,
4223 nspace: 1,
4224 alias: Some(TEST_ALIAS.to_string()),
4225 blob: None,
4226 },
4227 KeyType::Client,
4228 KeyEntryLoadBits::NONE,
4229 1,
4230 |_k, _av| Ok(()),
4231 )
4232 .unwrap_err()
4233 .root_cause()
4234 .downcast_ref::<KsError>()
4235 );
4236
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004237 Ok(())
4238 }
4239
4240 #[test]
4241 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4242 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004243 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004244 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4245 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004246 let (_, key_entry) = db
4247 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004248 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004249 KeyType::Client,
4250 KeyEntryLoadBits::BOTH,
4251 1,
4252 |_k, _av| Ok(()),
4253 )
4254 .unwrap();
4255
Qi Wub9433b52020-12-01 14:52:46 +08004256 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004257
4258 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004259 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004260 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004261 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004262 |_, _| Ok(()),
4263 )
4264 .unwrap();
4265
4266 assert_eq!(
4267 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4268 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004269 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004270 KeyType::Client,
4271 KeyEntryLoadBits::NONE,
4272 1,
4273 |_k, _av| Ok(()),
4274 )
4275 .unwrap_err()
4276 .root_cause()
4277 .downcast_ref::<KsError>()
4278 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004279
4280 Ok(())
4281 }
4282
4283 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004284 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4285 let mut db = new_test_db()?;
4286 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4287 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4288 .0;
4289 // Update the usage count of the limited use key.
4290 db.check_and_update_key_usage_count(key_id)?;
4291
4292 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004293 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004294 KeyType::Client,
4295 KeyEntryLoadBits::BOTH,
4296 1,
4297 |_k, _av| Ok(()),
4298 )?;
4299
4300 // The usage count is decremented now.
4301 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4302
4303 Ok(())
4304 }
4305
4306 #[test]
4307 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4308 let mut db = new_test_db()?;
4309 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4310 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4311 .0;
4312 // Update the usage count of the limited use key.
4313 db.check_and_update_key_usage_count(key_id).expect(concat!(
4314 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4315 "This should succeed."
4316 ));
4317
4318 // Try to update the exhausted limited use key.
4319 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4320 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4321 "This should fail."
4322 ));
4323 assert_eq!(
4324 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4325 e.root_cause().downcast_ref::<KsError>().unwrap()
4326 );
4327
4328 Ok(())
4329 }
4330
4331 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004332 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4333 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004334 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004335 .context("test_insert_and_load_full_keyentry_from_grant")?
4336 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004337
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004338 let granted_key = db
4339 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004340 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004341 domain: Domain::APP,
4342 nspace: 0,
4343 alias: Some(TEST_ALIAS.to_string()),
4344 blob: None,
4345 },
4346 1,
4347 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004348 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004349 |_k, _av| Ok(()),
4350 )
4351 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004352
4353 debug_dump_grant_table(&mut db)?;
4354
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004355 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004356 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4357 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004358 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08004359 Ok(())
4360 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004361 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004362
Qi Wub9433b52020-12-01 14:52:46 +08004363 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004364
Janis Danisevskis66784c42021-01-27 08:40:25 -08004365 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004366
4367 assert_eq!(
4368 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4369 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004370 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004371 KeyType::Client,
4372 KeyEntryLoadBits::NONE,
4373 2,
4374 |_k, _av| Ok(()),
4375 )
4376 .unwrap_err()
4377 .root_cause()
4378 .downcast_ref::<KsError>()
4379 );
4380
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004381 Ok(())
4382 }
4383
Janis Danisevskis45760022021-01-19 16:34:10 -08004384 // This test attempts to load a key by key id while the caller is not the owner
4385 // but a grant exists for the given key and the caller.
4386 #[test]
4387 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4388 let mut db = new_test_db()?;
4389 const OWNER_UID: u32 = 1u32;
4390 const GRANTEE_UID: u32 = 2u32;
4391 const SOMEONE_ELSE_UID: u32 = 3u32;
4392 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4393 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4394 .0;
4395
4396 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004397 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004398 domain: Domain::APP,
4399 nspace: 0,
4400 alias: Some(TEST_ALIAS.to_string()),
4401 blob: None,
4402 },
4403 OWNER_UID,
4404 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004405 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08004406 |_k, _av| Ok(()),
4407 )
4408 .unwrap();
4409
4410 debug_dump_grant_table(&mut db)?;
4411
4412 let id_descriptor =
4413 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4414
4415 let (_, key_entry) = db
4416 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004417 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004418 KeyType::Client,
4419 KeyEntryLoadBits::BOTH,
4420 GRANTEE_UID,
4421 |k, av| {
4422 assert_eq!(Domain::APP, k.domain);
4423 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004424 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08004425 Ok(())
4426 },
4427 )
4428 .unwrap();
4429
4430 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4431
4432 let (_, key_entry) = db
4433 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004434 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004435 KeyType::Client,
4436 KeyEntryLoadBits::BOTH,
4437 SOMEONE_ELSE_UID,
4438 |k, av| {
4439 assert_eq!(Domain::APP, k.domain);
4440 assert_eq!(OWNER_UID as i64, k.nspace);
4441 assert!(av.is_none());
4442 Ok(())
4443 },
4444 )
4445 .unwrap();
4446
4447 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4448
Janis Danisevskis66784c42021-01-27 08:40:25 -08004449 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004450
4451 assert_eq!(
4452 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4453 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004454 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004455 KeyType::Client,
4456 KeyEntryLoadBits::NONE,
4457 GRANTEE_UID,
4458 |_k, _av| Ok(()),
4459 )
4460 .unwrap_err()
4461 .root_cause()
4462 .downcast_ref::<KsError>()
4463 );
4464
4465 Ok(())
4466 }
4467
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004468 // Creates a key migrates it to a different location and then tries to access it by the old
4469 // and new location.
4470 #[test]
4471 fn test_migrate_key_app_to_app() -> Result<()> {
4472 let mut db = new_test_db()?;
4473 const SOURCE_UID: u32 = 1u32;
4474 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004475 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4476 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004477 let key_id_guard =
4478 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4479 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4480
4481 let source_descriptor: KeyDescriptor = KeyDescriptor {
4482 domain: Domain::APP,
4483 nspace: -1,
4484 alias: Some(SOURCE_ALIAS.to_string()),
4485 blob: None,
4486 };
4487
4488 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4489 domain: Domain::APP,
4490 nspace: -1,
4491 alias: Some(DESTINATION_ALIAS.to_string()),
4492 blob: None,
4493 };
4494
4495 let key_id = key_id_guard.id();
4496
4497 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4498 Ok(())
4499 })
4500 .unwrap();
4501
4502 let (_, key_entry) = db
4503 .load_key_entry(
4504 &destination_descriptor,
4505 KeyType::Client,
4506 KeyEntryLoadBits::BOTH,
4507 DESTINATION_UID,
4508 |k, av| {
4509 assert_eq!(Domain::APP, k.domain);
4510 assert_eq!(DESTINATION_UID as i64, k.nspace);
4511 assert!(av.is_none());
4512 Ok(())
4513 },
4514 )
4515 .unwrap();
4516
4517 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4518
4519 assert_eq!(
4520 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4521 db.load_key_entry(
4522 &source_descriptor,
4523 KeyType::Client,
4524 KeyEntryLoadBits::NONE,
4525 SOURCE_UID,
4526 |_k, _av| Ok(()),
4527 )
4528 .unwrap_err()
4529 .root_cause()
4530 .downcast_ref::<KsError>()
4531 );
4532
4533 Ok(())
4534 }
4535
4536 // Creates a key migrates it to a different location and then tries to access it by the old
4537 // and new location.
4538 #[test]
4539 fn test_migrate_key_app_to_selinux() -> Result<()> {
4540 let mut db = new_test_db()?;
4541 const SOURCE_UID: u32 = 1u32;
4542 const DESTINATION_UID: u32 = 2u32;
4543 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004544 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4545 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004546 let key_id_guard =
4547 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4548 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4549
4550 let source_descriptor: KeyDescriptor = KeyDescriptor {
4551 domain: Domain::APP,
4552 nspace: -1,
4553 alias: Some(SOURCE_ALIAS.to_string()),
4554 blob: None,
4555 };
4556
4557 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4558 domain: Domain::SELINUX,
4559 nspace: DESTINATION_NAMESPACE,
4560 alias: Some(DESTINATION_ALIAS.to_string()),
4561 blob: None,
4562 };
4563
4564 let key_id = key_id_guard.id();
4565
4566 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4567 Ok(())
4568 })
4569 .unwrap();
4570
4571 let (_, key_entry) = db
4572 .load_key_entry(
4573 &destination_descriptor,
4574 KeyType::Client,
4575 KeyEntryLoadBits::BOTH,
4576 DESTINATION_UID,
4577 |k, av| {
4578 assert_eq!(Domain::SELINUX, k.domain);
4579 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4580 assert!(av.is_none());
4581 Ok(())
4582 },
4583 )
4584 .unwrap();
4585
4586 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4587
4588 assert_eq!(
4589 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4590 db.load_key_entry(
4591 &source_descriptor,
4592 KeyType::Client,
4593 KeyEntryLoadBits::NONE,
4594 SOURCE_UID,
4595 |_k, _av| Ok(()),
4596 )
4597 .unwrap_err()
4598 .root_cause()
4599 .downcast_ref::<KsError>()
4600 );
4601
4602 Ok(())
4603 }
4604
4605 // Creates two keys and tries to migrate the first to the location of the second which
4606 // is expected to fail.
4607 #[test]
4608 fn test_migrate_key_destination_occupied() -> Result<()> {
4609 let mut db = new_test_db()?;
4610 const SOURCE_UID: u32 = 1u32;
4611 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004612 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4613 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004614 let key_id_guard =
4615 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4616 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4617 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4618 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4619
4620 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4621 domain: Domain::APP,
4622 nspace: -1,
4623 alias: Some(DESTINATION_ALIAS.to_string()),
4624 blob: None,
4625 };
4626
4627 assert_eq!(
4628 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4629 db.migrate_key_namespace(
4630 key_id_guard,
4631 &destination_descriptor,
4632 DESTINATION_UID,
4633 |_k| Ok(())
4634 )
4635 .unwrap_err()
4636 .root_cause()
4637 .downcast_ref::<KsError>()
4638 );
4639
4640 Ok(())
4641 }
4642
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004643 #[test]
4644 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004645 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4646 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4647 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004648 const UID: u32 = 33;
4649 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4650 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4651 let key_id_untouched1 =
4652 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4653 let key_id_untouched2 =
4654 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4655 let key_id_deleted =
4656 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4657
4658 let (_, key_entry) = db
4659 .load_key_entry(
4660 &KeyDescriptor {
4661 domain: Domain::APP,
4662 nspace: -1,
4663 alias: Some(ALIAS1.to_string()),
4664 blob: None,
4665 },
4666 KeyType::Client,
4667 KeyEntryLoadBits::BOTH,
4668 UID,
4669 |k, av| {
4670 assert_eq!(Domain::APP, k.domain);
4671 assert_eq!(UID as i64, k.nspace);
4672 assert!(av.is_none());
4673 Ok(())
4674 },
4675 )
4676 .unwrap();
4677 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4678 let (_, key_entry) = db
4679 .load_key_entry(
4680 &KeyDescriptor {
4681 domain: Domain::APP,
4682 nspace: -1,
4683 alias: Some(ALIAS2.to_string()),
4684 blob: None,
4685 },
4686 KeyType::Client,
4687 KeyEntryLoadBits::BOTH,
4688 UID,
4689 |k, av| {
4690 assert_eq!(Domain::APP, k.domain);
4691 assert_eq!(UID as i64, k.nspace);
4692 assert!(av.is_none());
4693 Ok(())
4694 },
4695 )
4696 .unwrap();
4697 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4698 let (_, key_entry) = db
4699 .load_key_entry(
4700 &KeyDescriptor {
4701 domain: Domain::APP,
4702 nspace: -1,
4703 alias: Some(ALIAS3.to_string()),
4704 blob: None,
4705 },
4706 KeyType::Client,
4707 KeyEntryLoadBits::BOTH,
4708 UID,
4709 |k, av| {
4710 assert_eq!(Domain::APP, k.domain);
4711 assert_eq!(UID as i64, k.nspace);
4712 assert!(av.is_none());
4713 Ok(())
4714 },
4715 )
4716 .unwrap();
4717 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4718
4719 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4720 KeystoreDB::from_0_to_1(tx).no_gc()
4721 })
4722 .unwrap();
4723
4724 let (_, key_entry) = db
4725 .load_key_entry(
4726 &KeyDescriptor {
4727 domain: Domain::APP,
4728 nspace: -1,
4729 alias: Some(ALIAS1.to_string()),
4730 blob: None,
4731 },
4732 KeyType::Client,
4733 KeyEntryLoadBits::BOTH,
4734 UID,
4735 |k, av| {
4736 assert_eq!(Domain::APP, k.domain);
4737 assert_eq!(UID as i64, k.nspace);
4738 assert!(av.is_none());
4739 Ok(())
4740 },
4741 )
4742 .unwrap();
4743 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4744 let (_, key_entry) = db
4745 .load_key_entry(
4746 &KeyDescriptor {
4747 domain: Domain::APP,
4748 nspace: -1,
4749 alias: Some(ALIAS2.to_string()),
4750 blob: None,
4751 },
4752 KeyType::Client,
4753 KeyEntryLoadBits::BOTH,
4754 UID,
4755 |k, av| {
4756 assert_eq!(Domain::APP, k.domain);
4757 assert_eq!(UID as i64, k.nspace);
4758 assert!(av.is_none());
4759 Ok(())
4760 },
4761 )
4762 .unwrap();
4763 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4764 assert_eq!(
4765 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4766 db.load_key_entry(
4767 &KeyDescriptor {
4768 domain: Domain::APP,
4769 nspace: -1,
4770 alias: Some(ALIAS3.to_string()),
4771 blob: None,
4772 },
4773 KeyType::Client,
4774 KeyEntryLoadBits::BOTH,
4775 UID,
4776 |k, av| {
4777 assert_eq!(Domain::APP, k.domain);
4778 assert_eq!(UID as i64, k.nspace);
4779 assert!(av.is_none());
4780 Ok(())
4781 },
4782 )
4783 .unwrap_err()
4784 .root_cause()
4785 .downcast_ref::<KsError>()
4786 );
4787 }
4788
Janis Danisevskisaec14592020-11-12 09:41:49 -08004789 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4790
Janis Danisevskisaec14592020-11-12 09:41:49 -08004791 #[test]
4792 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4793 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004794 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4795 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004796 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004797 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004798 .context("test_insert_and_load_full_keyentry_domain_app")?
4799 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004800 let (_key_guard, key_entry) = db
4801 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004802 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004803 domain: Domain::APP,
4804 nspace: 0,
4805 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4806 blob: None,
4807 },
4808 KeyType::Client,
4809 KeyEntryLoadBits::BOTH,
4810 33,
4811 |_k, _av| Ok(()),
4812 )
4813 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004814 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004815 let state = Arc::new(AtomicU8::new(1));
4816 let state2 = state.clone();
4817
4818 // Spawning a second thread that attempts to acquire the key id lock
4819 // for the same key as the primary thread. The primary thread then
4820 // waits, thereby forcing the secondary thread into the second stage
4821 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4822 // The test succeeds if the secondary thread observes the transition
4823 // of `state` from 1 to 2, despite having a whole second to overtake
4824 // the primary thread.
4825 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004826 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004827 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004828 assert!(db
4829 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004830 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004831 domain: Domain::APP,
4832 nspace: 0,
4833 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4834 blob: None,
4835 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004836 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004837 KeyEntryLoadBits::BOTH,
4838 33,
4839 |_k, _av| Ok(()),
4840 )
4841 .is_ok());
4842 // We should only see a 2 here because we can only return
4843 // from load_key_entry when the `_key_guard` expires,
4844 // which happens at the end of the scope.
4845 assert_eq!(2, state2.load(Ordering::Relaxed));
4846 });
4847
4848 thread::sleep(std::time::Duration::from_millis(1000));
4849
4850 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4851
4852 // Return the handle from this scope so we can join with the
4853 // secondary thread after the key id lock has expired.
4854 handle
4855 // This is where the `_key_guard` goes out of scope,
4856 // which is the reason for concurrent load_key_entry on the same key
4857 // to unblock.
4858 };
4859 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4860 // main test thread. We will not see failing asserts in secondary threads otherwise.
4861 handle.join().unwrap();
4862 Ok(())
4863 }
4864
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004865 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004866 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004867 let temp_dir =
4868 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4869
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004870 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4871 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004872
4873 let _tx1 = db1
4874 .conn
4875 .transaction_with_behavior(TransactionBehavior::Immediate)
4876 .expect("Failed to create first transaction.");
4877
4878 let error = db2
4879 .conn
4880 .transaction_with_behavior(TransactionBehavior::Immediate)
4881 .context("Transaction begin failed.")
4882 .expect_err("This should fail.");
4883 let root_cause = error.root_cause();
4884 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4885 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4886 {
4887 return;
4888 }
4889 panic!(
4890 "Unexpected error {:?} \n{:?} \n{:?}",
4891 error,
4892 root_cause,
4893 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4894 )
4895 }
4896
4897 #[cfg(disabled)]
4898 #[test]
4899 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4900 let temp_dir = Arc::new(
4901 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4902 .expect("Failed to create temp dir."),
4903 );
4904
4905 let test_begin = Instant::now();
4906
Janis Danisevskis66784c42021-01-27 08:40:25 -08004907 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004908 let mut db =
4909 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004910 const OPEN_DB_COUNT: u32 = 50u32;
4911
4912 let mut actual_key_count = KEY_COUNT;
4913 // First insert KEY_COUNT keys.
4914 for count in 0..KEY_COUNT {
4915 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4916 actual_key_count = count;
4917 break;
4918 }
4919 let alias = format!("test_alias_{}", count);
4920 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4921 .expect("Failed to make key entry.");
4922 }
4923
4924 // Insert more keys from a different thread and into a different namespace.
4925 let temp_dir1 = temp_dir.clone();
4926 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004927 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4928 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004929
4930 for count in 0..actual_key_count {
4931 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4932 return;
4933 }
4934 let alias = format!("test_alias_{}", count);
4935 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4936 .expect("Failed to make key entry.");
4937 }
4938
4939 // then unbind them again.
4940 for count in 0..actual_key_count {
4941 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4942 return;
4943 }
4944 let key = KeyDescriptor {
4945 domain: Domain::APP,
4946 nspace: -1,
4947 alias: Some(format!("test_alias_{}", count)),
4948 blob: None,
4949 };
4950 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4951 }
4952 });
4953
4954 // And start unbinding the first set of keys.
4955 let temp_dir2 = temp_dir.clone();
4956 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004957 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4958 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004959
4960 for count in 0..actual_key_count {
4961 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4962 return;
4963 }
4964 let key = KeyDescriptor {
4965 domain: Domain::APP,
4966 nspace: -1,
4967 alias: Some(format!("test_alias_{}", count)),
4968 blob: None,
4969 };
4970 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4971 }
4972 });
4973
Janis Danisevskis66784c42021-01-27 08:40:25 -08004974 // While a lot of inserting and deleting is going on we have to open database connections
4975 // successfully and use them.
4976 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4977 // out of scope.
4978 #[allow(clippy::redundant_clone)]
4979 let temp_dir4 = temp_dir.clone();
4980 let handle4 = thread::spawn(move || {
4981 for count in 0..OPEN_DB_COUNT {
4982 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4983 return;
4984 }
Seth Moore444b51a2021-06-11 09:49:49 -07004985 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4986 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004987
4988 let alias = format!("test_alias_{}", count);
4989 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4990 .expect("Failed to make key entry.");
4991 let key = KeyDescriptor {
4992 domain: Domain::APP,
4993 nspace: -1,
4994 alias: Some(alias),
4995 blob: None,
4996 };
4997 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4998 }
4999 });
5000
5001 handle1.join().expect("Thread 1 panicked.");
5002 handle2.join().expect("Thread 2 panicked.");
5003 handle4.join().expect("Thread 4 panicked.");
5004
Janis Danisevskis66784c42021-01-27 08:40:25 -08005005 Ok(())
5006 }
5007
5008 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005009 fn list() -> Result<()> {
5010 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005011 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005012 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
5013 (Domain::APP, 1, "test1"),
5014 (Domain::APP, 1, "test2"),
5015 (Domain::APP, 1, "test3"),
5016 (Domain::APP, 1, "test4"),
5017 (Domain::APP, 1, "test5"),
5018 (Domain::APP, 1, "test6"),
5019 (Domain::APP, 1, "test7"),
5020 (Domain::APP, 2, "test1"),
5021 (Domain::APP, 2, "test2"),
5022 (Domain::APP, 2, "test3"),
5023 (Domain::APP, 2, "test4"),
5024 (Domain::APP, 2, "test5"),
5025 (Domain::APP, 2, "test6"),
5026 (Domain::APP, 2, "test8"),
5027 (Domain::SELINUX, 100, "test1"),
5028 (Domain::SELINUX, 100, "test2"),
5029 (Domain::SELINUX, 100, "test3"),
5030 (Domain::SELINUX, 100, "test4"),
5031 (Domain::SELINUX, 100, "test5"),
5032 (Domain::SELINUX, 100, "test6"),
5033 (Domain::SELINUX, 100, "test9"),
5034 ];
5035
5036 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
5037 .iter()
5038 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08005039 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
5040 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005041 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
5042 });
5043 (entry.id(), *ns)
5044 })
5045 .collect();
5046
5047 for (domain, namespace) in
5048 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
5049 {
5050 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
5051 .iter()
5052 .filter_map(|(domain, ns, alias)| match ns {
5053 ns if *ns == *namespace => Some(KeyDescriptor {
5054 domain: *domain,
5055 nspace: *ns,
5056 alias: Some(alias.to_string()),
5057 blob: None,
5058 }),
5059 _ => None,
5060 })
5061 .collect();
5062 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07005063 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005064 list_result.sort();
5065 assert_eq!(list_o_descriptors, list_result);
5066
5067 let mut list_o_ids: Vec<i64> = list_o_descriptors
5068 .into_iter()
5069 .map(|d| {
5070 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005071 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08005072 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005073 KeyType::Client,
5074 KeyEntryLoadBits::NONE,
5075 *namespace as u32,
5076 |_, _| Ok(()),
5077 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005078 .unwrap();
5079 entry.id()
5080 })
5081 .collect();
5082 list_o_ids.sort_unstable();
5083 let mut loaded_entries: Vec<i64> = list_o_keys
5084 .iter()
5085 .filter_map(|(id, ns)| match ns {
5086 ns if *ns == *namespace => Some(*id),
5087 _ => None,
5088 })
5089 .collect();
5090 loaded_entries.sort_unstable();
5091 assert_eq!(list_o_ids, loaded_entries);
5092 }
Janis Danisevskis18313832021-05-17 13:30:32 -07005093 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005094
5095 Ok(())
5096 }
5097
Joel Galenson0891bc12020-07-20 10:37:03 -07005098 // Helpers
5099
5100 // Checks that the given result is an error containing the given string.
5101 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
5102 let error_str = format!(
5103 "{:#?}",
5104 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
5105 );
5106 assert!(
5107 error_str.contains(target),
5108 "The string \"{}\" should contain \"{}\"",
5109 error_str,
5110 target
5111 );
5112 }
5113
Joel Galenson2aab4432020-07-22 15:27:57 -07005114 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07005115 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005116 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005117 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005118 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005119 namespace: Option<i64>,
5120 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005121 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08005122 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005123 }
5124
5125 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
5126 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07005127 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07005128 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07005129 Ok(KeyEntryRow {
5130 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005131 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07005132 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07005133 namespace: row.get(3)?,
5134 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005135 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08005136 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07005137 })
5138 })?
5139 .map(|r| r.context("Could not read keyentry row."))
5140 .collect::<Result<Vec<_>>>()
5141 }
5142
Max Biresb2e1d032021-02-08 21:35:05 -08005143 struct RemoteProvValues {
5144 cert_chain: Vec<u8>,
5145 priv_key: Vec<u8>,
5146 batch_cert: Vec<u8>,
5147 }
5148
Max Bires2b2e6562020-09-22 11:22:36 -07005149 fn load_attestation_key_pool(
5150 db: &mut KeystoreDB,
5151 expiration_date: i64,
5152 namespace: i64,
5153 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08005154 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07005155 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
5156 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
5157 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5158 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005159 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005160 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5161 db.store_signed_attestation_certificate_chain(
5162 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005163 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005164 &cert_chain,
5165 expiration_date,
5166 &KEYSTORE_UUID,
5167 )?;
5168 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005169 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005170 }
5171
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005172 // Note: The parameters and SecurityLevel associations are nonsensical. This
5173 // collection is only used to check if the parameters are preserved as expected by the
5174 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005175 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5176 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005177 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5178 KeyParameter::new(
5179 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5180 SecurityLevel::TRUSTED_ENVIRONMENT,
5181 ),
5182 KeyParameter::new(
5183 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5184 SecurityLevel::TRUSTED_ENVIRONMENT,
5185 ),
5186 KeyParameter::new(
5187 KeyParameterValue::Algorithm(Algorithm::RSA),
5188 SecurityLevel::TRUSTED_ENVIRONMENT,
5189 ),
5190 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5191 KeyParameter::new(
5192 KeyParameterValue::BlockMode(BlockMode::ECB),
5193 SecurityLevel::TRUSTED_ENVIRONMENT,
5194 ),
5195 KeyParameter::new(
5196 KeyParameterValue::BlockMode(BlockMode::GCM),
5197 SecurityLevel::TRUSTED_ENVIRONMENT,
5198 ),
5199 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5200 KeyParameter::new(
5201 KeyParameterValue::Digest(Digest::MD5),
5202 SecurityLevel::TRUSTED_ENVIRONMENT,
5203 ),
5204 KeyParameter::new(
5205 KeyParameterValue::Digest(Digest::SHA_2_224),
5206 SecurityLevel::TRUSTED_ENVIRONMENT,
5207 ),
5208 KeyParameter::new(
5209 KeyParameterValue::Digest(Digest::SHA_2_256),
5210 SecurityLevel::STRONGBOX,
5211 ),
5212 KeyParameter::new(
5213 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5214 SecurityLevel::TRUSTED_ENVIRONMENT,
5215 ),
5216 KeyParameter::new(
5217 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5218 SecurityLevel::TRUSTED_ENVIRONMENT,
5219 ),
5220 KeyParameter::new(
5221 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5222 SecurityLevel::STRONGBOX,
5223 ),
5224 KeyParameter::new(
5225 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5226 SecurityLevel::TRUSTED_ENVIRONMENT,
5227 ),
5228 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5229 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5230 KeyParameter::new(
5231 KeyParameterValue::EcCurve(EcCurve::P_224),
5232 SecurityLevel::TRUSTED_ENVIRONMENT,
5233 ),
5234 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5235 KeyParameter::new(
5236 KeyParameterValue::EcCurve(EcCurve::P_384),
5237 SecurityLevel::TRUSTED_ENVIRONMENT,
5238 ),
5239 KeyParameter::new(
5240 KeyParameterValue::EcCurve(EcCurve::P_521),
5241 SecurityLevel::TRUSTED_ENVIRONMENT,
5242 ),
5243 KeyParameter::new(
5244 KeyParameterValue::RSAPublicExponent(3),
5245 SecurityLevel::TRUSTED_ENVIRONMENT,
5246 ),
5247 KeyParameter::new(
5248 KeyParameterValue::IncludeUniqueID,
5249 SecurityLevel::TRUSTED_ENVIRONMENT,
5250 ),
5251 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5252 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5253 KeyParameter::new(
5254 KeyParameterValue::ActiveDateTime(1234567890),
5255 SecurityLevel::STRONGBOX,
5256 ),
5257 KeyParameter::new(
5258 KeyParameterValue::OriginationExpireDateTime(1234567890),
5259 SecurityLevel::TRUSTED_ENVIRONMENT,
5260 ),
5261 KeyParameter::new(
5262 KeyParameterValue::UsageExpireDateTime(1234567890),
5263 SecurityLevel::TRUSTED_ENVIRONMENT,
5264 ),
5265 KeyParameter::new(
5266 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5267 SecurityLevel::TRUSTED_ENVIRONMENT,
5268 ),
5269 KeyParameter::new(
5270 KeyParameterValue::MaxUsesPerBoot(1234567890),
5271 SecurityLevel::TRUSTED_ENVIRONMENT,
5272 ),
5273 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5274 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5275 KeyParameter::new(
5276 KeyParameterValue::NoAuthRequired,
5277 SecurityLevel::TRUSTED_ENVIRONMENT,
5278 ),
5279 KeyParameter::new(
5280 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5281 SecurityLevel::TRUSTED_ENVIRONMENT,
5282 ),
5283 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5284 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5285 KeyParameter::new(
5286 KeyParameterValue::TrustedUserPresenceRequired,
5287 SecurityLevel::TRUSTED_ENVIRONMENT,
5288 ),
5289 KeyParameter::new(
5290 KeyParameterValue::TrustedConfirmationRequired,
5291 SecurityLevel::TRUSTED_ENVIRONMENT,
5292 ),
5293 KeyParameter::new(
5294 KeyParameterValue::UnlockedDeviceRequired,
5295 SecurityLevel::TRUSTED_ENVIRONMENT,
5296 ),
5297 KeyParameter::new(
5298 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5299 SecurityLevel::SOFTWARE,
5300 ),
5301 KeyParameter::new(
5302 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5303 SecurityLevel::SOFTWARE,
5304 ),
5305 KeyParameter::new(
5306 KeyParameterValue::CreationDateTime(12345677890),
5307 SecurityLevel::SOFTWARE,
5308 ),
5309 KeyParameter::new(
5310 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5311 SecurityLevel::TRUSTED_ENVIRONMENT,
5312 ),
5313 KeyParameter::new(
5314 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5315 SecurityLevel::TRUSTED_ENVIRONMENT,
5316 ),
5317 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5318 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5319 KeyParameter::new(
5320 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5321 SecurityLevel::SOFTWARE,
5322 ),
5323 KeyParameter::new(
5324 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5325 SecurityLevel::TRUSTED_ENVIRONMENT,
5326 ),
5327 KeyParameter::new(
5328 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5329 SecurityLevel::TRUSTED_ENVIRONMENT,
5330 ),
5331 KeyParameter::new(
5332 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5333 SecurityLevel::TRUSTED_ENVIRONMENT,
5334 ),
5335 KeyParameter::new(
5336 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5337 SecurityLevel::TRUSTED_ENVIRONMENT,
5338 ),
5339 KeyParameter::new(
5340 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5341 SecurityLevel::TRUSTED_ENVIRONMENT,
5342 ),
5343 KeyParameter::new(
5344 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5345 SecurityLevel::TRUSTED_ENVIRONMENT,
5346 ),
5347 KeyParameter::new(
5348 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5349 SecurityLevel::TRUSTED_ENVIRONMENT,
5350 ),
5351 KeyParameter::new(
5352 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5353 SecurityLevel::TRUSTED_ENVIRONMENT,
5354 ),
5355 KeyParameter::new(
5356 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5357 SecurityLevel::TRUSTED_ENVIRONMENT,
5358 ),
5359 KeyParameter::new(
5360 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5361 SecurityLevel::TRUSTED_ENVIRONMENT,
5362 ),
5363 KeyParameter::new(
5364 KeyParameterValue::VendorPatchLevel(3),
5365 SecurityLevel::TRUSTED_ENVIRONMENT,
5366 ),
5367 KeyParameter::new(
5368 KeyParameterValue::BootPatchLevel(4),
5369 SecurityLevel::TRUSTED_ENVIRONMENT,
5370 ),
5371 KeyParameter::new(
5372 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5373 SecurityLevel::TRUSTED_ENVIRONMENT,
5374 ),
5375 KeyParameter::new(
5376 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5377 SecurityLevel::TRUSTED_ENVIRONMENT,
5378 ),
5379 KeyParameter::new(
5380 KeyParameterValue::MacLength(256),
5381 SecurityLevel::TRUSTED_ENVIRONMENT,
5382 ),
5383 KeyParameter::new(
5384 KeyParameterValue::ResetSinceIdRotation,
5385 SecurityLevel::TRUSTED_ENVIRONMENT,
5386 ),
5387 KeyParameter::new(
5388 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5389 SecurityLevel::TRUSTED_ENVIRONMENT,
5390 ),
Qi Wub9433b52020-12-01 14:52:46 +08005391 ];
5392 if let Some(value) = max_usage_count {
5393 params.push(KeyParameter::new(
5394 KeyParameterValue::UsageCountLimit(value),
5395 SecurityLevel::SOFTWARE,
5396 ));
5397 }
5398 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005399 }
5400
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005401 fn make_test_key_entry(
5402 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005403 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005404 namespace: i64,
5405 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005406 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005407 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005408 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005409 let mut blob_metadata = BlobMetaData::new();
5410 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5411 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5412 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5413 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5414 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5415
5416 db.set_blob(
5417 &key_id,
5418 SubComponentType::KEY_BLOB,
5419 Some(TEST_KEY_BLOB),
5420 Some(&blob_metadata),
5421 )?;
5422 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5423 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005424
5425 let params = make_test_params(max_usage_count);
5426 db.insert_keyparameter(&key_id, &params)?;
5427
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005428 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005429 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005430 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005431 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005432 Ok(key_id)
5433 }
5434
Qi Wub9433b52020-12-01 14:52:46 +08005435 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5436 let params = make_test_params(max_usage_count);
5437
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005438 let mut blob_metadata = BlobMetaData::new();
5439 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5440 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5441 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5442 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5443 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5444
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005445 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005446 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005447
5448 KeyEntry {
5449 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005450 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005451 cert: Some(TEST_CERT_BLOB.to_vec()),
5452 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005453 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005454 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005455 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005456 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005457 }
5458 }
5459
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005460 fn make_bootlevel_key_entry(
5461 db: &mut KeystoreDB,
5462 domain: Domain,
5463 namespace: i64,
5464 alias: &str,
5465 logical_only: bool,
5466 ) -> Result<KeyIdGuard> {
5467 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5468 let mut blob_metadata = BlobMetaData::new();
5469 if !logical_only {
5470 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5471 }
5472 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5473
5474 db.set_blob(
5475 &key_id,
5476 SubComponentType::KEY_BLOB,
5477 Some(TEST_KEY_BLOB),
5478 Some(&blob_metadata),
5479 )?;
5480 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5481 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5482
5483 let mut params = make_test_params(None);
5484 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5485
5486 db.insert_keyparameter(&key_id, &params)?;
5487
5488 let mut metadata = KeyMetaData::new();
5489 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5490 db.insert_key_metadata(&key_id, &metadata)?;
5491 rebind_alias(db, &key_id, alias, domain, namespace)?;
5492 Ok(key_id)
5493 }
5494
5495 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5496 let mut params = make_test_params(None);
5497 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5498
5499 let mut blob_metadata = BlobMetaData::new();
5500 if !logical_only {
5501 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5502 }
5503 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5504
5505 let mut metadata = KeyMetaData::new();
5506 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5507
5508 KeyEntry {
5509 id: key_id,
5510 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5511 cert: Some(TEST_CERT_BLOB.to_vec()),
5512 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5513 km_uuid: KEYSTORE_UUID,
5514 parameters: params,
5515 metadata,
5516 pure_cert: false,
5517 }
5518 }
5519
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005520 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005521 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005522 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005523 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005524 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005525 NO_PARAMS,
5526 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005527 Ok((
5528 row.get(0)?,
5529 row.get(1)?,
5530 row.get(2)?,
5531 row.get(3)?,
5532 row.get(4)?,
5533 row.get(5)?,
5534 row.get(6)?,
5535 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005536 },
5537 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005538
5539 println!("Key entry table rows:");
5540 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005541 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005542 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005543 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5544 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005545 );
5546 }
5547 Ok(())
5548 }
5549
5550 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005551 let mut stmt = db
5552 .conn
5553 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005554 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5555 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5556 })?;
5557
5558 println!("Grant table rows:");
5559 for r in rows {
5560 let (id, gt, ki, av) = r.unwrap();
5561 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5562 }
5563 Ok(())
5564 }
5565
Joel Galenson0891bc12020-07-20 10:37:03 -07005566 // Use a custom random number generator that repeats each number once.
5567 // This allows us to test repeated elements.
5568
5569 thread_local! {
5570 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5571 }
5572
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005573 fn reset_random() {
5574 RANDOM_COUNTER.with(|counter| {
5575 *counter.borrow_mut() = 0;
5576 })
5577 }
5578
Joel Galenson0891bc12020-07-20 10:37:03 -07005579 pub fn random() -> i64 {
5580 RANDOM_COUNTER.with(|counter| {
5581 let result = *counter.borrow() / 2;
5582 *counter.borrow_mut() += 1;
5583 result
5584 })
5585 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005586
5587 #[test]
5588 fn test_last_off_body() -> Result<()> {
5589 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005590 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005591 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005592 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005593 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005594 let one_second = Duration::from_secs(1);
5595 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005596 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005597 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005598 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005599 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005600 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005601 Ok(())
5602 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005603
5604 #[test]
5605 fn test_unbind_keys_for_user() -> Result<()> {
5606 let mut db = new_test_db()?;
5607 db.unbind_keys_for_user(1, false)?;
5608
5609 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5610 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5611 db.unbind_keys_for_user(2, false)?;
5612
Janis Danisevskis18313832021-05-17 13:30:32 -07005613 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5614 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005615
5616 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005617 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005618
5619 Ok(())
5620 }
5621
5622 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005623 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5624 let mut db = new_test_db()?;
5625 let super_key = keystore2_crypto::generate_aes256_key()?;
5626 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5627 let (encrypted_super_key, metadata) =
5628 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5629
5630 let key_name_enc = SuperKeyType {
5631 alias: "test_super_key_1",
5632 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5633 };
5634
5635 let key_name_nonenc = SuperKeyType {
5636 alias: "test_super_key_2",
5637 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5638 };
5639
5640 // Install two super keys.
5641 db.store_super_key(
5642 1,
5643 &key_name_nonenc,
5644 &super_key,
5645 &BlobMetaData::new(),
5646 &KeyMetaData::new(),
5647 )?;
5648 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5649
5650 // Check that both can be found in the database.
5651 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5652 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5653
5654 // Install the same keys for a different user.
5655 db.store_super_key(
5656 2,
5657 &key_name_nonenc,
5658 &super_key,
5659 &BlobMetaData::new(),
5660 &KeyMetaData::new(),
5661 )?;
5662 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5663
5664 // Check that the second pair of keys can be found in the database.
5665 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5666 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5667
5668 // Delete only encrypted keys.
5669 db.unbind_keys_for_user(1, true)?;
5670
5671 // The encrypted superkey should be gone now.
5672 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5673 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5674
5675 // Reinsert the encrypted key.
5676 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5677
5678 // Check that both can be found in the database, again..
5679 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5680 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5681
5682 // Delete all even unencrypted keys.
5683 db.unbind_keys_for_user(1, false)?;
5684
5685 // Both should be gone now.
5686 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5687 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5688
5689 // Check that the second pair of keys was untouched.
5690 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5691 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5692
5693 Ok(())
5694 }
5695
5696 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005697 fn test_store_super_key() -> Result<()> {
5698 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005699 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005700 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005701 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005702 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005703 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005704
5705 let (encrypted_super_key, metadata) =
5706 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005707 db.store_super_key(
5708 1,
5709 &USER_SUPER_KEY,
5710 &encrypted_super_key,
5711 &metadata,
5712 &KeyMetaData::new(),
5713 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005714
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005715 // Check if super key exists.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005716 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005717
Paul Crowley7a658392021-03-18 17:08:20 -07005718 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005719 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5720 USER_SUPER_KEY.algorithm,
5721 key_entry,
5722 &pw,
5723 None,
5724 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005725
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005726 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005727 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005728
Hasini Gunasingheda895552021-01-27 19:34:37 +00005729 Ok(())
5730 }
Seth Moore78c091f2021-04-09 21:38:30 +00005731
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005732 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005733 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005734 MetricsStorage::KEY_ENTRY,
5735 MetricsStorage::KEY_ENTRY_ID_INDEX,
5736 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5737 MetricsStorage::BLOB_ENTRY,
5738 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5739 MetricsStorage::KEY_PARAMETER,
5740 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5741 MetricsStorage::KEY_METADATA,
5742 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5743 MetricsStorage::GRANT,
5744 MetricsStorage::AUTH_TOKEN,
5745 MetricsStorage::BLOB_METADATA,
5746 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005747 ]
5748 }
5749
5750 /// Perform a simple check to ensure that we can query all the storage types
5751 /// that are supported by the DB. Check for reasonable values.
5752 #[test]
5753 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005754 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005755
5756 let mut db = new_test_db()?;
5757
5758 for t in get_valid_statsd_storage_types() {
5759 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005760 // AuthToken can be less than a page since it's in a btree, not sqlite
5761 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005762 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005763 } else {
5764 assert!(stat.size >= PAGE_SIZE);
5765 }
Seth Moore78c091f2021-04-09 21:38:30 +00005766 assert!(stat.size >= stat.unused_size);
5767 }
5768
5769 Ok(())
5770 }
5771
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005772 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005773 get_valid_statsd_storage_types()
5774 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005775 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005776 .collect()
5777 }
5778
5779 fn assert_storage_increased(
5780 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005781 increased_storage_types: Vec<MetricsStorage>,
5782 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005783 ) {
5784 for storage in increased_storage_types {
5785 // Verify the expected storage increased.
5786 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005787 let storage = storage;
5788 let old = &baseline[&storage.0];
5789 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005790 assert!(
5791 new.unused_size <= old.unused_size,
5792 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005793 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005794 new.unused_size,
5795 old.unused_size
5796 );
5797
5798 // Update the baseline with the new value so that it succeeds in the
5799 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005800 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005801 }
5802
5803 // Get an updated map of the storage and verify there were no unexpected changes.
5804 let updated_stats = get_storage_stats_map(db);
5805 assert_eq!(updated_stats.len(), baseline.len());
5806
5807 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005808 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005809 let mut s = String::new();
5810 for &k in map.keys() {
5811 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5812 .expect("string concat failed");
5813 }
5814 s
5815 };
5816
5817 assert!(
5818 updated_stats[&k].size == baseline[&k].size
5819 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5820 "updated_stats:\n{}\nbaseline:\n{}",
5821 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005822 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005823 );
5824 }
5825 }
5826
5827 #[test]
5828 fn test_verify_key_table_size_reporting() -> Result<()> {
5829 let mut db = new_test_db()?;
5830 let mut working_stats = get_storage_stats_map(&mut db);
5831
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005832 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005833 assert_storage_increased(
5834 &mut db,
5835 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005836 MetricsStorage::KEY_ENTRY,
5837 MetricsStorage::KEY_ENTRY_ID_INDEX,
5838 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005839 ],
5840 &mut working_stats,
5841 );
5842
5843 let mut blob_metadata = BlobMetaData::new();
5844 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5845 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5846 assert_storage_increased(
5847 &mut db,
5848 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005849 MetricsStorage::BLOB_ENTRY,
5850 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5851 MetricsStorage::BLOB_METADATA,
5852 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005853 ],
5854 &mut working_stats,
5855 );
5856
5857 let params = make_test_params(None);
5858 db.insert_keyparameter(&key_id, &params)?;
5859 assert_storage_increased(
5860 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005861 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005862 &mut working_stats,
5863 );
5864
5865 let mut metadata = KeyMetaData::new();
5866 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5867 db.insert_key_metadata(&key_id, &metadata)?;
5868 assert_storage_increased(
5869 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005870 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005871 &mut working_stats,
5872 );
5873
5874 let mut sum = 0;
5875 for stat in working_stats.values() {
5876 sum += stat.size;
5877 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005878 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005879 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5880
5881 Ok(())
5882 }
5883
5884 #[test]
5885 fn test_verify_auth_table_size_reporting() -> Result<()> {
5886 let mut db = new_test_db()?;
5887 let mut working_stats = get_storage_stats_map(&mut db);
5888 db.insert_auth_token(&HardwareAuthToken {
5889 challenge: 123,
5890 userId: 456,
5891 authenticatorId: 789,
5892 authenticatorType: kmhw_authenticator_type::ANY,
5893 timestamp: Timestamp { milliSeconds: 10 },
5894 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005895 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005896 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005897 Ok(())
5898 }
5899
5900 #[test]
5901 fn test_verify_grant_table_size_reporting() -> Result<()> {
5902 const OWNER: i64 = 1;
5903 let mut db = new_test_db()?;
5904 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5905
5906 let mut working_stats = get_storage_stats_map(&mut db);
5907 db.grant(
5908 &KeyDescriptor {
5909 domain: Domain::APP,
5910 nspace: 0,
5911 alias: Some(TEST_ALIAS.to_string()),
5912 blob: None,
5913 },
5914 OWNER as u32,
5915 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005916 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005917 |_, _| Ok(()),
5918 )?;
5919
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005920 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005921
5922 Ok(())
5923 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005924
5925 #[test]
5926 fn find_auth_token_entry_returns_latest() -> Result<()> {
5927 let mut db = new_test_db()?;
5928 db.insert_auth_token(&HardwareAuthToken {
5929 challenge: 123,
5930 userId: 456,
5931 authenticatorId: 789,
5932 authenticatorType: kmhw_authenticator_type::ANY,
5933 timestamp: Timestamp { milliSeconds: 10 },
5934 mac: b"mac0".to_vec(),
5935 });
5936 std::thread::sleep(std::time::Duration::from_millis(1));
5937 db.insert_auth_token(&HardwareAuthToken {
5938 challenge: 123,
5939 userId: 457,
5940 authenticatorId: 789,
5941 authenticatorType: kmhw_authenticator_type::ANY,
5942 timestamp: Timestamp { milliSeconds: 12 },
5943 mac: b"mac1".to_vec(),
5944 });
5945 std::thread::sleep(std::time::Duration::from_millis(1));
5946 db.insert_auth_token(&HardwareAuthToken {
5947 challenge: 123,
5948 userId: 458,
5949 authenticatorId: 789,
5950 authenticatorType: kmhw_authenticator_type::ANY,
5951 timestamp: Timestamp { milliSeconds: 3 },
5952 mac: b"mac2".to_vec(),
5953 });
5954 // All three entries are in the database
5955 assert_eq!(db.perboot.auth_tokens_len(), 3);
5956 // It selected the most recent timestamp
5957 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5958 Ok(())
5959 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005960
5961 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005962 fn test_load_key_descriptor() -> Result<()> {
5963 let mut db = new_test_db()?;
5964 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5965
5966 let key = db.load_key_descriptor(key_id)?.unwrap();
5967
5968 assert_eq!(key.domain, Domain::APP);
5969 assert_eq!(key.nspace, 1);
5970 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5971
5972 // No such id
5973 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5974 Ok(())
5975 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005976}