blob: 0081bb7305ca66c1e010f4c9c3ab97c0b31798a3 [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 Danisevskisb42fc182020-12-15 08:41:27 -080048use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080049use crate::key_parameter::{KeyParameter, Tag};
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000050use crate::metrics_store::log_rkp_error_stats;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070051use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000052use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080053use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070054 error::{Error as KsError, ErrorCode, ResponseCode},
55 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080056};
Janis Danisevskis030ba022021-05-26 11:15:30 -070057use crate::{gc::Gc, super_key::USER_SUPER_KEY};
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,
145 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
146 .context("Failed to read KeyMetaEntry.")?,
147 );
148 Ok(())
149 })
150 .context("In KeyMetaData::load_from_db.")?;
151
152 Ok(Self { data: metadata })
153 }
154
155 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
156 let mut stmt = tx
157 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000158 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800159 VALUES (?, ?, ?);",
160 )
161 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
162
163 let iter = self.data.iter();
164 for (tag, entry) in iter {
165 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
166 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
167 })?;
168 }
169 Ok(())
170 }
171}
172
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800173impl_metadata!(
174 /// A set of metadata for key blobs.
175 #[derive(Debug, Default, Eq, PartialEq)]
176 pub struct BlobMetaData;
177 /// A metadata entry for key blobs.
178 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
179 pub enum BlobMetaEntry {
180 /// If present, indicates that the blob is encrypted with another key or a key derived
181 /// from a password.
182 EncryptedBy(EncryptedBy) with accessor encrypted_by,
183 /// If the blob is password encrypted this field is set to the
184 /// salt used for the key derivation.
185 Salt(Vec<u8>) with accessor salt,
186 /// If the blob is encrypted, this field is set to the initialization vector.
187 Iv(Vec<u8>) with accessor iv,
188 /// If the blob is encrypted, this field holds the AEAD TAG.
189 AeadTag(Vec<u8>) with accessor aead_tag,
190 /// The uuid of the owning KeyMint instance.
191 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700192 /// If the key is ECDH encrypted, this is the ephemeral public key
193 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000194 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
195 /// of that key
196 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800197 // --- ADD NEW META DATA FIELDS HERE ---
198 // For backwards compatibility add new entries only to
199 // end of this list and above this comment.
200 };
201);
202
203impl BlobMetaData {
204 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
205 let mut stmt = tx
206 .prepare(
207 "SELECT tag, data from persistent.blobmetadata
208 WHERE blobentryid = ?;",
209 )
210 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
211
212 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
213
214 let mut rows =
215 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
216 db_utils::with_rows_extract_all(&mut rows, |row| {
217 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
218 metadata.insert(
219 db_tag,
220 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
221 .context("Failed to read BlobMetaEntry.")?,
222 );
223 Ok(())
224 })
225 .context("In BlobMetaData::load_from_db.")?;
226
227 Ok(Self { data: metadata })
228 }
229
230 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
231 let mut stmt = tx
232 .prepare(
233 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
234 VALUES (?, ?, ?);",
235 )
236 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
237
238 let iter = self.data.iter();
239 for (tag, entry) in iter {
240 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
241 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
242 })?;
243 }
244 Ok(())
245 }
246}
247
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800248/// Indicates the type of the keyentry.
249#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
250pub enum KeyType {
251 /// This is a client key type. These keys are created or imported through the Keystore 2.0
252 /// AIDL interface android.system.keystore2.
253 Client,
254 /// This is a super key type. These keys are created by keystore itself and used to encrypt
255 /// other key blobs to provide LSKF binding.
256 Super,
257 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
258 Attestation,
259}
260
261impl ToSql for KeyType {
262 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
263 Ok(ToSqlOutput::Owned(Value::Integer(match self {
264 KeyType::Client => 0,
265 KeyType::Super => 1,
266 KeyType::Attestation => 2,
267 })))
268 }
269}
270
271impl FromSql for KeyType {
272 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
273 match i64::column_result(value)? {
274 0 => Ok(KeyType::Client),
275 1 => Ok(KeyType::Super),
276 2 => Ok(KeyType::Attestation),
277 v => Err(FromSqlError::OutOfRange(v)),
278 }
279 }
280}
281
Max Bires8e93d2b2021-01-14 13:17:59 -0800282/// Uuid representation that can be stored in the database.
283/// Right now it can only be initialized from SecurityLevel.
284/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
285#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
286pub struct Uuid([u8; 16]);
287
288impl Deref for Uuid {
289 type Target = [u8; 16];
290
291 fn deref(&self) -> &Self::Target {
292 &self.0
293 }
294}
295
296impl From<SecurityLevel> for Uuid {
297 fn from(sec_level: SecurityLevel) -> Self {
298 Self((sec_level.0 as u128).to_be_bytes())
299 }
300}
301
302impl ToSql for Uuid {
303 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
304 self.0.to_sql()
305 }
306}
307
308impl FromSql for Uuid {
309 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
310 let blob = Vec::<u8>::column_result(value)?;
311 if blob.len() != 16 {
312 return Err(FromSqlError::OutOfRange(blob.len() as i64));
313 }
314 let mut arr = [0u8; 16];
315 arr.copy_from_slice(&blob);
316 Ok(Self(arr))
317 }
318}
319
320/// Key entries that are not associated with any KeyMint instance, such as pure certificate
321/// entries are associated with this UUID.
322pub static KEYSTORE_UUID: Uuid = Uuid([
323 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
324]);
325
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800326/// Indicates how the sensitive part of this key blob is encrypted.
327#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
328pub enum EncryptedBy {
329 /// The keyblob is encrypted by a user password.
330 /// In the database this variant is represented as NULL.
331 Password,
332 /// The keyblob is encrypted by another key with wrapped key id.
333 /// In the database this variant is represented as non NULL value
334 /// that is convertible to i64, typically NUMERIC.
335 KeyId(i64),
336}
337
338impl ToSql for EncryptedBy {
339 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
340 match self {
341 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
342 Self::KeyId(id) => id.to_sql(),
343 }
344 }
345}
346
347impl FromSql for EncryptedBy {
348 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
349 match value {
350 ValueRef::Null => Ok(Self::Password),
351 _ => Ok(Self::KeyId(i64::column_result(value)?)),
352 }
353 }
354}
355
356/// A database representation of wall clock time. DateTime stores unix epoch time as
357/// i64 in milliseconds.
358#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
359pub struct DateTime(i64);
360
361/// Error type returned when creating DateTime or converting it from and to
362/// SystemTime.
363#[derive(thiserror::Error, Debug)]
364pub enum DateTimeError {
365 /// This is returned when SystemTime and Duration computations fail.
366 #[error(transparent)]
367 SystemTimeError(#[from] SystemTimeError),
368
369 /// This is returned when type conversions fail.
370 #[error(transparent)]
371 TypeConversion(#[from] std::num::TryFromIntError),
372
373 /// This is returned when checked time arithmetic failed.
374 #[error("Time arithmetic failed.")]
375 TimeArithmetic,
376}
377
378impl DateTime {
379 /// Constructs a new DateTime object denoting the current time. This may fail during
380 /// conversion to unix epoch time and during conversion to the internal i64 representation.
381 pub fn now() -> Result<Self, DateTimeError> {
382 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
383 }
384
385 /// Constructs a new DateTime object from milliseconds.
386 pub fn from_millis_epoch(millis: i64) -> Self {
387 Self(millis)
388 }
389
390 /// Returns unix epoch time in milliseconds.
391 pub fn to_millis_epoch(&self) -> i64 {
392 self.0
393 }
394
395 /// Returns unix epoch time in seconds.
396 pub fn to_secs_epoch(&self) -> i64 {
397 self.0 / 1000
398 }
399}
400
401impl ToSql for DateTime {
402 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
403 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
404 }
405}
406
407impl FromSql for DateTime {
408 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
409 Ok(Self(i64::column_result(value)?))
410 }
411}
412
413impl TryInto<SystemTime> for DateTime {
414 type Error = DateTimeError;
415
416 fn try_into(self) -> Result<SystemTime, Self::Error> {
417 // We want to construct a SystemTime representation equivalent to self, denoting
418 // a point in time THEN, but we cannot set the time directly. We can only construct
419 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
420 // and between EPOCH and THEN. With this common reference we can construct the
421 // duration between NOW and THEN which we can add to our SystemTime representation
422 // of NOW to get a SystemTime representation of THEN.
423 // Durations can only be positive, thus the if statement below.
424 let now = SystemTime::now();
425 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
426 let then_epoch = Duration::from_millis(self.0.try_into()?);
427 Ok(if now_epoch > then_epoch {
428 // then = now - (now_epoch - then_epoch)
429 now_epoch
430 .checked_sub(then_epoch)
431 .and_then(|d| now.checked_sub(d))
432 .ok_or(DateTimeError::TimeArithmetic)?
433 } else {
434 // then = now + (then_epoch - now_epoch)
435 then_epoch
436 .checked_sub(now_epoch)
437 .and_then(|d| now.checked_add(d))
438 .ok_or(DateTimeError::TimeArithmetic)?
439 })
440 }
441}
442
443impl TryFrom<SystemTime> for DateTime {
444 type Error = DateTimeError;
445
446 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
447 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
448 }
449}
450
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800451#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
452enum KeyLifeCycle {
453 /// Existing keys have a key ID but are not fully populated yet.
454 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
455 /// them to Unreferenced for garbage collection.
456 Existing,
457 /// A live key is fully populated and usable by clients.
458 Live,
459 /// An unreferenced key is scheduled for garbage collection.
460 Unreferenced,
461}
462
463impl ToSql for KeyLifeCycle {
464 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
465 match self {
466 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
467 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
468 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
469 }
470 }
471}
472
473impl FromSql for KeyLifeCycle {
474 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
475 match i64::column_result(value)? {
476 0 => Ok(KeyLifeCycle::Existing),
477 1 => Ok(KeyLifeCycle::Live),
478 2 => Ok(KeyLifeCycle::Unreferenced),
479 v => Err(FromSqlError::OutOfRange(v)),
480 }
481 }
482}
483
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700484/// Keys have a KeyMint blob component and optional public certificate and
485/// certificate chain components.
486/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
487/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800488#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700489pub struct KeyEntryLoadBits(u32);
490
491impl KeyEntryLoadBits {
492 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
493 pub const NONE: KeyEntryLoadBits = Self(0);
494 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
495 pub const KM: KeyEntryLoadBits = Self(1);
496 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
497 pub const PUBLIC: KeyEntryLoadBits = Self(2);
498 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
499 pub const BOTH: KeyEntryLoadBits = Self(3);
500
501 /// Returns true if this object indicates that the public components shall be loaded.
502 pub const fn load_public(&self) -> bool {
503 self.0 & Self::PUBLIC.0 != 0
504 }
505
506 /// Returns true if the object indicates that the KeyMint component shall be loaded.
507 pub const fn load_km(&self) -> bool {
508 self.0 & Self::KM.0 != 0
509 }
510}
511
Janis Danisevskisaec14592020-11-12 09:41:49 -0800512lazy_static! {
513 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
514}
515
516struct KeyIdLockDb {
517 locked_keys: Mutex<HashSet<i64>>,
518 cond_var: Condvar,
519}
520
521/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
522/// from the database a second time. Most functions manipulating the key blob database
523/// require a KeyIdGuard.
524#[derive(Debug)]
525pub struct KeyIdGuard(i64);
526
527impl KeyIdLockDb {
528 fn new() -> Self {
529 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
530 }
531
532 /// This function blocks until an exclusive lock for the given key entry id can
533 /// be acquired. It returns a guard object, that represents the lifecycle of the
534 /// acquired lock.
535 pub fn get(&self, key_id: i64) -> KeyIdGuard {
536 let mut locked_keys = self.locked_keys.lock().unwrap();
537 while locked_keys.contains(&key_id) {
538 locked_keys = self.cond_var.wait(locked_keys).unwrap();
539 }
540 locked_keys.insert(key_id);
541 KeyIdGuard(key_id)
542 }
543
544 /// This function attempts to acquire an exclusive lock on a given key id. If the
545 /// given key id is already taken the function returns None immediately. If a lock
546 /// can be acquired this function returns a guard object, that represents the
547 /// lifecycle of the acquired lock.
548 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
549 let mut locked_keys = self.locked_keys.lock().unwrap();
550 if locked_keys.insert(key_id) {
551 Some(KeyIdGuard(key_id))
552 } else {
553 None
554 }
555 }
556}
557
558impl KeyIdGuard {
559 /// Get the numeric key id of the locked key.
560 pub fn id(&self) -> i64 {
561 self.0
562 }
563}
564
565impl Drop for KeyIdGuard {
566 fn drop(&mut self) {
567 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
568 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800569 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800570 KEY_ID_LOCK.cond_var.notify_all();
571 }
572}
573
Max Bires8e93d2b2021-01-14 13:17:59 -0800574/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700575#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800576pub struct CertificateInfo {
577 cert: Option<Vec<u8>>,
578 cert_chain: Option<Vec<u8>>,
579}
580
581impl CertificateInfo {
582 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
583 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
584 Self { cert, cert_chain }
585 }
586
587 /// Take the cert
588 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
589 self.cert.take()
590 }
591
592 /// Take the cert chain
593 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
594 self.cert_chain.take()
595 }
596}
597
Max Bires2b2e6562020-09-22 11:22:36 -0700598/// This type represents a certificate chain with a private key corresponding to the leaf
599/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
Max Bires2b2e6562020-09-22 11:22:36 -0700600pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800601 /// A KM key blob
602 pub private_key: ZVec,
603 /// A batch cert for private_key
604 pub batch_cert: Vec<u8>,
605 /// A full certificate chain from root signing authority to private_key, including batch_cert
606 /// for convenience.
607 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700608}
609
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700610/// This type represents a Keystore 2.0 key entry.
611/// An entry has a unique `id` by which it can be found in the database.
612/// It has a security level field, key parameters, and three optional fields
613/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800614#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615pub struct KeyEntry {
616 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800617 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700618 cert: Option<Vec<u8>>,
619 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800620 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700621 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800622 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800623 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700624}
625
626impl KeyEntry {
627 /// Returns the unique id of the Key entry.
628 pub fn id(&self) -> i64 {
629 self.id
630 }
631 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
633 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700634 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800635 /// Extracts the Optional KeyMint blob including its metadata.
636 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
637 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700638 }
639 /// Exposes the optional public certificate.
640 pub fn cert(&self) -> &Option<Vec<u8>> {
641 &self.cert
642 }
643 /// Extracts the optional public certificate.
644 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
645 self.cert.take()
646 }
647 /// Exposes the optional public certificate chain.
648 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
649 &self.cert_chain
650 }
651 /// Extracts the optional public certificate_chain.
652 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
653 self.cert_chain.take()
654 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800655 /// Returns the uuid of the owning KeyMint instance.
656 pub fn km_uuid(&self) -> &Uuid {
657 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700658 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700659 /// Exposes the key parameters of this key entry.
660 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
661 &self.parameters
662 }
663 /// Consumes this key entry and extracts the keyparameters from it.
664 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
665 self.parameters
666 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800667 /// Exposes the key metadata of this key entry.
668 pub fn metadata(&self) -> &KeyMetaData {
669 &self.metadata
670 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800671 /// This returns true if the entry is a pure certificate entry with no
672 /// private key component.
673 pub fn pure_cert(&self) -> bool {
674 self.pure_cert
675 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000676 /// Consumes this key entry and extracts the keyparameters and metadata from it.
677 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
678 (self.parameters, self.metadata)
679 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700680}
681
682/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800683#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700684pub struct SubComponentType(u32);
685impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800686 /// Persistent identifier for a key blob.
687 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700688 /// Persistent identifier for a certificate blob.
689 pub const CERT: SubComponentType = Self(1);
690 /// Persistent identifier for a certificate chain blob.
691 pub const CERT_CHAIN: SubComponentType = Self(2);
692}
693
694impl ToSql for SubComponentType {
695 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
696 self.0.to_sql()
697 }
698}
699
700impl FromSql for SubComponentType {
701 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
702 Ok(Self(u32::column_result(value)?))
703 }
704}
705
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800706/// This trait is private to the database module. It is used to convey whether or not the garbage
707/// collector shall be invoked after a database access. All closures passed to
708/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
709/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
710/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
711/// `.need_gc()`.
712trait DoGc<T> {
713 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
714
715 fn no_gc(self) -> Result<(bool, T)>;
716
717 fn need_gc(self) -> Result<(bool, T)>;
718}
719
720impl<T> DoGc<T> for Result<T> {
721 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
722 self.map(|r| (need_gc, r))
723 }
724
725 fn no_gc(self) -> Result<(bool, T)> {
726 self.do_gc(false)
727 }
728
729 fn need_gc(self) -> Result<(bool, T)> {
730 self.do_gc(true)
731 }
732}
733
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700734/// KeystoreDB wraps a connection to an SQLite database and tracks its
735/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700736pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700737 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700738 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700739 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700740}
741
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000742/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000743/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000744#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
745pub struct MonotonicRawTime(i64);
746
747impl MonotonicRawTime {
748 /// Constructs a new MonotonicRawTime
749 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000750 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000751 }
752
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000753 /// Returns the value of MonotonicRawTime in milliseconds as i64
754 pub fn milliseconds(&self) -> i64 {
755 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000756 }
757
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000758 /// Returns the integer value of MonotonicRawTime as i64
759 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000760 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000761 }
762
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800763 /// Like i64::checked_sub.
764 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
765 self.0.checked_sub(other.0).map(Self)
766 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000767}
768
769impl ToSql for MonotonicRawTime {
770 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
771 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
772 }
773}
774
775impl FromSql for MonotonicRawTime {
776 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
777 Ok(Self(i64::column_result(value)?))
778 }
779}
780
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000781/// This struct encapsulates the information to be stored in the database about the auth tokens
782/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700783#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000784pub struct AuthTokenEntry {
785 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000786 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000787 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000788}
789
790impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000791 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000792 AuthTokenEntry { auth_token, time_received }
793 }
794
795 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800796 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
799 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 })
801 }
802
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000803 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800804 pub fn auth_token(&self) -> &HardwareAuthToken {
805 &self.auth_token
806 }
807
808 /// Returns the auth token wrapped by the AuthTokenEntry
809 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000810 self.auth_token
811 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800812
813 /// Returns the time that this auth token was received.
814 pub fn time_received(&self) -> MonotonicRawTime {
815 self.time_received
816 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000817
818 /// Returns the challenge value of the auth token.
819 pub fn challenge(&self) -> i64 {
820 self.auth_token.challenge
821 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822}
823
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800824/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
825/// This object does not allow access to the database connection. But it keeps a database
826/// connection alive in order to keep the in memory per boot database alive.
827pub struct PerBootDbKeepAlive(Connection);
828
Joel Galenson26f4d012020-07-17 14:57:21 -0700829impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800830 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700831 const CURRENT_DB_VERSION: u32 = 1;
832 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800833
Seth Moore78c091f2021-04-09 21:38:30 +0000834 /// Name of the file that holds the cross-boot persistent database.
835 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
836
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700837 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800838 /// files persistent.sqlite and perboot.sqlite in the given directory.
839 /// It also attempts to initialize all of the tables.
840 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700841 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700842 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700843 let _wp = wd::watch_millis("KeystoreDB::new", 500);
844
Seth Moore472fcbb2021-05-12 10:07:51 -0700845 let persistent_path = Self::make_persistent_path(&db_root)?;
846 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800847
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700848 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800849 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700850 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
851 .context("In KeystoreDB::new: trying to upgrade database.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800852 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800853 })?;
854 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700855 }
856
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700857 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
858 // cryptographic binding to the boot level keys was implemented.
859 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
860 tx.execute(
861 "UPDATE persistent.keyentry SET state = ?
862 WHERE
863 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
864 AND
865 id NOT IN (
866 SELECT keyentryid FROM persistent.blobentry
867 WHERE id IN (
868 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
869 )
870 );",
871 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
872 )
873 .context("In from_0_to_1: Failed to delete logical boot level keys.")?;
874 Ok(1)
875 }
876
Janis Danisevskis66784c42021-01-27 08:40:25 -0800877 fn init_tables(tx: &Transaction) -> Result<()> {
878 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700879 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700880 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800881 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700882 domain INTEGER,
883 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800884 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800885 state INTEGER,
886 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700887 NO_PARAMS,
888 )
889 .context("Failed to initialize \"keyentry\" table.")?;
890
Janis Danisevskis66784c42021-01-27 08:40:25 -0800891 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800892 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
893 ON keyentry(id);",
894 NO_PARAMS,
895 )
896 .context("Failed to create index keyentry_id_index.")?;
897
898 tx.execute(
899 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
900 ON keyentry(domain, namespace, alias);",
901 NO_PARAMS,
902 )
903 .context("Failed to create index keyentry_domain_namespace_index.")?;
904
905 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700906 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
907 id INTEGER PRIMARY KEY,
908 subcomponent_type INTEGER,
909 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800910 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700911 NO_PARAMS,
912 )
913 .context("Failed to initialize \"blobentry\" table.")?;
914
Janis Danisevskis66784c42021-01-27 08:40:25 -0800915 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800916 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
917 ON blobentry(keyentryid);",
918 NO_PARAMS,
919 )
920 .context("Failed to create index blobentry_keyentryid_index.")?;
921
922 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800923 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
924 id INTEGER PRIMARY KEY,
925 blobentryid INTEGER,
926 tag INTEGER,
927 data ANY,
928 UNIQUE (blobentryid, tag));",
929 NO_PARAMS,
930 )
931 .context("Failed to initialize \"blobmetadata\" table.")?;
932
933 tx.execute(
934 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
935 ON blobmetadata(blobentryid);",
936 NO_PARAMS,
937 )
938 .context("Failed to create index blobmetadata_blobentryid_index.")?;
939
940 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700941 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000942 keyentryid INTEGER,
943 tag INTEGER,
944 data ANY,
945 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700946 NO_PARAMS,
947 )
948 .context("Failed to initialize \"keyparameter\" table.")?;
949
Janis Danisevskis66784c42021-01-27 08:40:25 -0800950 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800951 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
952 ON keyparameter(keyentryid);",
953 NO_PARAMS,
954 )
955 .context("Failed to create index keyparameter_keyentryid_index.")?;
956
957 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800958 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
959 keyentryid INTEGER,
960 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000961 data ANY,
962 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800963 NO_PARAMS,
964 )
965 .context("Failed to initialize \"keymetadata\" table.")?;
966
Janis Danisevskis66784c42021-01-27 08:40:25 -0800967 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800968 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
969 ON keymetadata(keyentryid);",
970 NO_PARAMS,
971 )
972 .context("Failed to create index keymetadata_keyentryid_index.")?;
973
974 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800975 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700976 id INTEGER UNIQUE,
977 grantee INTEGER,
978 keyentryid INTEGER,
979 access_vector INTEGER);",
980 NO_PARAMS,
981 )
982 .context("Failed to initialize \"grant\" table.")?;
983
Joel Galenson0891bc12020-07-20 10:37:03 -0700984 Ok(())
985 }
986
Seth Moore472fcbb2021-05-12 10:07:51 -0700987 fn make_persistent_path(db_root: &Path) -> Result<String> {
988 // Build the path to the sqlite file.
989 let mut persistent_path = db_root.to_path_buf();
990 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
991
992 // Now convert them to strings prefixed with "file:"
993 let mut persistent_path_str = "file:".to_owned();
994 persistent_path_str.push_str(&persistent_path.to_string_lossy());
995
996 Ok(persistent_path_str)
997 }
998
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700999 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001000 let conn =
1001 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1002
Janis Danisevskis66784c42021-01-27 08:40:25 -08001003 loop {
1004 if let Err(e) = conn
1005 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1006 .context("Failed to attach database persistent.")
1007 {
1008 if Self::is_locked_error(&e) {
1009 std::thread::sleep(std::time::Duration::from_micros(500));
1010 continue;
1011 } else {
1012 return Err(e);
1013 }
1014 }
1015 break;
1016 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001017
Matthew Maurer4fb19112021-05-06 15:40:44 -07001018 // Drop the cache size from default (2M) to 0.5M
1019 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1020 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001021
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001022 Ok(conn)
1023 }
1024
Seth Moore78c091f2021-04-09 21:38:30 +00001025 fn do_table_size_query(
1026 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001027 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001028 query: &str,
1029 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001030 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001031 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001032 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001033 .with_context(|| {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001034 format!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001035 })
1036 .no_gc()
1037 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001038 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001039 }
1040
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001041 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001042 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001043 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001044 "SELECT page_count * page_size, freelist_count * page_size
1045 FROM pragma_page_count('persistent'),
1046 pragma_page_size('persistent'),
1047 persistent.pragma_freelist_count();",
1048 &[],
1049 )
1050 }
1051
1052 fn get_table_size(
1053 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001054 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001055 schema: &str,
1056 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001057 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001058 self.do_table_size_query(
1059 storage_type,
1060 "SELECT pgsize,unused FROM dbstat(?1)
1061 WHERE name=?2 AND aggregate=TRUE;",
1062 &[schema, table],
1063 )
1064 }
1065
1066 /// Fetches a storage statisitics atom for a given storage type. For storage
1067 /// types that map to a table, information about the table's storage is
1068 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001069 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001070 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1071
Seth Moore78c091f2021-04-09 21:38:30 +00001072 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001073 MetricsStorage::DATABASE => self.get_total_size(),
1074 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001075 self.get_table_size(storage_type, "persistent", "keyentry")
1076 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001077 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001078 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1079 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001080 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001081 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1082 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001083 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001084 self.get_table_size(storage_type, "persistent", "blobentry")
1085 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001086 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001087 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1088 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001089 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001090 self.get_table_size(storage_type, "persistent", "keyparameter")
1091 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001092 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001093 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1094 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001095 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001096 self.get_table_size(storage_type, "persistent", "keymetadata")
1097 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001098 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001099 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1100 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001101 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1102 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001103 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1104 // reportable
1105 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001106 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001107 storage_type,
1108 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001109 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001110 unused_size: 0,
1111 })
Seth Moore78c091f2021-04-09 21:38:30 +00001112 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001113 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001114 self.get_table_size(storage_type, "persistent", "blobmetadata")
1115 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001116 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001120 }
1121 }
1122
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001123 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001124 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1125 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001126 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1127 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001128 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001129 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001130 blob_ids_to_delete: &[i64],
1131 max_blobs: usize,
1132 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001133 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001134 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001135 // Delete the given blobs.
1136 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001137 tx.execute(
1138 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001139 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001140 )
1141 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001142 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1143 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001144 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001145
1146 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1147
Janis Danisevskis3395f862021-05-06 10:54:17 -07001148 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1149 let result: Vec<(i64, Vec<u8>)> = {
1150 let mut stmt = tx
1151 .prepare(
1152 "SELECT id, blob FROM persistent.blobentry
1153 WHERE subcomponent_type = ?
1154 AND (
1155 id NOT IN (
1156 SELECT MAX(id) FROM persistent.blobentry
1157 WHERE subcomponent_type = ?
1158 GROUP BY keyentryid, subcomponent_type
1159 )
1160 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1161 ) LIMIT ?;",
1162 )
1163 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001164
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 let rows = stmt
1166 .query_map(
1167 params![
1168 SubComponentType::KEY_BLOB,
1169 SubComponentType::KEY_BLOB,
1170 max_blobs as i64,
1171 ],
1172 |row| Ok((row.get(0)?, row.get(1)?)),
1173 )
1174 .context("Trying to query superseded blob.")?;
1175
1176 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1177 .context("Trying to extract superseded blobs.")?
1178 };
1179
1180 let result = result
1181 .into_iter()
1182 .map(|(blob_id, blob)| {
1183 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1184 })
1185 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1186 .context("Trying to load blob metadata.")?;
1187 if !result.is_empty() {
1188 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001189 }
1190
1191 // We did not find any superseded key blob, so let's remove other superseded blob in
1192 // one transaction.
1193 tx.execute(
1194 "DELETE FROM persistent.blobentry
1195 WHERE NOT subcomponent_type = ?
1196 AND (
1197 id NOT IN (
1198 SELECT MAX(id) FROM persistent.blobentry
1199 WHERE NOT subcomponent_type = ?
1200 GROUP BY keyentryid, subcomponent_type
1201 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1202 );",
1203 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1204 )
1205 .context("Trying to purge superseded blobs.")?;
1206
Janis Danisevskis3395f862021-05-06 10:54:17 -07001207 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001208 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001209 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001210 }
1211
1212 /// This maintenance function should be called only once before the database is used for the
1213 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1214 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1215 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1216 /// Keystore crashed at some point during key generation. Callers may want to log such
1217 /// occurrences.
1218 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1219 /// it to `KeyLifeCycle::Live` may have grants.
1220 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001221 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1222
Janis Danisevskis66784c42021-01-27 08:40:25 -08001223 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1224 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001225 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1226 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1227 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001228 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001229 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001230 })
1231 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001232 }
1233
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001234 /// Checks if a key exists with given key type and key descriptor properties.
1235 pub fn key_exists(
1236 &mut self,
1237 domain: Domain,
1238 nspace: i64,
1239 alias: &str,
1240 key_type: KeyType,
1241 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001242 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1243
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001244 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1245 let key_descriptor =
1246 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1247 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1248 match result {
1249 Ok(_) => Ok(true),
1250 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1251 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1252 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1253 },
1254 }
1255 .no_gc()
1256 })
1257 .context("In key_exists.")
1258 }
1259
Hasini Gunasingheda895552021-01-27 19:34:37 +00001260 /// Stores a super key in the database.
1261 pub fn store_super_key(
1262 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001263 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001264 key_type: &SuperKeyType,
1265 blob: &[u8],
1266 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001267 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001268 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001269 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1270
Hasini Gunasingheda895552021-01-27 19:34:37 +00001271 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1272 let key_id = Self::insert_with_retry(|id| {
1273 tx.execute(
1274 "INSERT into persistent.keyentry
1275 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001276 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001277 params![
1278 id,
1279 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001280 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001281 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001282 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001283 KeyLifeCycle::Live,
1284 &KEYSTORE_UUID,
1285 ],
1286 )
1287 })
1288 .context("Failed to insert into keyentry table.")?;
1289
Paul Crowley8d5b2532021-03-19 10:53:07 -07001290 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1291
Hasini Gunasingheda895552021-01-27 19:34:37 +00001292 Self::set_blob_internal(
1293 &tx,
1294 key_id,
1295 SubComponentType::KEY_BLOB,
1296 Some(blob),
1297 Some(blob_metadata),
1298 )
1299 .context("Failed to store key blob.")?;
1300
1301 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1302 .context("Trying to load key components.")
1303 .no_gc()
1304 })
1305 .context("In store_super_key.")
1306 }
1307
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001308 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001309 pub fn load_super_key(
1310 &mut self,
1311 key_type: &SuperKeyType,
1312 user_id: u32,
1313 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001314 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1315
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001316 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1317 let key_descriptor = KeyDescriptor {
1318 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001319 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001320 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001321 blob: None,
1322 };
1323 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1324 match id {
1325 Ok(id) => {
1326 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1327 .context("In load_super_key. Failed to load key entry.")?;
1328 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1329 }
1330 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1331 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1332 _ => Err(error).context("In load_super_key."),
1333 },
1334 }
1335 .no_gc()
1336 })
1337 .context("In load_super_key.")
1338 }
1339
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001340 /// Atomically loads a key entry and associated metadata or creates it using the
1341 /// callback create_new_key callback. The callback is called during a database
1342 /// transaction. This means that implementers should be mindful about using
1343 /// blocking operations such as IPC or grabbing mutexes.
1344 pub fn get_or_create_key_with<F>(
1345 &mut self,
1346 domain: Domain,
1347 namespace: i64,
1348 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001349 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001350 create_new_key: F,
1351 ) -> Result<(KeyIdGuard, KeyEntry)>
1352 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001353 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001354 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001355 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1356
Janis Danisevskis66784c42021-01-27 08:40:25 -08001357 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1358 let id = {
1359 let mut stmt = tx
1360 .prepare(
1361 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001362 WHERE
1363 key_type = ?
1364 AND domain = ?
1365 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001366 AND alias = ?
1367 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001368 )
1369 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1370 let mut rows = stmt
1371 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1372 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001373
Janis Danisevskis66784c42021-01-27 08:40:25 -08001374 db_utils::with_rows_extract_one(&mut rows, |row| {
1375 Ok(match row {
1376 Some(r) => r.get(0).context("Failed to unpack id.")?,
1377 None => None,
1378 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001379 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001380 .context("In get_or_create_key_with.")?
1381 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001382
Janis Danisevskis66784c42021-01-27 08:40:25 -08001383 let (id, entry) = match id {
1384 Some(id) => (
1385 id,
1386 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1387 .context("In get_or_create_key_with.")?,
1388 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001389
Janis Danisevskis66784c42021-01-27 08:40:25 -08001390 None => {
1391 let id = Self::insert_with_retry(|id| {
1392 tx.execute(
1393 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001394 (id, key_type, domain, namespace, alias, state, km_uuid)
1395 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001396 params![
1397 id,
1398 KeyType::Super,
1399 domain.0,
1400 namespace,
1401 alias,
1402 KeyLifeCycle::Live,
1403 km_uuid,
1404 ],
1405 )
1406 })
1407 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001408
Janis Danisevskis66784c42021-01-27 08:40:25 -08001409 let (blob, metadata) =
1410 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001411 Self::set_blob_internal(
1412 &tx,
1413 id,
1414 SubComponentType::KEY_BLOB,
1415 Some(&blob),
1416 Some(&metadata),
1417 )
Paul Crowley7a658392021-03-18 17:08:20 -07001418 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001420 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001421 KeyEntry {
1422 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001423 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001424 pure_cert: false,
1425 ..Default::default()
1426 },
1427 )
1428 }
1429 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001430 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001431 })
1432 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001433 }
1434
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001435 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001436 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1437 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001438 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1439 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001440 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001441 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001442 loop {
1443 match self
1444 .conn
1445 .transaction_with_behavior(behavior)
1446 .context("In with_transaction.")
1447 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1448 .and_then(|(result, tx)| {
1449 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1450 Ok(result)
1451 }) {
1452 Ok(result) => break Ok(result),
1453 Err(e) => {
1454 if Self::is_locked_error(&e) {
1455 std::thread::sleep(std::time::Duration::from_micros(500));
1456 continue;
1457 } else {
1458 return Err(e).context("In with_transaction.");
1459 }
1460 }
1461 }
1462 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001463 .map(|(need_gc, result)| {
1464 if need_gc {
1465 if let Some(ref gc) = self.gc {
1466 gc.notify_gc();
1467 }
1468 }
1469 result
1470 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001471 }
1472
1473 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001474 matches!(
1475 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1476 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1477 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1478 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001479 }
1480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001481 /// Creates a new key entry and allocates a new randomized id for the new key.
1482 /// The key id gets associated with a domain and namespace but not with an alias.
1483 /// To complete key generation `rebind_alias` should be called after all of the
1484 /// key artifacts, i.e., blobs and parameters have been associated with the new
1485 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1486 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001487 pub fn create_key_entry(
1488 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001489 domain: &Domain,
1490 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001491 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001492 km_uuid: &Uuid,
1493 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001494 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1495
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001496 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001497 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001498 })
1499 .context("In create_key_entry.")
1500 }
1501
1502 fn create_key_entry_internal(
1503 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001504 domain: &Domain,
1505 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001506 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001507 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001508 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001509 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001510 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001511 _ => {
1512 return Err(KsError::sys())
1513 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1514 }
1515 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001516 Ok(KEY_ID_LOCK.get(
1517 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001518 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001519 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001520 (id, key_type, domain, namespace, alias, state, km_uuid)
1521 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001522 params![
1523 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001524 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001526 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001527 KeyLifeCycle::Existing,
1528 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001529 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001530 )
1531 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001532 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001533 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001534 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001535
Max Bires2b2e6562020-09-22 11:22:36 -07001536 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1537 /// The key id gets associated with a domain and namespace later but not with an alias. The
1538 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1539 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1540 /// a key.
1541 pub fn create_attestation_key_entry(
1542 &mut self,
1543 maced_public_key: &[u8],
1544 raw_public_key: &[u8],
1545 private_key: &[u8],
1546 km_uuid: &Uuid,
1547 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001548 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1549
Max Bires2b2e6562020-09-22 11:22:36 -07001550 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1551 let key_id = KEY_ID_LOCK.get(
1552 Self::insert_with_retry(|id| {
1553 tx.execute(
1554 "INSERT into persistent.keyentry
1555 (id, key_type, domain, namespace, alias, state, km_uuid)
1556 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1557 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1558 )
1559 })
1560 .context("In create_key_entry")?,
1561 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001562 Self::set_blob_internal(
1563 &tx,
1564 key_id.0,
1565 SubComponentType::KEY_BLOB,
1566 Some(private_key),
1567 None,
1568 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001569 let mut metadata = KeyMetaData::new();
1570 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1571 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1572 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001573 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001574 })
1575 .context("In create_attestation_key_entry")
1576 }
1577
Janis Danisevskis377d1002021-01-27 19:07:48 -08001578 /// Set a new blob and associates it with the given key id. Each blob
1579 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001580 /// Each key can have one of each sub component type associated. If more
1581 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001582 /// will get garbage collected.
1583 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1584 /// removed by setting blob to None.
1585 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001586 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001587 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001588 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001589 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001590 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001591 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001592 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1593
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001594 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001595 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001596 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001597 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001598 }
1599
Janis Danisevskiseed69842021-02-18 20:04:10 -08001600 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1601 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1602 /// We use this to insert key blobs into the database which can then be garbage collected
1603 /// lazily by the key garbage collector.
1604 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001605 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1606
Janis Danisevskiseed69842021-02-18 20:04:10 -08001607 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1608 Self::set_blob_internal(
1609 &tx,
1610 Self::UNASSIGNED_KEY_ID,
1611 SubComponentType::KEY_BLOB,
1612 Some(blob),
1613 Some(blob_metadata),
1614 )
1615 .need_gc()
1616 })
1617 .context("In set_deleted_blob.")
1618 }
1619
Janis Danisevskis377d1002021-01-27 19:07:48 -08001620 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001621 tx: &Transaction,
1622 key_id: i64,
1623 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001624 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001625 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001626 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001627 match (blob, sc_type) {
1628 (Some(blob), _) => {
1629 tx.execute(
1630 "INSERT INTO persistent.blobentry
1631 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1632 params![sc_type, key_id, blob],
1633 )
1634 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001635 if let Some(blob_metadata) = blob_metadata {
1636 let blob_id = tx
1637 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1638 row.get(0)
1639 })
1640 .context("In set_blob_internal: Failed to get new blob id.")?;
1641 blob_metadata
1642 .store_in_db(blob_id, tx)
1643 .context("In set_blob_internal: Trying to store blob metadata.")?;
1644 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001645 }
1646 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1647 tx.execute(
1648 "DELETE FROM persistent.blobentry
1649 WHERE subcomponent_type = ? AND keyentryid = ?;",
1650 params![sc_type, key_id],
1651 )
1652 .context("In set_blob_internal: Failed to delete blob.")?;
1653 }
1654 (None, _) => {
1655 return Err(KsError::sys())
1656 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1657 }
1658 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001659 Ok(())
1660 }
1661
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001662 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1663 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001664 #[cfg(test)]
1665 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001666 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001667 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001668 })
1669 .context("In insert_keyparameter.")
1670 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001671
Janis Danisevskis66784c42021-01-27 08:40:25 -08001672 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001673 tx: &Transaction,
1674 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001675 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001676 ) -> Result<()> {
1677 let mut stmt = tx
1678 .prepare(
1679 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1680 VALUES (?, ?, ?, ?);",
1681 )
1682 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1683
Janis Danisevskis66784c42021-01-27 08:40:25 -08001684 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001685 stmt.insert(params![
1686 key_id.0,
1687 p.get_tag().0,
1688 p.key_parameter_value(),
1689 p.security_level().0
1690 ])
1691 .with_context(|| {
1692 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1693 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001694 }
1695 Ok(())
1696 }
1697
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001698 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001699 #[cfg(test)]
1700 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001701 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001702 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001703 })
1704 .context("In insert_key_metadata.")
1705 }
1706
Max Bires2b2e6562020-09-22 11:22:36 -07001707 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1708 /// on the public key.
1709 pub fn store_signed_attestation_certificate_chain(
1710 &mut self,
1711 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001712 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001713 cert_chain: &[u8],
1714 expiration_date: i64,
1715 km_uuid: &Uuid,
1716 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001717 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1718
Max Bires2b2e6562020-09-22 11:22:36 -07001719 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1720 let mut stmt = tx
1721 .prepare(
1722 "SELECT keyentryid
1723 FROM persistent.keymetadata
1724 WHERE tag = ? AND data = ? AND keyentryid IN
1725 (SELECT id
1726 FROM persistent.keyentry
1727 WHERE
1728 alias IS NULL AND
1729 domain IS NULL AND
1730 namespace IS NULL AND
1731 key_type = ? AND
1732 km_uuid = ?);",
1733 )
1734 .context("Failed to store attestation certificate chain.")?;
1735 let mut rows = stmt
1736 .query(params![
1737 KeyMetaData::AttestationRawPubKey,
1738 raw_public_key,
1739 KeyType::Attestation,
1740 km_uuid
1741 ])
1742 .context("Failed to fetch keyid")?;
1743 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1744 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1745 .get(0)
1746 .context("Failed to unpack id.")
1747 })
1748 .context("Failed to get key_id.")?;
1749 let num_updated = tx
1750 .execute(
1751 "UPDATE persistent.keyentry
1752 SET alias = ?
1753 WHERE id = ?;",
1754 params!["signed", key_id],
1755 )
1756 .context("Failed to update alias.")?;
1757 if num_updated != 1 {
1758 return Err(KsError::sys()).context("Alias not updated for the key.");
1759 }
1760 let mut metadata = KeyMetaData::new();
1761 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1762 expiration_date,
1763 )));
1764 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001765 Self::set_blob_internal(
1766 &tx,
1767 key_id,
1768 SubComponentType::CERT_CHAIN,
1769 Some(cert_chain),
1770 None,
1771 )
1772 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001773 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1774 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001775 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001776 })
1777 .context("In store_signed_attestation_certificate_chain: ")
1778 }
1779
1780 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1781 /// currently have a key assigned to it.
1782 pub fn assign_attestation_key(
1783 &mut self,
1784 domain: Domain,
1785 namespace: i64,
1786 km_uuid: &Uuid,
1787 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001788 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1789
Max Bires2b2e6562020-09-22 11:22:36 -07001790 match domain {
1791 Domain::APP | Domain::SELINUX => {}
1792 _ => {
1793 return Err(KsError::sys()).context(format!(
1794 concat!(
1795 "In assign_attestation_key: Domain {:?} ",
1796 "must be either App or SELinux.",
1797 ),
1798 domain
1799 ));
1800 }
1801 }
1802 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1803 let result = tx
1804 .execute(
1805 "UPDATE persistent.keyentry
1806 SET domain=?1, namespace=?2
1807 WHERE
1808 id =
1809 (SELECT MIN(id)
1810 FROM persistent.keyentry
1811 WHERE ALIAS IS NOT NULL
1812 AND domain IS NULL
1813 AND key_type IS ?3
1814 AND state IS ?4
1815 AND km_uuid IS ?5)
1816 AND
1817 (SELECT COUNT(*)
1818 FROM persistent.keyentry
1819 WHERE domain=?1
1820 AND namespace=?2
1821 AND key_type IS ?3
1822 AND state IS ?4
1823 AND km_uuid IS ?5) = 0;",
1824 params![
1825 domain.0 as u32,
1826 namespace,
1827 KeyType::Attestation,
1828 KeyLifeCycle::Live,
1829 km_uuid,
1830 ],
1831 )
1832 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001833 if result == 0 {
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +00001834 log_rkp_error_stats(MetricsRkpError::OUT_OF_KEYS);
Max Bires01f8af22021-03-02 23:24:50 -08001835 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1836 } else if result > 1 {
1837 return Err(KsError::sys())
1838 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001839 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001840 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001841 })
1842 .context("In assign_attestation_key: ")
1843 }
1844
1845 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1846 /// provisioning server, or the maximum number available if there are not num_keys number of
1847 /// entries in the table.
1848 pub fn fetch_unsigned_attestation_keys(
1849 &mut self,
1850 num_keys: i32,
1851 km_uuid: &Uuid,
1852 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001853 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1854
Max Bires2b2e6562020-09-22 11:22:36 -07001855 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1856 let mut stmt = tx
1857 .prepare(
1858 "SELECT data
1859 FROM persistent.keymetadata
1860 WHERE tag = ? AND keyentryid IN
1861 (SELECT id
1862 FROM persistent.keyentry
1863 WHERE
1864 alias IS NULL AND
1865 domain IS NULL AND
1866 namespace IS NULL AND
1867 key_type = ? AND
1868 km_uuid = ?
1869 LIMIT ?);",
1870 )
1871 .context("Failed to prepare statement")?;
1872 let rows = stmt
1873 .query_map(
1874 params![
1875 KeyMetaData::AttestationMacedPublicKey,
1876 KeyType::Attestation,
1877 km_uuid,
1878 num_keys
1879 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001880 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001881 )?
1882 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1883 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001884 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001885 })
1886 .context("In fetch_unsigned_attestation_keys")
1887 }
1888
1889 /// Removes any keys that have expired as of the current time. Returns the number of keys
1890 /// marked unreferenced that are bound to be garbage collected.
1891 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001892 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1893
Max Bires2b2e6562020-09-22 11:22:36 -07001894 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1895 let mut stmt = tx
1896 .prepare(
1897 "SELECT keyentryid, data
1898 FROM persistent.keymetadata
1899 WHERE tag = ? AND keyentryid IN
1900 (SELECT id
1901 FROM persistent.keyentry
1902 WHERE key_type = ?);",
1903 )
1904 .context("Failed to prepare query")?;
1905 let key_ids_to_check = stmt
1906 .query_map(
1907 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1908 |row| Ok((row.get(0)?, row.get(1)?)),
1909 )?
1910 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1911 .context("Failed to get date metadata")?;
1912 let curr_time = DateTime::from_millis_epoch(
1913 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1914 );
1915 let mut num_deleted = 0;
1916 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1917 if Self::mark_unreferenced(&tx, id)? {
1918 num_deleted += 1;
1919 }
1920 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001921 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001922 })
1923 .context("In delete_expired_attestation_keys: ")
1924 }
1925
Max Bires60d7ed12021-03-05 15:59:22 -08001926 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1927 /// they are in. This is useful primarily as a testing mechanism.
1928 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001929 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1930
Max Bires60d7ed12021-03-05 15:59:22 -08001931 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1932 let mut stmt = tx
1933 .prepare(
1934 "SELECT id FROM persistent.keyentry
1935 WHERE key_type IS ?;",
1936 )
1937 .context("Failed to prepare statement")?;
1938 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001939 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001940 .collect::<rusqlite::Result<Vec<i64>>>()
1941 .context("Failed to execute statement")?;
1942 let num_deleted = keys_to_delete
1943 .iter()
1944 .map(|id| Self::mark_unreferenced(&tx, *id))
1945 .collect::<Result<Vec<bool>>>()
1946 .context("Failed to execute mark_unreferenced on a keyid")?
1947 .into_iter()
1948 .filter(|result| *result)
1949 .count() as i64;
1950 Ok(num_deleted).do_gc(num_deleted != 0)
1951 })
1952 .context("In delete_all_attestation_keys: ")
1953 }
1954
Max Bires2b2e6562020-09-22 11:22:36 -07001955 /// Counts the number of keys that will expire by the provided epoch date and the number of
1956 /// keys not currently assigned to a domain.
1957 pub fn get_attestation_pool_status(
1958 &mut self,
1959 date: i64,
1960 km_uuid: &Uuid,
1961 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001962 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1963
Max Bires2b2e6562020-09-22 11:22:36 -07001964 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1965 let mut stmt = tx.prepare(
1966 "SELECT data
1967 FROM persistent.keymetadata
1968 WHERE tag = ? AND keyentryid IN
1969 (SELECT id
1970 FROM persistent.keyentry
1971 WHERE alias IS NOT NULL
1972 AND key_type = ?
1973 AND km_uuid = ?
1974 AND state = ?);",
1975 )?;
1976 let times = stmt
1977 .query_map(
1978 params![
1979 KeyMetaData::AttestationExpirationDate,
1980 KeyType::Attestation,
1981 km_uuid,
1982 KeyLifeCycle::Live
1983 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001984 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001985 )?
1986 .collect::<rusqlite::Result<Vec<DateTime>>>()
1987 .context("Failed to execute metadata statement")?;
1988 let expiring =
1989 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1990 as i32;
1991 stmt = tx.prepare(
1992 "SELECT alias, domain
1993 FROM persistent.keyentry
1994 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1995 )?;
1996 let rows = stmt
1997 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1998 Ok((row.get(0)?, row.get(1)?))
1999 })?
2000 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2001 .context("Failed to execute keyentry statement")?;
2002 let mut unassigned = 0i32;
2003 let mut attested = 0i32;
2004 let total = rows.len() as i32;
2005 for (alias, domain) in rows {
2006 match (alias, domain) {
2007 (Some(_alias), None) => {
2008 attested += 1;
2009 unassigned += 1;
2010 }
2011 (Some(_alias), Some(_domain)) => {
2012 attested += 1;
2013 }
2014 _ => {}
2015 }
2016 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002017 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002018 })
2019 .context("In get_attestation_pool_status: ")
2020 }
2021
2022 /// Fetches the private key and corresponding certificate chain assigned to a
2023 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2024 /// not assigned, or one CertificateChain.
2025 pub fn retrieve_attestation_key_and_cert_chain(
2026 &mut self,
2027 domain: Domain,
2028 namespace: i64,
2029 km_uuid: &Uuid,
2030 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002031 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2032
Max Bires2b2e6562020-09-22 11:22:36 -07002033 match domain {
2034 Domain::APP | Domain::SELINUX => {}
2035 _ => {
2036 return Err(KsError::sys())
2037 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2038 }
2039 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002040 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2041 let mut stmt = tx.prepare(
2042 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002043 FROM persistent.blobentry
2044 WHERE keyentryid IN
2045 (SELECT id
2046 FROM persistent.keyentry
2047 WHERE key_type = ?
2048 AND domain = ?
2049 AND namespace = ?
2050 AND state = ?
2051 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002052 )?;
2053 let rows = stmt
2054 .query_map(
2055 params![
2056 KeyType::Attestation,
2057 domain.0 as u32,
2058 namespace,
2059 KeyLifeCycle::Live,
2060 km_uuid
2061 ],
2062 |row| Ok((row.get(0)?, row.get(1)?)),
2063 )?
2064 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002065 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002066 if rows.is_empty() {
2067 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002068 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002069 return Err(KsError::sys()).context(format!(
2070 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002071 "Expected to get a single attestation",
2072 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2073 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002074 rows.len()
2075 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002076 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002077 let mut km_blob: Vec<u8> = Vec::new();
2078 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002079 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002080 for row in rows {
2081 let sub_type: SubComponentType = row.0;
2082 match sub_type {
2083 SubComponentType::KEY_BLOB => {
2084 km_blob = row.1;
2085 }
2086 SubComponentType::CERT_CHAIN => {
2087 cert_chain_blob = row.1;
2088 }
Max Biresb2e1d032021-02-08 21:35:05 -08002089 SubComponentType::CERT => {
2090 batch_cert_blob = row.1;
2091 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002092 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2093 }
2094 }
2095 Ok(Some(CertificateChain {
2096 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002097 batch_cert: batch_cert_blob,
2098 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002099 }))
2100 .no_gc()
2101 })
Max Biresb2e1d032021-02-08 21:35:05 -08002102 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002103 }
2104
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002105 /// Updates the alias column of the given key id `newid` with the given alias,
2106 /// and atomically, removes the alias, domain, and namespace from another row
2107 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002108 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2109 /// collector.
2110 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002111 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002112 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002113 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002114 domain: &Domain,
2115 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002116 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002117 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002118 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002119 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002120 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002121 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002122 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002123 domain
2124 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002125 }
2126 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 let updated = tx
2128 .execute(
2129 "UPDATE persistent.keyentry
2130 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002131 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2132 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002133 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002134 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002135 let result = tx
2136 .execute(
2137 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002138 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002139 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002140 params![
2141 alias,
2142 KeyLifeCycle::Live,
2143 newid.0,
2144 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002145 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002146 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002147 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002148 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002149 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002150 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002151 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002152 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002153 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002154 result
2155 ));
2156 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002157 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002158 }
2159
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002160 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2161 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2162 pub fn migrate_key_namespace(
2163 &mut self,
2164 key_id_guard: KeyIdGuard,
2165 destination: &KeyDescriptor,
2166 caller_uid: u32,
2167 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2168 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002169 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2170
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002171 let destination = match destination.domain {
2172 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2173 Domain::SELINUX => (*destination).clone(),
2174 domain => {
2175 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2176 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2177 }
2178 };
2179
2180 // Security critical: Must return immediately on failure. Do not remove the '?';
2181 check_permission(&destination)
2182 .context("In migrate_key_namespace: Trying to check permission.")?;
2183
2184 let alias = destination
2185 .alias
2186 .as_ref()
2187 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2188 .context("In migrate_key_namespace: Alias must be specified.")?;
2189
2190 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2191 // Query the destination location. If there is a key, the migration request fails.
2192 if tx
2193 .query_row(
2194 "SELECT id FROM persistent.keyentry
2195 WHERE alias = ? AND domain = ? AND namespace = ?;",
2196 params![alias, destination.domain.0, destination.nspace],
2197 |_| Ok(()),
2198 )
2199 .optional()
2200 .context("Failed to query destination.")?
2201 .is_some()
2202 {
2203 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2204 .context("Target already exists.");
2205 }
2206
2207 let updated = tx
2208 .execute(
2209 "UPDATE persistent.keyentry
2210 SET alias = ?, domain = ?, namespace = ?
2211 WHERE id = ?;",
2212 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2213 )
2214 .context("Failed to update key entry.")?;
2215
2216 if updated != 1 {
2217 return Err(KsError::sys())
2218 .context(format!("Update succeeded, but {} rows were updated.", updated));
2219 }
2220 Ok(()).no_gc()
2221 })
2222 .context("In migrate_key_namespace:")
2223 }
2224
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002225 /// Store a new key in a single transaction.
2226 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2227 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002228 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2229 /// is now unreferenced and needs to be collected.
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002230 #[allow(clippy::clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002231 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002232 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002233 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002234 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002235 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002236 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002237 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002238 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002239 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002240 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002241 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2242
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002243 let (alias, domain, namespace) = match key {
2244 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2245 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2246 (alias, key.domain, nspace)
2247 }
2248 _ => {
2249 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2250 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2251 }
2252 };
2253 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002254 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002255 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002256 let (blob, blob_metadata) = *blob_info;
2257 Self::set_blob_internal(
2258 tx,
2259 key_id.id(),
2260 SubComponentType::KEY_BLOB,
2261 Some(blob),
2262 Some(&blob_metadata),
2263 )
2264 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002265 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002266 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002267 .context("Trying to insert the certificate.")?;
2268 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002269 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002270 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 tx,
2272 key_id.id(),
2273 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002274 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002275 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002276 )
2277 .context("Trying to insert the certificate chain.")?;
2278 }
2279 Self::insert_keyparameter_internal(tx, &key_id, params)
2280 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002281 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002282 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace, key_type)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002283 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002284 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002285 })
2286 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002287 }
2288
Janis Danisevskis377d1002021-01-27 19:07:48 -08002289 /// Store a new certificate
2290 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2291 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002292 pub fn store_new_certificate(
2293 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002294 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002295 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002296 cert: &[u8],
2297 km_uuid: &Uuid,
2298 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002299 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2300
Janis Danisevskis377d1002021-01-27 19:07:48 -08002301 let (alias, domain, namespace) = match key {
2302 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2303 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2304 (alias, key.domain, nspace)
2305 }
2306 _ => {
2307 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2308 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2309 )
2310 }
2311 };
2312 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002313 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002314 .context("Trying to create new key entry.")?;
2315
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002316 Self::set_blob_internal(
2317 tx,
2318 key_id.id(),
2319 SubComponentType::CERT_CHAIN,
2320 Some(cert),
2321 None,
2322 )
2323 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002324
2325 let mut metadata = KeyMetaData::new();
2326 metadata.add(KeyMetaEntry::CreationDate(
2327 DateTime::now().context("Trying to make creation time.")?,
2328 ));
2329
2330 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2331
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002332 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002333 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002334 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002335 })
2336 .context("In store_new_certificate.")
2337 }
2338
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002339 // Helper function loading the key_id given the key descriptor
2340 // tuple comprising domain, namespace, and alias.
2341 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002342 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002343 let alias = key
2344 .alias
2345 .as_ref()
2346 .map_or_else(|| Err(KsError::sys()), Ok)
2347 .context("In load_key_entry_id: Alias must be specified.")?;
2348 let mut stmt = tx
2349 .prepare(
2350 "SELECT id FROM persistent.keyentry
2351 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002352 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002353 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002354 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002355 AND alias = ?
2356 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002357 )
2358 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2359 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002360 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002361 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002362 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002363 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002364 .get(0)
2365 .context("Failed to unpack id.")
2366 })
2367 .context("In load_key_entry_id.")
2368 }
2369
2370 /// This helper function completes the access tuple of a key, which is required
2371 /// to perform access control. The strategy depends on the `domain` field in the
2372 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002373 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002374 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002375 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002376 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002377 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002378 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002379 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002380 /// `namespace`.
2381 /// In each case the information returned is sufficient to perform the access
2382 /// check and the key id can be used to load further key artifacts.
2383 fn load_access_tuple(
2384 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002385 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002386 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002387 caller_uid: u32,
2388 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2389 match key.domain {
2390 // Domain App or SELinux. In this case we load the key_id from
2391 // the keyentry database for further loading of key components.
2392 // We already have the full access tuple to perform access control.
2393 // The only distinction is that we use the caller_uid instead
2394 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002395 // Domain::APP.
2396 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002397 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002398 if access_key.domain == Domain::APP {
2399 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002400 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002401 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002402 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002403
2404 Ok((key_id, access_key, None))
2405 }
2406
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002407 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002409 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002410 let mut stmt = tx
2411 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002412 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002413 WHERE grantee = ? AND id = ? AND
2414 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002415 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002416 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002417 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002418 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419 .context("Domain:Grant: query failed.")?;
2420 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002421 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002422 let r =
2423 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002424 Ok((
2425 r.get(0).context("Failed to unpack key_id.")?,
2426 r.get(1).context("Failed to unpack access_vector.")?,
2427 ))
2428 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002429 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002430 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002431 }
2432
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002433 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002434 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002435 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002436 let (domain, namespace): (Domain, i64) = {
2437 let mut stmt = tx
2438 .prepare(
2439 "SELECT domain, namespace FROM persistent.keyentry
2440 WHERE
2441 id = ?
2442 AND state = ?;",
2443 )
2444 .context("Domain::KEY_ID: prepare statement failed")?;
2445 let mut rows = stmt
2446 .query(params![key.nspace, KeyLifeCycle::Live])
2447 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002448 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002449 let r =
2450 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002451 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002452 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002453 r.get(1).context("Failed to unpack namespace.")?,
2454 ))
2455 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002456 .context("Domain::KEY_ID.")?
2457 };
2458
2459 // We may use a key by id after loading it by grant.
2460 // In this case we have to check if the caller has a grant for this particular
2461 // key. We can skip this if we already know that the caller is the owner.
2462 // But we cannot know this if domain is anything but App. E.g. in the case
2463 // of Domain::SELINUX we have to speculatively check for grants because we have to
2464 // consult the SEPolicy before we know if the caller is the owner.
2465 let access_vector: Option<KeyPermSet> =
2466 if domain != Domain::APP || namespace != caller_uid as i64 {
2467 let access_vector: Option<i32> = tx
2468 .query_row(
2469 "SELECT access_vector FROM persistent.grant
2470 WHERE grantee = ? AND keyentryid = ?;",
2471 params![caller_uid as i64, key.nspace],
2472 |row| row.get(0),
2473 )
2474 .optional()
2475 .context("Domain::KEY_ID: query grant failed.")?;
2476 access_vector.map(|p| p.into())
2477 } else {
2478 None
2479 };
2480
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002481 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002482 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002483 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002484 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002485
Janis Danisevskis45760022021-01-19 16:34:10 -08002486 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002487 }
2488 _ => Err(anyhow!(KsError::sys())),
2489 }
2490 }
2491
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002492 fn load_blob_components(
2493 key_id: i64,
2494 load_bits: KeyEntryLoadBits,
2495 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002496 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002497 let mut stmt = tx
2498 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002499 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002500 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2501 )
2502 .context("In load_blob_components: prepare statement failed.")?;
2503
2504 let mut rows =
2505 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2506
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002507 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002508 let mut cert_blob: Option<Vec<u8>> = None;
2509 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002510 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002511 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002512 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002513 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002514 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002515 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2516 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002517 key_blob = Some((
2518 row.get(0).context("Failed to extract key blob id.")?,
2519 row.get(2).context("Failed to extract key blob.")?,
2520 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002521 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002522 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002523 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002524 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002525 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002526 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002527 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002528 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002529 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002530 (SubComponentType::CERT, _, _)
2531 | (SubComponentType::CERT_CHAIN, _, _)
2532 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002533 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2534 }
2535 Ok(())
2536 })
2537 .context("In load_blob_components.")?;
2538
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002539 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2540 Ok(Some((
2541 blob,
2542 BlobMetaData::load_from_db(blob_id, tx)
2543 .context("In load_blob_components: Trying to load blob_metadata.")?,
2544 )))
2545 })?;
2546
2547 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002548 }
2549
2550 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2551 let mut stmt = tx
2552 .prepare(
2553 "SELECT tag, data, security_level from persistent.keyparameter
2554 WHERE keyentryid = ?;",
2555 )
2556 .context("In load_key_parameters: prepare statement failed.")?;
2557
2558 let mut parameters: Vec<KeyParameter> = Vec::new();
2559
2560 let mut rows =
2561 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002562 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002563 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2564 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002565 parameters.push(
2566 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2567 .context("Failed to read KeyParameter.")?,
2568 );
2569 Ok(())
2570 })
2571 .context("In load_key_parameters.")?;
2572
2573 Ok(parameters)
2574 }
2575
Qi Wub9433b52020-12-01 14:52:46 +08002576 /// Decrements the usage count of a limited use key. This function first checks whether the
2577 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2578 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2579 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002580 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002581 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2582
Qi Wub9433b52020-12-01 14:52:46 +08002583 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2584 let limit: Option<i32> = tx
2585 .query_row(
2586 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2587 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2588 |row| row.get(0),
2589 )
2590 .optional()
2591 .context("Trying to load usage count")?;
2592
2593 let limit = limit
2594 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2595 .context("The Key no longer exists. Key is exhausted.")?;
2596
2597 tx.execute(
2598 "UPDATE persistent.keyparameter
2599 SET data = data - 1
2600 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2601 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2602 )
2603 .context("Failed to update key usage count.")?;
2604
2605 match limit {
2606 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002607 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002608 .context("Trying to mark limited use key for deletion."),
2609 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002610 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002611 }
2612 })
2613 .context("In check_and_update_key_usage_count.")
2614 }
2615
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002616 /// Load a key entry by the given key descriptor.
2617 /// It uses the `check_permission` callback to verify if the access is allowed
2618 /// given the key access tuple read from the database using `load_access_tuple`.
2619 /// With `load_bits` the caller may specify which blobs shall be loaded from
2620 /// the blob database.
2621 pub fn load_key_entry(
2622 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002623 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002624 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002625 load_bits: KeyEntryLoadBits,
2626 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002627 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2628 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002629 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2630
Janis Danisevskis66784c42021-01-27 08:40:25 -08002631 loop {
2632 match self.load_key_entry_internal(
2633 key,
2634 key_type,
2635 load_bits,
2636 caller_uid,
2637 &check_permission,
2638 ) {
2639 Ok(result) => break Ok(result),
2640 Err(e) => {
2641 if Self::is_locked_error(&e) {
2642 std::thread::sleep(std::time::Duration::from_micros(500));
2643 continue;
2644 } else {
2645 return Err(e).context("In load_key_entry.");
2646 }
2647 }
2648 }
2649 }
2650 }
2651
2652 fn load_key_entry_internal(
2653 &mut self,
2654 key: &KeyDescriptor,
2655 key_type: KeyType,
2656 load_bits: KeyEntryLoadBits,
2657 caller_uid: u32,
2658 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002659 ) -> Result<(KeyIdGuard, KeyEntry)> {
2660 // KEY ID LOCK 1/2
2661 // If we got a key descriptor with a key id we can get the lock right away.
2662 // Otherwise we have to defer it until we know the key id.
2663 let key_id_guard = match key.domain {
2664 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2665 _ => None,
2666 };
2667
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002668 let tx = self
2669 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002670 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002671 .context("In load_key_entry: Failed to initialize transaction.")?;
2672
2673 // Load the key_id and complete the access control tuple.
2674 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002675 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2676 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002677
2678 // Perform access control. It is vital that we return here if the permission is denied.
2679 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002680 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002681
Janis Danisevskisaec14592020-11-12 09:41:49 -08002682 // KEY ID LOCK 2/2
2683 // If we did not get a key id lock by now, it was because we got a key descriptor
2684 // without a key id. At this point we got the key id, so we can try and get a lock.
2685 // However, we cannot block here, because we are in the middle of the transaction.
2686 // So first we try to get the lock non blocking. If that fails, we roll back the
2687 // transaction and block until we get the lock. After we successfully got the lock,
2688 // we start a new transaction and load the access tuple again.
2689 //
2690 // We don't need to perform access control again, because we already established
2691 // that the caller had access to the given key. But we need to make sure that the
2692 // key id still exists. So we have to load the key entry by key id this time.
2693 let (key_id_guard, tx) = match key_id_guard {
2694 None => match KEY_ID_LOCK.try_get(key_id) {
2695 None => {
2696 // Roll back the transaction.
2697 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002698
Janis Danisevskisaec14592020-11-12 09:41:49 -08002699 // Block until we have a key id lock.
2700 let key_id_guard = KEY_ID_LOCK.get(key_id);
2701
2702 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002703 let tx = self
2704 .conn
2705 .unchecked_transaction()
2706 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002707
2708 Self::load_access_tuple(
2709 &tx,
2710 // This time we have to load the key by the retrieved key id, because the
2711 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002712 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002713 domain: Domain::KEY_ID,
2714 nspace: key_id,
2715 ..Default::default()
2716 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002717 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002718 caller_uid,
2719 )
2720 .context("In load_key_entry. (deferred key lock)")?;
2721 (key_id_guard, tx)
2722 }
2723 Some(l) => (l, tx),
2724 },
2725 Some(key_id_guard) => (key_id_guard, tx),
2726 };
2727
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002728 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2729 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002730
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002731 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2732
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002733 Ok((key_id_guard, key_entry))
2734 }
2735
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002736 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002737 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002738 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2739 .context("Trying to delete keyentry.")?;
2740 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2741 .context("Trying to delete keymetadata.")?;
2742 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2743 .context("Trying to delete keyparameters.")?;
2744 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2745 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002746 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002747 }
2748
2749 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002750 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002751 pub fn unbind_key(
2752 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002753 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002754 key_type: KeyType,
2755 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002756 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002757 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002758 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2759
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002760 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2761 let (key_id, access_key_descriptor, access_vector) =
2762 Self::load_access_tuple(tx, key, key_type, caller_uid)
2763 .context("Trying to get access tuple.")?;
2764
2765 // Perform access control. It is vital that we return here if the permission is denied.
2766 // So do not touch that '?' at the end.
2767 check_permission(&access_key_descriptor, access_vector)
2768 .context("While checking permission.")?;
2769
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002770 Self::mark_unreferenced(tx, key_id)
2771 .map(|need_gc| (need_gc, ()))
2772 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002773 })
2774 .context("In unbind_key.")
2775 }
2776
Max Bires8e93d2b2021-01-14 13:17:59 -08002777 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2778 tx.query_row(
2779 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2780 params![key_id],
2781 |row| row.get(0),
2782 )
2783 .context("In get_key_km_uuid.")
2784 }
2785
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002786 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2787 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2788 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002789 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2790
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002791 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2792 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2793 .context("In unbind_keys_for_namespace.");
2794 }
2795 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2796 tx.execute(
2797 "DELETE FROM persistent.keymetadata
2798 WHERE keyentryid IN (
2799 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002800 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002801 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002802 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002803 )
2804 .context("Trying to delete keymetadata.")?;
2805 tx.execute(
2806 "DELETE FROM persistent.keyparameter
2807 WHERE keyentryid IN (
2808 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002809 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002810 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002811 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002812 )
2813 .context("Trying to delete keyparameters.")?;
2814 tx.execute(
2815 "DELETE FROM persistent.grant
2816 WHERE keyentryid IN (
2817 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002818 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002819 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002820 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002821 )
2822 .context("Trying to delete grants.")?;
2823 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002824 "DELETE FROM persistent.keyentry
2825 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2826 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002827 )
2828 .context("Trying to delete keyentry.")?;
2829 Ok(()).need_gc()
2830 })
2831 .context("In unbind_keys_for_namespace")
2832 }
2833
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002834 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2835 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2836 {
2837 tx.execute(
2838 "DELETE FROM persistent.keymetadata
2839 WHERE keyentryid IN (
2840 SELECT id FROM persistent.keyentry
2841 WHERE state = ?
2842 );",
2843 params![KeyLifeCycle::Unreferenced],
2844 )
2845 .context("Trying to delete keymetadata.")?;
2846 tx.execute(
2847 "DELETE FROM persistent.keyparameter
2848 WHERE keyentryid IN (
2849 SELECT id FROM persistent.keyentry
2850 WHERE state = ?
2851 );",
2852 params![KeyLifeCycle::Unreferenced],
2853 )
2854 .context("Trying to delete keyparameters.")?;
2855 tx.execute(
2856 "DELETE FROM persistent.grant
2857 WHERE keyentryid IN (
2858 SELECT id FROM persistent.keyentry
2859 WHERE state = ?
2860 );",
2861 params![KeyLifeCycle::Unreferenced],
2862 )
2863 .context("Trying to delete grants.")?;
2864 tx.execute(
2865 "DELETE FROM persistent.keyentry
2866 WHERE state = ?;",
2867 params![KeyLifeCycle::Unreferenced],
2868 )
2869 .context("Trying to delete keyentry.")?;
2870 Result::<()>::Ok(())
2871 }
2872 .context("In cleanup_unreferenced")
2873 }
2874
Hasini Gunasingheda895552021-01-27 19:34:37 +00002875 /// Delete the keys created on behalf of the user, denoted by the user id.
2876 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2877 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2878 /// The caller of this function should notify the gc if the returned value is true.
2879 pub fn unbind_keys_for_user(
2880 &mut self,
2881 user_id: u32,
2882 keep_non_super_encrypted_keys: bool,
2883 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002884 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2885
Hasini Gunasingheda895552021-01-27 19:34:37 +00002886 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2887 let mut stmt = tx
2888 .prepare(&format!(
2889 "SELECT id from persistent.keyentry
2890 WHERE (
2891 key_type = ?
2892 AND domain = ?
2893 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2894 AND state = ?
2895 ) OR (
2896 key_type = ?
2897 AND namespace = ?
2898 AND alias = ?
2899 AND state = ?
2900 );",
2901 aid_user_offset = AID_USER_OFFSET
2902 ))
2903 .context(concat!(
2904 "In unbind_keys_for_user. ",
2905 "Failed to prepare the query to find the keys created by apps."
2906 ))?;
2907
2908 let mut rows = stmt
2909 .query(params![
2910 // WHERE client key:
2911 KeyType::Client,
2912 Domain::APP.0 as u32,
2913 user_id,
2914 KeyLifeCycle::Live,
2915 // OR super key:
2916 KeyType::Super,
2917 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002918 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002919 KeyLifeCycle::Live
2920 ])
2921 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2922
2923 let mut key_ids: Vec<i64> = Vec::new();
2924 db_utils::with_rows_extract_all(&mut rows, |row| {
2925 key_ids
2926 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2927 Ok(())
2928 })
2929 .context("In unbind_keys_for_user.")?;
2930
2931 let mut notify_gc = false;
2932 for key_id in key_ids {
2933 if keep_non_super_encrypted_keys {
2934 // Load metadata and filter out non-super-encrypted keys.
2935 if let (_, Some((_, blob_metadata)), _, _) =
2936 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2937 .context("In unbind_keys_for_user: Trying to load blob info.")?
2938 {
2939 if blob_metadata.encrypted_by().is_none() {
2940 continue;
2941 }
2942 }
2943 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002944 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002945 .context("In unbind_keys_for_user.")?
2946 || notify_gc;
2947 }
2948 Ok(()).do_gc(notify_gc)
2949 })
2950 .context("In unbind_keys_for_user.")
2951 }
2952
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002953 fn load_key_components(
2954 tx: &Transaction,
2955 load_bits: KeyEntryLoadBits,
2956 key_id: i64,
2957 ) -> Result<KeyEntry> {
2958 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2959
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002960 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002961 Self::load_blob_components(key_id, load_bits, &tx)
2962 .context("In load_key_components.")?;
2963
Max Bires8e93d2b2021-01-14 13:17:59 -08002964 let parameters = Self::load_key_parameters(key_id, &tx)
2965 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002966
Max Bires8e93d2b2021-01-14 13:17:59 -08002967 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2968 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002969
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002970 Ok(KeyEntry {
2971 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002972 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002973 cert: cert_blob,
2974 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002975 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002976 parameters,
2977 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002978 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002979 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002980 }
2981
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002982 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2983 /// The key descriptors will have the domain, nspace, and alias field set.
2984 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07002985 pub fn list(
2986 &mut self,
2987 domain: Domain,
2988 namespace: i64,
2989 key_type: KeyType,
2990 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002991 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2992
Janis Danisevskis66784c42021-01-27 08:40:25 -08002993 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2994 let mut stmt = tx
2995 .prepare(
2996 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002997 WHERE domain = ?
2998 AND namespace = ?
2999 AND alias IS NOT NULL
3000 AND state = ?
3001 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003002 )
3003 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003004
Janis Danisevskis66784c42021-01-27 08:40:25 -08003005 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003006 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08003007 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003008
Janis Danisevskis66784c42021-01-27 08:40:25 -08003009 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3010 db_utils::with_rows_extract_all(&mut rows, |row| {
3011 descriptors.push(KeyDescriptor {
3012 domain,
3013 nspace: namespace,
3014 alias: Some(row.get(0).context("Trying to extract alias.")?),
3015 blob: None,
3016 });
3017 Ok(())
3018 })
3019 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003020 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003021 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003022 }
3023
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003024 /// Adds a grant to the grant table.
3025 /// Like `load_key_entry` this function loads the access tuple before
3026 /// it uses the callback for a permission check. Upon success,
3027 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3028 /// grant table. The new row will have a randomized id, which is used as
3029 /// grant id in the namespace field of the resulting KeyDescriptor.
3030 pub fn grant(
3031 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003032 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003033 caller_uid: u32,
3034 grantee_uid: u32,
3035 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003036 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003037 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003038 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3039
Janis Danisevskis66784c42021-01-27 08:40:25 -08003040 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3041 // Load the key_id and complete the access control tuple.
3042 // We ignore the access vector here because grants cannot be granted.
3043 // The access vector returned here expresses the permissions the
3044 // grantee has if key.domain == Domain::GRANT. But this vector
3045 // cannot include the grant permission by design, so there is no way the
3046 // subsequent permission check can pass.
3047 // We could check key.domain == Domain::GRANT and fail early.
3048 // But even if we load the access tuple by grant here, the permission
3049 // check denies the attempt to create a grant by grant descriptor.
3050 let (key_id, access_key_descriptor, _) =
3051 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3052 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003053
Janis Danisevskis66784c42021-01-27 08:40:25 -08003054 // Perform access control. It is vital that we return here if the permission
3055 // was denied. So do not touch that '?' at the end of the line.
3056 // This permission check checks if the caller has the grant permission
3057 // for the given key and in addition to all of the permissions
3058 // expressed in `access_vector`.
3059 check_permission(&access_key_descriptor, &access_vector)
3060 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003061
Janis Danisevskis66784c42021-01-27 08:40:25 -08003062 let grant_id = if let Some(grant_id) = tx
3063 .query_row(
3064 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003065 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003066 params![key_id, grantee_uid],
3067 |row| row.get(0),
3068 )
3069 .optional()
3070 .context("In grant: Failed get optional existing grant id.")?
3071 {
3072 tx.execute(
3073 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003074 SET access_vector = ?
3075 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003076 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003077 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 .context("In grant: Failed to update existing grant.")?;
3079 grant_id
3080 } else {
3081 Self::insert_with_retry(|id| {
3082 tx.execute(
3083 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3084 VALUES (?, ?, ?, ?);",
3085 params![id, grantee_uid, key_id, i32::from(access_vector)],
3086 )
3087 })
3088 .context("In grant")?
3089 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003090
Janis Danisevskis66784c42021-01-27 08:40:25 -08003091 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003092 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003093 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003094 }
3095
3096 /// This function checks permissions like `grant` and `load_key_entry`
3097 /// before removing a grant from the grant table.
3098 pub fn ungrant(
3099 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003100 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101 caller_uid: u32,
3102 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003103 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003104 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003105 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3106
Janis Danisevskis66784c42021-01-27 08:40:25 -08003107 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3108 // Load the key_id and complete the access control tuple.
3109 // We ignore the access vector here because grants cannot be granted.
3110 let (key_id, access_key_descriptor, _) =
3111 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3112 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003113
Janis Danisevskis66784c42021-01-27 08:40:25 -08003114 // Perform access control. We must return here if the permission
3115 // was denied. So do not touch the '?' at the end of this line.
3116 check_permission(&access_key_descriptor)
3117 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003118
Janis Danisevskis66784c42021-01-27 08:40:25 -08003119 tx.execute(
3120 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003121 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003122 params![key_id, grantee_uid],
3123 )
3124 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003125
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003126 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003127 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003128 }
3129
Joel Galenson845f74b2020-09-09 14:11:55 -07003130 // Generates a random id and passes it to the given function, which will
3131 // try to insert it into a database. If that insertion fails, retry;
3132 // otherwise return the id.
3133 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3134 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003135 let newid: i64 = match random() {
3136 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3137 i => i,
3138 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003139 match inserter(newid) {
3140 // If the id already existed, try again.
3141 Err(rusqlite::Error::SqliteFailure(
3142 libsqlite3_sys::Error {
3143 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3144 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3145 },
3146 _,
3147 )) => (),
3148 Err(e) => {
3149 return Err(e).context("In insert_with_retry: failed to insert into database.")
3150 }
3151 _ => return Ok(newid),
3152 }
3153 }
3154 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003155
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003156 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3157 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3158 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3159 auth_token.clone(),
3160 MonotonicRawTime::now(),
3161 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003162 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003163
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003164 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003165 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003166 where
3167 F: Fn(&AuthTokenEntry) -> bool,
3168 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003169 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003170 }
3171
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003172 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003173 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3174 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003175 }
3176
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003177 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003178 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3179 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003180 }
3181
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003182 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003183 fn get_last_off_body(&self) -> MonotonicRawTime {
3184 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003185 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003186
3187 /// Load descriptor of a key by key id
3188 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3189 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3190
3191 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3192 tx.query_row(
3193 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3194 params![key_id],
3195 |row| {
3196 Ok(KeyDescriptor {
3197 domain: Domain(row.get(0)?),
3198 nspace: row.get(1)?,
3199 alias: row.get(2)?,
3200 blob: None,
3201 })
3202 },
3203 )
3204 .optional()
3205 .context("Trying to load key descriptor")
3206 .no_gc()
3207 })
3208 .context("In load_key_descriptor.")
3209 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003210}
3211
3212#[cfg(test)]
3213mod tests {
3214
3215 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003216 use crate::key_parameter::{
3217 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3218 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3219 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003220 use crate::key_perm_set;
3221 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003222 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003223 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003224 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3225 HardwareAuthToken::HardwareAuthToken,
3226 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003227 };
3228 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003229 Timestamp::Timestamp,
3230 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003231 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003232 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003233 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003234 use std::collections::BTreeMap;
3235 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003236 use std::sync::atomic::{AtomicU8, Ordering};
3237 use std::sync::Arc;
3238 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003239 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003240 #[cfg(disabled)]
3241 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003242
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003243 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003244 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003245
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003246 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003247 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003248 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003249 })?;
3250 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003251 }
3252
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003253 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3254 where
3255 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3256 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003257 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003258
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003259 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003260 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003261
Janis Danisevskis3395f862021-05-06 10:54:17 -07003262 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003263 }
3264
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003265 fn rebind_alias(
3266 db: &mut KeystoreDB,
3267 newid: &KeyIdGuard,
3268 alias: &str,
3269 domain: Domain,
3270 namespace: i64,
3271 ) -> Result<bool> {
3272 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003273 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003274 })
3275 .context("In rebind_alias.")
3276 }
3277
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003278 #[test]
3279 fn datetime() -> Result<()> {
3280 let conn = Connection::open_in_memory()?;
3281 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3282 let now = SystemTime::now();
3283 let duration = Duration::from_secs(1000);
3284 let then = now.checked_sub(duration).unwrap();
3285 let soon = now.checked_add(duration).unwrap();
3286 conn.execute(
3287 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3288 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3289 )?;
3290 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3291 let mut rows = stmt.query(NO_PARAMS)?;
3292 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3293 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3294 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3295 assert!(rows.next()?.is_none());
3296 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3297 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3298 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3299 Ok(())
3300 }
3301
Joel Galenson0891bc12020-07-20 10:37:03 -07003302 // Ensure that we're using the "injected" random function, not the real one.
3303 #[test]
3304 fn test_mocked_random() {
3305 let rand1 = random();
3306 let rand2 = random();
3307 let rand3 = random();
3308 if rand1 == rand2 {
3309 assert_eq!(rand2 + 1, rand3);
3310 } else {
3311 assert_eq!(rand1 + 1, rand2);
3312 assert_eq!(rand2, rand3);
3313 }
3314 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003315
Joel Galenson26f4d012020-07-17 14:57:21 -07003316 // Test that we have the correct tables.
3317 #[test]
3318 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003319 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003320 let tables = db
3321 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003322 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003323 .query_map(params![], |row| row.get(0))?
3324 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003325 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003326 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003327 assert_eq!(tables[1], "blobmetadata");
3328 assert_eq!(tables[2], "grant");
3329 assert_eq!(tables[3], "keyentry");
3330 assert_eq!(tables[4], "keymetadata");
3331 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003332 Ok(())
3333 }
3334
3335 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003336 fn test_auth_token_table_invariant() -> Result<()> {
3337 let mut db = new_test_db()?;
3338 let auth_token1 = HardwareAuthToken {
3339 challenge: i64::MAX,
3340 userId: 200,
3341 authenticatorId: 200,
3342 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3343 timestamp: Timestamp { milliSeconds: 500 },
3344 mac: String::from("mac").into_bytes(),
3345 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003346 db.insert_auth_token(&auth_token1);
3347 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003348 assert_eq!(auth_tokens_returned.len(), 1);
3349
3350 // insert another auth token with the same values for the columns in the UNIQUE constraint
3351 // of the auth token table and different value for timestamp
3352 let auth_token2 = HardwareAuthToken {
3353 challenge: i64::MAX,
3354 userId: 200,
3355 authenticatorId: 200,
3356 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3357 timestamp: Timestamp { milliSeconds: 600 },
3358 mac: String::from("mac").into_bytes(),
3359 };
3360
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003361 db.insert_auth_token(&auth_token2);
3362 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003363 assert_eq!(auth_tokens_returned.len(), 1);
3364
3365 if let Some(auth_token) = auth_tokens_returned.pop() {
3366 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3367 }
3368
3369 // insert another auth token with the different values for the columns in the UNIQUE
3370 // constraint of the auth token table
3371 let auth_token3 = HardwareAuthToken {
3372 challenge: i64::MAX,
3373 userId: 201,
3374 authenticatorId: 200,
3375 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3376 timestamp: Timestamp { milliSeconds: 600 },
3377 mac: String::from("mac").into_bytes(),
3378 };
3379
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003380 db.insert_auth_token(&auth_token3);
3381 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003382 assert_eq!(auth_tokens_returned.len(), 2);
3383
3384 Ok(())
3385 }
3386
3387 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003388 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3389 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003390 }
3391
3392 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003393 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003394 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003395 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003396
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003397 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003398 let entries = get_keyentry(&db)?;
3399 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003400
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003401 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003402
3403 let entries_new = get_keyentry(&db)?;
3404 assert_eq!(entries, entries_new);
3405 Ok(())
3406 }
3407
3408 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003409 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003410 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3411 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003412 }
3413
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003414 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003415
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003416 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3417 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003418
3419 let entries = get_keyentry(&db)?;
3420 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003421 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3422 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003423
3424 // Test that we must pass in a valid Domain.
3425 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003426 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003427 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003428 );
3429 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003430 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003431 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003432 );
3433 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003434 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003435 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003436 );
3437
3438 Ok(())
3439 }
3440
Joel Galenson33c04ad2020-08-03 11:04:38 -07003441 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003442 fn test_add_unsigned_key() -> Result<()> {
3443 let mut db = new_test_db()?;
3444 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3445 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3446 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3447 db.create_attestation_key_entry(
3448 &public_key,
3449 &raw_public_key,
3450 &private_key,
3451 &KEYSTORE_UUID,
3452 )?;
3453 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3454 assert_eq!(keys.len(), 1);
3455 assert_eq!(keys[0], public_key);
3456 Ok(())
3457 }
3458
3459 #[test]
3460 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3461 let mut db = new_test_db()?;
3462 let expiration_date: i64 = 20;
3463 let namespace: i64 = 30;
3464 let base_byte: u8 = 1;
3465 let loaded_values =
3466 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3467 let chain =
3468 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3469 assert_eq!(true, chain.is_some());
3470 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003471 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003472 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3473 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003474 Ok(())
3475 }
3476
3477 #[test]
3478 fn test_get_attestation_pool_status() -> Result<()> {
3479 let mut db = new_test_db()?;
3480 let namespace: i64 = 30;
3481 load_attestation_key_pool(
3482 &mut db, 10, /* expiration */
3483 namespace, 0x01, /* base_byte */
3484 )?;
3485 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3486 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3487 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3488 assert_eq!(status.expiring, 0);
3489 assert_eq!(status.attested, 3);
3490 assert_eq!(status.unassigned, 0);
3491 assert_eq!(status.total, 3);
3492 assert_eq!(
3493 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3494 1
3495 );
3496 assert_eq!(
3497 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3498 2
3499 );
3500 assert_eq!(
3501 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3502 3
3503 );
3504 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3505 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3506 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3507 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003508 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003509 db.create_attestation_key_entry(
3510 &public_key,
3511 &raw_public_key,
3512 &private_key,
3513 &KEYSTORE_UUID,
3514 )?;
3515 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3516 assert_eq!(status.attested, 3);
3517 assert_eq!(status.unassigned, 0);
3518 assert_eq!(status.total, 4);
3519 db.store_signed_attestation_certificate_chain(
3520 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003521 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003522 &cert_chain,
3523 20,
3524 &KEYSTORE_UUID,
3525 )?;
3526 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3527 assert_eq!(status.attested, 4);
3528 assert_eq!(status.unassigned, 1);
3529 assert_eq!(status.total, 4);
3530 Ok(())
3531 }
3532
3533 #[test]
3534 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003535 let temp_dir =
3536 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3537 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003538 let expiration_date: i64 =
3539 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3540 let namespace: i64 = 30;
3541 let namespace_del1: i64 = 45;
3542 let namespace_del2: i64 = 60;
3543 let entry_values = load_attestation_key_pool(
3544 &mut db,
3545 expiration_date,
3546 namespace,
3547 0x01, /* base_byte */
3548 )?;
3549 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3550 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003551
3552 let blob_entry_row_count: u32 = db
3553 .conn
3554 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3555 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003556 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3557 // one key, one certificate chain, and one certificate.
3558 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003559
Max Bires2b2e6562020-09-22 11:22:36 -07003560 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3561
3562 let mut cert_chain =
3563 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003564 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003565 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003566 assert_eq!(entry_values.batch_cert, value.batch_cert);
3567 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003568 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003569
3570 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3571 Domain::APP,
3572 namespace_del1,
3573 &KEYSTORE_UUID,
3574 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003575 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003576 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3577 Domain::APP,
3578 namespace_del2,
3579 &KEYSTORE_UUID,
3580 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003581 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003582
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003583 // Give the garbage collector half a second to catch up.
3584 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003585
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003586 let blob_entry_row_count: u32 = db
3587 .conn
3588 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3589 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003590 // There shound be 3 blob entries left, because we deleted two of the attestation
3591 // key entries with three blobs each.
3592 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003593
Max Bires2b2e6562020-09-22 11:22:36 -07003594 Ok(())
3595 }
3596
3597 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003598 fn test_delete_all_attestation_keys() -> Result<()> {
3599 let mut db = new_test_db()?;
3600 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3601 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003602 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003603 let result = db.delete_all_attestation_keys()?;
3604
3605 // Give the garbage collector half a second to catch up.
3606 std::thread::sleep(Duration::from_millis(500));
3607
3608 // Attestation keys should be deleted, and the regular key should remain.
3609 assert_eq!(result, 2);
3610
3611 Ok(())
3612 }
3613
3614 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003615 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003616 fn extractor(
3617 ke: &KeyEntryRow,
3618 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3619 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003620 }
3621
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003622 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003623 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3624 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003625 let entries = get_keyentry(&db)?;
3626 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003627 assert_eq!(
3628 extractor(&entries[0]),
3629 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3630 );
3631 assert_eq!(
3632 extractor(&entries[1]),
3633 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3634 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003635
3636 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003637 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003638 let entries = get_keyentry(&db)?;
3639 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003640 assert_eq!(
3641 extractor(&entries[0]),
3642 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3643 );
3644 assert_eq!(
3645 extractor(&entries[1]),
3646 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3647 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003648
3649 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003650 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003651 let entries = get_keyentry(&db)?;
3652 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003653 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3654 assert_eq!(
3655 extractor(&entries[1]),
3656 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3657 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003658
3659 // Test that we must pass in a valid Domain.
3660 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003661 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003662 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003663 );
3664 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003665 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003666 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003667 );
3668 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003669 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003670 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003671 );
3672
3673 // Test that we correctly handle setting an alias for something that does not exist.
3674 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003675 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003676 "Expected to update a single entry but instead updated 0",
3677 );
3678 // Test that we correctly abort the transaction in this case.
3679 let entries = get_keyentry(&db)?;
3680 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003681 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3682 assert_eq!(
3683 extractor(&entries[1]),
3684 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3685 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003686
3687 Ok(())
3688 }
3689
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003690 #[test]
3691 fn test_grant_ungrant() -> Result<()> {
3692 const CALLER_UID: u32 = 15;
3693 const GRANTEE_UID: u32 = 12;
3694 const SELINUX_NAMESPACE: i64 = 7;
3695
3696 let mut db = new_test_db()?;
3697 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003698 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3699 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3700 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003701 )?;
3702 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003703 domain: super::Domain::APP,
3704 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003705 alias: Some("key".to_string()),
3706 blob: None,
3707 };
3708 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3709 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3710
3711 // Reset totally predictable random number generator in case we
3712 // are not the first test running on this thread.
3713 reset_random();
3714 let next_random = 0i64;
3715
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003716 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003717 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003718 assert_eq!(*a, PVEC1);
3719 assert_eq!(
3720 *k,
3721 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003722 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003723 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003724 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725 alias: Some("key".to_string()),
3726 blob: None,
3727 }
3728 );
3729 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003730 })
3731 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003732
3733 assert_eq!(
3734 app_granted_key,
3735 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003736 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003737 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003738 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003739 alias: None,
3740 blob: None,
3741 }
3742 );
3743
3744 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003745 domain: super::Domain::SELINUX,
3746 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003747 alias: Some("yek".to_string()),
3748 blob: None,
3749 };
3750
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003751 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003752 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003753 assert_eq!(*a, PVEC1);
3754 assert_eq!(
3755 *k,
3756 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003757 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003758 // namespace must be the supplied SELinux
3759 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003760 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003761 alias: Some("yek".to_string()),
3762 blob: None,
3763 }
3764 );
3765 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003766 })
3767 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003768
3769 assert_eq!(
3770 selinux_granted_key,
3771 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003772 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003773 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003774 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775 alias: None,
3776 blob: None,
3777 }
3778 );
3779
3780 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003781 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003782 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003783 assert_eq!(*a, PVEC2);
3784 assert_eq!(
3785 *k,
3786 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003787 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003788 // namespace must be the supplied SELinux
3789 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003790 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003791 alias: Some("yek".to_string()),
3792 blob: None,
3793 }
3794 );
3795 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003796 })
3797 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003798
3799 assert_eq!(
3800 selinux_granted_key,
3801 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003802 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003803 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003804 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003805 alias: None,
3806 blob: None,
3807 }
3808 );
3809
3810 {
3811 // Limiting scope of stmt, because it borrows db.
3812 let mut stmt = db
3813 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003814 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003815 let mut rows =
3816 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3817 Ok((
3818 row.get(0)?,
3819 row.get(1)?,
3820 row.get(2)?,
3821 KeyPermSet::from(row.get::<_, i32>(3)?),
3822 ))
3823 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003824
3825 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003826 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003827 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003828 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003829 assert!(rows.next().is_none());
3830 }
3831
3832 debug_dump_keyentry_table(&mut db)?;
3833 println!("app_key {:?}", app_key);
3834 println!("selinux_key {:?}", selinux_key);
3835
Janis Danisevskis66784c42021-01-27 08:40:25 -08003836 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3837 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003838
3839 Ok(())
3840 }
3841
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003842 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003843 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3844 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3845
3846 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003847 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003848 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003849 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003850 let mut blob_metadata = BlobMetaData::new();
3851 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3852 db.set_blob(
3853 &key_id,
3854 SubComponentType::KEY_BLOB,
3855 Some(TEST_KEY_BLOB),
3856 Some(&blob_metadata),
3857 )?;
3858 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3859 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003860 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003861
3862 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003863 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003864 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003865 )?;
3866 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003867 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3868 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003869 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003870 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003871 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003872 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003873 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003874 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003875 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003876
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003877 drop(rows);
3878 drop(stmt);
3879
3880 assert_eq!(
3881 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3882 BlobMetaData::load_from_db(id, tx).no_gc()
3883 })
3884 .expect("Should find blob metadata."),
3885 blob_metadata
3886 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003887 Ok(())
3888 }
3889
3890 static TEST_ALIAS: &str = "my super duper key";
3891
3892 #[test]
3893 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3894 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003895 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003896 .context("test_insert_and_load_full_keyentry_domain_app")?
3897 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003898 let (_key_guard, key_entry) = db
3899 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003900 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003901 domain: Domain::APP,
3902 nspace: 0,
3903 alias: Some(TEST_ALIAS.to_string()),
3904 blob: None,
3905 },
3906 KeyType::Client,
3907 KeyEntryLoadBits::BOTH,
3908 1,
3909 |_k, _av| Ok(()),
3910 )
3911 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003912 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003913
3914 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003915 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003916 domain: Domain::APP,
3917 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003918 alias: Some(TEST_ALIAS.to_string()),
3919 blob: None,
3920 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003921 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003922 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003923 |_, _| Ok(()),
3924 )
3925 .unwrap();
3926
3927 assert_eq!(
3928 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3929 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003930 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003931 domain: Domain::APP,
3932 nspace: 0,
3933 alias: Some(TEST_ALIAS.to_string()),
3934 blob: None,
3935 },
3936 KeyType::Client,
3937 KeyEntryLoadBits::NONE,
3938 1,
3939 |_k, _av| Ok(()),
3940 )
3941 .unwrap_err()
3942 .root_cause()
3943 .downcast_ref::<KsError>()
3944 );
3945
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003946 Ok(())
3947 }
3948
3949 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003950 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3951 let mut db = new_test_db()?;
3952
3953 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003954 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003955 domain: Domain::APP,
3956 nspace: 1,
3957 alias: Some(TEST_ALIAS.to_string()),
3958 blob: None,
3959 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003960 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003961 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003962 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003963 )
3964 .expect("Trying to insert cert.");
3965
3966 let (_key_guard, mut key_entry) = db
3967 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003968 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003969 domain: Domain::APP,
3970 nspace: 1,
3971 alias: Some(TEST_ALIAS.to_string()),
3972 blob: None,
3973 },
3974 KeyType::Client,
3975 KeyEntryLoadBits::PUBLIC,
3976 1,
3977 |_k, _av| Ok(()),
3978 )
3979 .expect("Trying to read certificate entry.");
3980
3981 assert!(key_entry.pure_cert());
3982 assert!(key_entry.cert().is_none());
3983 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3984
3985 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003986 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003987 domain: Domain::APP,
3988 nspace: 1,
3989 alias: Some(TEST_ALIAS.to_string()),
3990 blob: None,
3991 },
3992 KeyType::Client,
3993 1,
3994 |_, _| Ok(()),
3995 )
3996 .unwrap();
3997
3998 assert_eq!(
3999 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4000 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004001 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004002 domain: Domain::APP,
4003 nspace: 1,
4004 alias: Some(TEST_ALIAS.to_string()),
4005 blob: None,
4006 },
4007 KeyType::Client,
4008 KeyEntryLoadBits::NONE,
4009 1,
4010 |_k, _av| Ok(()),
4011 )
4012 .unwrap_err()
4013 .root_cause()
4014 .downcast_ref::<KsError>()
4015 );
4016
4017 Ok(())
4018 }
4019
4020 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004021 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4022 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004023 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004024 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4025 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004026 let (_key_guard, key_entry) = db
4027 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004028 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004029 domain: Domain::SELINUX,
4030 nspace: 1,
4031 alias: Some(TEST_ALIAS.to_string()),
4032 blob: None,
4033 },
4034 KeyType::Client,
4035 KeyEntryLoadBits::BOTH,
4036 1,
4037 |_k, _av| Ok(()),
4038 )
4039 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004040 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004041
4042 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004043 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004044 domain: Domain::SELINUX,
4045 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004046 alias: Some(TEST_ALIAS.to_string()),
4047 blob: None,
4048 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004049 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004050 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004051 |_, _| Ok(()),
4052 )
4053 .unwrap();
4054
4055 assert_eq!(
4056 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4057 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004058 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004059 domain: Domain::SELINUX,
4060 nspace: 1,
4061 alias: Some(TEST_ALIAS.to_string()),
4062 blob: None,
4063 },
4064 KeyType::Client,
4065 KeyEntryLoadBits::NONE,
4066 1,
4067 |_k, _av| Ok(()),
4068 )
4069 .unwrap_err()
4070 .root_cause()
4071 .downcast_ref::<KsError>()
4072 );
4073
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004074 Ok(())
4075 }
4076
4077 #[test]
4078 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4079 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004080 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004081 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4082 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004083 let (_, key_entry) = db
4084 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004085 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004086 KeyType::Client,
4087 KeyEntryLoadBits::BOTH,
4088 1,
4089 |_k, _av| Ok(()),
4090 )
4091 .unwrap();
4092
Qi Wub9433b52020-12-01 14:52:46 +08004093 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004094
4095 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004096 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004097 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004098 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004099 |_, _| Ok(()),
4100 )
4101 .unwrap();
4102
4103 assert_eq!(
4104 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4105 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004106 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004107 KeyType::Client,
4108 KeyEntryLoadBits::NONE,
4109 1,
4110 |_k, _av| Ok(()),
4111 )
4112 .unwrap_err()
4113 .root_cause()
4114 .downcast_ref::<KsError>()
4115 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004116
4117 Ok(())
4118 }
4119
4120 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004121 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4122 let mut db = new_test_db()?;
4123 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4124 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4125 .0;
4126 // Update the usage count of the limited use key.
4127 db.check_and_update_key_usage_count(key_id)?;
4128
4129 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004130 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004131 KeyType::Client,
4132 KeyEntryLoadBits::BOTH,
4133 1,
4134 |_k, _av| Ok(()),
4135 )?;
4136
4137 // The usage count is decremented now.
4138 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4139
4140 Ok(())
4141 }
4142
4143 #[test]
4144 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4145 let mut db = new_test_db()?;
4146 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4147 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4148 .0;
4149 // Update the usage count of the limited use key.
4150 db.check_and_update_key_usage_count(key_id).expect(concat!(
4151 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4152 "This should succeed."
4153 ));
4154
4155 // Try to update the exhausted limited use key.
4156 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4157 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4158 "This should fail."
4159 ));
4160 assert_eq!(
4161 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4162 e.root_cause().downcast_ref::<KsError>().unwrap()
4163 );
4164
4165 Ok(())
4166 }
4167
4168 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004169 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4170 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004171 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004172 .context("test_insert_and_load_full_keyentry_from_grant")?
4173 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004174
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004175 let granted_key = db
4176 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004177 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004178 domain: Domain::APP,
4179 nspace: 0,
4180 alias: Some(TEST_ALIAS.to_string()),
4181 blob: None,
4182 },
4183 1,
4184 2,
4185 key_perm_set![KeyPerm::use_()],
4186 |_k, _av| Ok(()),
4187 )
4188 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004189
4190 debug_dump_grant_table(&mut db)?;
4191
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004192 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004193 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4194 assert_eq!(Domain::GRANT, k.domain);
4195 assert!(av.unwrap().includes(KeyPerm::use_()));
4196 Ok(())
4197 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004198 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004199
Qi Wub9433b52020-12-01 14:52:46 +08004200 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004201
Janis Danisevskis66784c42021-01-27 08:40:25 -08004202 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004203
4204 assert_eq!(
4205 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4206 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004207 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004208 KeyType::Client,
4209 KeyEntryLoadBits::NONE,
4210 2,
4211 |_k, _av| Ok(()),
4212 )
4213 .unwrap_err()
4214 .root_cause()
4215 .downcast_ref::<KsError>()
4216 );
4217
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004218 Ok(())
4219 }
4220
Janis Danisevskis45760022021-01-19 16:34:10 -08004221 // This test attempts to load a key by key id while the caller is not the owner
4222 // but a grant exists for the given key and the caller.
4223 #[test]
4224 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4225 let mut db = new_test_db()?;
4226 const OWNER_UID: u32 = 1u32;
4227 const GRANTEE_UID: u32 = 2u32;
4228 const SOMEONE_ELSE_UID: u32 = 3u32;
4229 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4230 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4231 .0;
4232
4233 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004234 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004235 domain: Domain::APP,
4236 nspace: 0,
4237 alias: Some(TEST_ALIAS.to_string()),
4238 blob: None,
4239 },
4240 OWNER_UID,
4241 GRANTEE_UID,
4242 key_perm_set![KeyPerm::use_()],
4243 |_k, _av| Ok(()),
4244 )
4245 .unwrap();
4246
4247 debug_dump_grant_table(&mut db)?;
4248
4249 let id_descriptor =
4250 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4251
4252 let (_, key_entry) = db
4253 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004254 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004255 KeyType::Client,
4256 KeyEntryLoadBits::BOTH,
4257 GRANTEE_UID,
4258 |k, av| {
4259 assert_eq!(Domain::APP, k.domain);
4260 assert_eq!(OWNER_UID as i64, k.nspace);
4261 assert!(av.unwrap().includes(KeyPerm::use_()));
4262 Ok(())
4263 },
4264 )
4265 .unwrap();
4266
4267 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4268
4269 let (_, key_entry) = db
4270 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004271 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004272 KeyType::Client,
4273 KeyEntryLoadBits::BOTH,
4274 SOMEONE_ELSE_UID,
4275 |k, av| {
4276 assert_eq!(Domain::APP, k.domain);
4277 assert_eq!(OWNER_UID as i64, k.nspace);
4278 assert!(av.is_none());
4279 Ok(())
4280 },
4281 )
4282 .unwrap();
4283
4284 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4285
Janis Danisevskis66784c42021-01-27 08:40:25 -08004286 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004287
4288 assert_eq!(
4289 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4290 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004291 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004292 KeyType::Client,
4293 KeyEntryLoadBits::NONE,
4294 GRANTEE_UID,
4295 |_k, _av| Ok(()),
4296 )
4297 .unwrap_err()
4298 .root_cause()
4299 .downcast_ref::<KsError>()
4300 );
4301
4302 Ok(())
4303 }
4304
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004305 // Creates a key migrates it to a different location and then tries to access it by the old
4306 // and new location.
4307 #[test]
4308 fn test_migrate_key_app_to_app() -> Result<()> {
4309 let mut db = new_test_db()?;
4310 const SOURCE_UID: u32 = 1u32;
4311 const DESTINATION_UID: u32 = 2u32;
4312 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4313 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4314 let key_id_guard =
4315 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4316 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4317
4318 let source_descriptor: KeyDescriptor = KeyDescriptor {
4319 domain: Domain::APP,
4320 nspace: -1,
4321 alias: Some(SOURCE_ALIAS.to_string()),
4322 blob: None,
4323 };
4324
4325 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4326 domain: Domain::APP,
4327 nspace: -1,
4328 alias: Some(DESTINATION_ALIAS.to_string()),
4329 blob: None,
4330 };
4331
4332 let key_id = key_id_guard.id();
4333
4334 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4335 Ok(())
4336 })
4337 .unwrap();
4338
4339 let (_, key_entry) = db
4340 .load_key_entry(
4341 &destination_descriptor,
4342 KeyType::Client,
4343 KeyEntryLoadBits::BOTH,
4344 DESTINATION_UID,
4345 |k, av| {
4346 assert_eq!(Domain::APP, k.domain);
4347 assert_eq!(DESTINATION_UID as i64, k.nspace);
4348 assert!(av.is_none());
4349 Ok(())
4350 },
4351 )
4352 .unwrap();
4353
4354 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4355
4356 assert_eq!(
4357 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4358 db.load_key_entry(
4359 &source_descriptor,
4360 KeyType::Client,
4361 KeyEntryLoadBits::NONE,
4362 SOURCE_UID,
4363 |_k, _av| Ok(()),
4364 )
4365 .unwrap_err()
4366 .root_cause()
4367 .downcast_ref::<KsError>()
4368 );
4369
4370 Ok(())
4371 }
4372
4373 // Creates a key migrates it to a different location and then tries to access it by the old
4374 // and new location.
4375 #[test]
4376 fn test_migrate_key_app_to_selinux() -> Result<()> {
4377 let mut db = new_test_db()?;
4378 const SOURCE_UID: u32 = 1u32;
4379 const DESTINATION_UID: u32 = 2u32;
4380 const DESTINATION_NAMESPACE: i64 = 1000i64;
4381 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4382 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4383 let key_id_guard =
4384 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4385 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4386
4387 let source_descriptor: KeyDescriptor = KeyDescriptor {
4388 domain: Domain::APP,
4389 nspace: -1,
4390 alias: Some(SOURCE_ALIAS.to_string()),
4391 blob: None,
4392 };
4393
4394 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4395 domain: Domain::SELINUX,
4396 nspace: DESTINATION_NAMESPACE,
4397 alias: Some(DESTINATION_ALIAS.to_string()),
4398 blob: None,
4399 };
4400
4401 let key_id = key_id_guard.id();
4402
4403 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4404 Ok(())
4405 })
4406 .unwrap();
4407
4408 let (_, key_entry) = db
4409 .load_key_entry(
4410 &destination_descriptor,
4411 KeyType::Client,
4412 KeyEntryLoadBits::BOTH,
4413 DESTINATION_UID,
4414 |k, av| {
4415 assert_eq!(Domain::SELINUX, k.domain);
4416 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4417 assert!(av.is_none());
4418 Ok(())
4419 },
4420 )
4421 .unwrap();
4422
4423 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4424
4425 assert_eq!(
4426 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4427 db.load_key_entry(
4428 &source_descriptor,
4429 KeyType::Client,
4430 KeyEntryLoadBits::NONE,
4431 SOURCE_UID,
4432 |_k, _av| Ok(()),
4433 )
4434 .unwrap_err()
4435 .root_cause()
4436 .downcast_ref::<KsError>()
4437 );
4438
4439 Ok(())
4440 }
4441
4442 // Creates two keys and tries to migrate the first to the location of the second which
4443 // is expected to fail.
4444 #[test]
4445 fn test_migrate_key_destination_occupied() -> Result<()> {
4446 let mut db = new_test_db()?;
4447 const SOURCE_UID: u32 = 1u32;
4448 const DESTINATION_UID: u32 = 2u32;
4449 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4450 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4451 let key_id_guard =
4452 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4453 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4454 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4455 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4456
4457 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4458 domain: Domain::APP,
4459 nspace: -1,
4460 alias: Some(DESTINATION_ALIAS.to_string()),
4461 blob: None,
4462 };
4463
4464 assert_eq!(
4465 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4466 db.migrate_key_namespace(
4467 key_id_guard,
4468 &destination_descriptor,
4469 DESTINATION_UID,
4470 |_k| Ok(())
4471 )
4472 .unwrap_err()
4473 .root_cause()
4474 .downcast_ref::<KsError>()
4475 );
4476
4477 Ok(())
4478 }
4479
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004480 #[test]
4481 fn test_upgrade_0_to_1() {
4482 const ALIAS1: &str = &"test_upgrade_0_to_1_1";
4483 const ALIAS2: &str = &"test_upgrade_0_to_1_2";
4484 const ALIAS3: &str = &"test_upgrade_0_to_1_3";
4485 const UID: u32 = 33;
4486 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4487 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4488 let key_id_untouched1 =
4489 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4490 let key_id_untouched2 =
4491 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4492 let key_id_deleted =
4493 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4494
4495 let (_, key_entry) = db
4496 .load_key_entry(
4497 &KeyDescriptor {
4498 domain: Domain::APP,
4499 nspace: -1,
4500 alias: Some(ALIAS1.to_string()),
4501 blob: None,
4502 },
4503 KeyType::Client,
4504 KeyEntryLoadBits::BOTH,
4505 UID,
4506 |k, av| {
4507 assert_eq!(Domain::APP, k.domain);
4508 assert_eq!(UID as i64, k.nspace);
4509 assert!(av.is_none());
4510 Ok(())
4511 },
4512 )
4513 .unwrap();
4514 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4515 let (_, key_entry) = db
4516 .load_key_entry(
4517 &KeyDescriptor {
4518 domain: Domain::APP,
4519 nspace: -1,
4520 alias: Some(ALIAS2.to_string()),
4521 blob: None,
4522 },
4523 KeyType::Client,
4524 KeyEntryLoadBits::BOTH,
4525 UID,
4526 |k, av| {
4527 assert_eq!(Domain::APP, k.domain);
4528 assert_eq!(UID as i64, k.nspace);
4529 assert!(av.is_none());
4530 Ok(())
4531 },
4532 )
4533 .unwrap();
4534 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4535 let (_, key_entry) = db
4536 .load_key_entry(
4537 &KeyDescriptor {
4538 domain: Domain::APP,
4539 nspace: -1,
4540 alias: Some(ALIAS3.to_string()),
4541 blob: None,
4542 },
4543 KeyType::Client,
4544 KeyEntryLoadBits::BOTH,
4545 UID,
4546 |k, av| {
4547 assert_eq!(Domain::APP, k.domain);
4548 assert_eq!(UID as i64, k.nspace);
4549 assert!(av.is_none());
4550 Ok(())
4551 },
4552 )
4553 .unwrap();
4554 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4555
4556 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4557 KeystoreDB::from_0_to_1(tx).no_gc()
4558 })
4559 .unwrap();
4560
4561 let (_, key_entry) = db
4562 .load_key_entry(
4563 &KeyDescriptor {
4564 domain: Domain::APP,
4565 nspace: -1,
4566 alias: Some(ALIAS1.to_string()),
4567 blob: None,
4568 },
4569 KeyType::Client,
4570 KeyEntryLoadBits::BOTH,
4571 UID,
4572 |k, av| {
4573 assert_eq!(Domain::APP, k.domain);
4574 assert_eq!(UID as i64, k.nspace);
4575 assert!(av.is_none());
4576 Ok(())
4577 },
4578 )
4579 .unwrap();
4580 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4581 let (_, key_entry) = db
4582 .load_key_entry(
4583 &KeyDescriptor {
4584 domain: Domain::APP,
4585 nspace: -1,
4586 alias: Some(ALIAS2.to_string()),
4587 blob: None,
4588 },
4589 KeyType::Client,
4590 KeyEntryLoadBits::BOTH,
4591 UID,
4592 |k, av| {
4593 assert_eq!(Domain::APP, k.domain);
4594 assert_eq!(UID as i64, k.nspace);
4595 assert!(av.is_none());
4596 Ok(())
4597 },
4598 )
4599 .unwrap();
4600 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4601 assert_eq!(
4602 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4603 db.load_key_entry(
4604 &KeyDescriptor {
4605 domain: Domain::APP,
4606 nspace: -1,
4607 alias: Some(ALIAS3.to_string()),
4608 blob: None,
4609 },
4610 KeyType::Client,
4611 KeyEntryLoadBits::BOTH,
4612 UID,
4613 |k, av| {
4614 assert_eq!(Domain::APP, k.domain);
4615 assert_eq!(UID as i64, k.nspace);
4616 assert!(av.is_none());
4617 Ok(())
4618 },
4619 )
4620 .unwrap_err()
4621 .root_cause()
4622 .downcast_ref::<KsError>()
4623 );
4624 }
4625
Janis Danisevskisaec14592020-11-12 09:41:49 -08004626 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4627
Janis Danisevskisaec14592020-11-12 09:41:49 -08004628 #[test]
4629 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4630 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004631 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4632 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004633 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004634 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004635 .context("test_insert_and_load_full_keyentry_domain_app")?
4636 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004637 let (_key_guard, key_entry) = db
4638 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004639 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004640 domain: Domain::APP,
4641 nspace: 0,
4642 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4643 blob: None,
4644 },
4645 KeyType::Client,
4646 KeyEntryLoadBits::BOTH,
4647 33,
4648 |_k, _av| Ok(()),
4649 )
4650 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004651 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004652 let state = Arc::new(AtomicU8::new(1));
4653 let state2 = state.clone();
4654
4655 // Spawning a second thread that attempts to acquire the key id lock
4656 // for the same key as the primary thread. The primary thread then
4657 // waits, thereby forcing the secondary thread into the second stage
4658 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4659 // The test succeeds if the secondary thread observes the transition
4660 // of `state` from 1 to 2, despite having a whole second to overtake
4661 // the primary thread.
4662 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004663 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004664 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004665 assert!(db
4666 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004667 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004668 domain: Domain::APP,
4669 nspace: 0,
4670 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4671 blob: None,
4672 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004673 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004674 KeyEntryLoadBits::BOTH,
4675 33,
4676 |_k, _av| Ok(()),
4677 )
4678 .is_ok());
4679 // We should only see a 2 here because we can only return
4680 // from load_key_entry when the `_key_guard` expires,
4681 // which happens at the end of the scope.
4682 assert_eq!(2, state2.load(Ordering::Relaxed));
4683 });
4684
4685 thread::sleep(std::time::Duration::from_millis(1000));
4686
4687 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4688
4689 // Return the handle from this scope so we can join with the
4690 // secondary thread after the key id lock has expired.
4691 handle
4692 // This is where the `_key_guard` goes out of scope,
4693 // which is the reason for concurrent load_key_entry on the same key
4694 // to unblock.
4695 };
4696 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4697 // main test thread. We will not see failing asserts in secondary threads otherwise.
4698 handle.join().unwrap();
4699 Ok(())
4700 }
4701
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004702 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004703 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004704 let temp_dir =
4705 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4706
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004707 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4708 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004709
4710 let _tx1 = db1
4711 .conn
4712 .transaction_with_behavior(TransactionBehavior::Immediate)
4713 .expect("Failed to create first transaction.");
4714
4715 let error = db2
4716 .conn
4717 .transaction_with_behavior(TransactionBehavior::Immediate)
4718 .context("Transaction begin failed.")
4719 .expect_err("This should fail.");
4720 let root_cause = error.root_cause();
4721 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4722 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4723 {
4724 return;
4725 }
4726 panic!(
4727 "Unexpected error {:?} \n{:?} \n{:?}",
4728 error,
4729 root_cause,
4730 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4731 )
4732 }
4733
4734 #[cfg(disabled)]
4735 #[test]
4736 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4737 let temp_dir = Arc::new(
4738 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4739 .expect("Failed to create temp dir."),
4740 );
4741
4742 let test_begin = Instant::now();
4743
Janis Danisevskis66784c42021-01-27 08:40:25 -08004744 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004745 let mut db =
4746 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004747 const OPEN_DB_COUNT: u32 = 50u32;
4748
4749 let mut actual_key_count = KEY_COUNT;
4750 // First insert KEY_COUNT keys.
4751 for count in 0..KEY_COUNT {
4752 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4753 actual_key_count = count;
4754 break;
4755 }
4756 let alias = format!("test_alias_{}", count);
4757 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4758 .expect("Failed to make key entry.");
4759 }
4760
4761 // Insert more keys from a different thread and into a different namespace.
4762 let temp_dir1 = temp_dir.clone();
4763 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004764 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4765 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004766
4767 for count in 0..actual_key_count {
4768 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4769 return;
4770 }
4771 let alias = format!("test_alias_{}", count);
4772 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4773 .expect("Failed to make key entry.");
4774 }
4775
4776 // then unbind them again.
4777 for count in 0..actual_key_count {
4778 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4779 return;
4780 }
4781 let key = KeyDescriptor {
4782 domain: Domain::APP,
4783 nspace: -1,
4784 alias: Some(format!("test_alias_{}", count)),
4785 blob: None,
4786 };
4787 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4788 }
4789 });
4790
4791 // And start unbinding the first set of keys.
4792 let temp_dir2 = temp_dir.clone();
4793 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004794 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4795 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004796
4797 for count in 0..actual_key_count {
4798 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4799 return;
4800 }
4801 let key = KeyDescriptor {
4802 domain: Domain::APP,
4803 nspace: -1,
4804 alias: Some(format!("test_alias_{}", count)),
4805 blob: None,
4806 };
4807 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4808 }
4809 });
4810
Janis Danisevskis66784c42021-01-27 08:40:25 -08004811 // While a lot of inserting and deleting is going on we have to open database connections
4812 // successfully and use them.
4813 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4814 // out of scope.
4815 #[allow(clippy::redundant_clone)]
4816 let temp_dir4 = temp_dir.clone();
4817 let handle4 = thread::spawn(move || {
4818 for count in 0..OPEN_DB_COUNT {
4819 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4820 return;
4821 }
Seth Moore444b51a2021-06-11 09:49:49 -07004822 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4823 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004824
4825 let alias = format!("test_alias_{}", count);
4826 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4827 .expect("Failed to make key entry.");
4828 let key = KeyDescriptor {
4829 domain: Domain::APP,
4830 nspace: -1,
4831 alias: Some(alias),
4832 blob: None,
4833 };
4834 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4835 }
4836 });
4837
4838 handle1.join().expect("Thread 1 panicked.");
4839 handle2.join().expect("Thread 2 panicked.");
4840 handle4.join().expect("Thread 4 panicked.");
4841
Janis Danisevskis66784c42021-01-27 08:40:25 -08004842 Ok(())
4843 }
4844
4845 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004846 fn list() -> Result<()> {
4847 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004848 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004849 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4850 (Domain::APP, 1, "test1"),
4851 (Domain::APP, 1, "test2"),
4852 (Domain::APP, 1, "test3"),
4853 (Domain::APP, 1, "test4"),
4854 (Domain::APP, 1, "test5"),
4855 (Domain::APP, 1, "test6"),
4856 (Domain::APP, 1, "test7"),
4857 (Domain::APP, 2, "test1"),
4858 (Domain::APP, 2, "test2"),
4859 (Domain::APP, 2, "test3"),
4860 (Domain::APP, 2, "test4"),
4861 (Domain::APP, 2, "test5"),
4862 (Domain::APP, 2, "test6"),
4863 (Domain::APP, 2, "test8"),
4864 (Domain::SELINUX, 100, "test1"),
4865 (Domain::SELINUX, 100, "test2"),
4866 (Domain::SELINUX, 100, "test3"),
4867 (Domain::SELINUX, 100, "test4"),
4868 (Domain::SELINUX, 100, "test5"),
4869 (Domain::SELINUX, 100, "test6"),
4870 (Domain::SELINUX, 100, "test9"),
4871 ];
4872
4873 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4874 .iter()
4875 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004876 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4877 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004878 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4879 });
4880 (entry.id(), *ns)
4881 })
4882 .collect();
4883
4884 for (domain, namespace) in
4885 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4886 {
4887 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4888 .iter()
4889 .filter_map(|(domain, ns, alias)| match ns {
4890 ns if *ns == *namespace => Some(KeyDescriptor {
4891 domain: *domain,
4892 nspace: *ns,
4893 alias: Some(alias.to_string()),
4894 blob: None,
4895 }),
4896 _ => None,
4897 })
4898 .collect();
4899 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07004900 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004901 list_result.sort();
4902 assert_eq!(list_o_descriptors, list_result);
4903
4904 let mut list_o_ids: Vec<i64> = list_o_descriptors
4905 .into_iter()
4906 .map(|d| {
4907 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004908 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004909 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004910 KeyType::Client,
4911 KeyEntryLoadBits::NONE,
4912 *namespace as u32,
4913 |_, _| Ok(()),
4914 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004915 .unwrap();
4916 entry.id()
4917 })
4918 .collect();
4919 list_o_ids.sort_unstable();
4920 let mut loaded_entries: Vec<i64> = list_o_keys
4921 .iter()
4922 .filter_map(|(id, ns)| match ns {
4923 ns if *ns == *namespace => Some(*id),
4924 _ => None,
4925 })
4926 .collect();
4927 loaded_entries.sort_unstable();
4928 assert_eq!(list_o_ids, loaded_entries);
4929 }
Janis Danisevskis18313832021-05-17 13:30:32 -07004930 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004931
4932 Ok(())
4933 }
4934
Joel Galenson0891bc12020-07-20 10:37:03 -07004935 // Helpers
4936
4937 // Checks that the given result is an error containing the given string.
4938 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4939 let error_str = format!(
4940 "{:#?}",
4941 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4942 );
4943 assert!(
4944 error_str.contains(target),
4945 "The string \"{}\" should contain \"{}\"",
4946 error_str,
4947 target
4948 );
4949 }
4950
Joel Galenson2aab4432020-07-22 15:27:57 -07004951 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004952 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004953 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004954 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004955 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004956 namespace: Option<i64>,
4957 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004958 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004959 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004960 }
4961
4962 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4963 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004964 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004965 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004966 Ok(KeyEntryRow {
4967 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004968 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004969 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004970 namespace: row.get(3)?,
4971 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004972 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004973 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004974 })
4975 })?
4976 .map(|r| r.context("Could not read keyentry row."))
4977 .collect::<Result<Vec<_>>>()
4978 }
4979
Max Biresb2e1d032021-02-08 21:35:05 -08004980 struct RemoteProvValues {
4981 cert_chain: Vec<u8>,
4982 priv_key: Vec<u8>,
4983 batch_cert: Vec<u8>,
4984 }
4985
Max Bires2b2e6562020-09-22 11:22:36 -07004986 fn load_attestation_key_pool(
4987 db: &mut KeystoreDB,
4988 expiration_date: i64,
4989 namespace: i64,
4990 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004991 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004992 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4993 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4994 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4995 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004996 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004997 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4998 db.store_signed_attestation_certificate_chain(
4999 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005000 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005001 &cert_chain,
5002 expiration_date,
5003 &KEYSTORE_UUID,
5004 )?;
5005 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005006 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005007 }
5008
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005009 // Note: The parameters and SecurityLevel associations are nonsensical. This
5010 // collection is only used to check if the parameters are preserved as expected by the
5011 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005012 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5013 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005014 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5015 KeyParameter::new(
5016 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5017 SecurityLevel::TRUSTED_ENVIRONMENT,
5018 ),
5019 KeyParameter::new(
5020 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5021 SecurityLevel::TRUSTED_ENVIRONMENT,
5022 ),
5023 KeyParameter::new(
5024 KeyParameterValue::Algorithm(Algorithm::RSA),
5025 SecurityLevel::TRUSTED_ENVIRONMENT,
5026 ),
5027 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5028 KeyParameter::new(
5029 KeyParameterValue::BlockMode(BlockMode::ECB),
5030 SecurityLevel::TRUSTED_ENVIRONMENT,
5031 ),
5032 KeyParameter::new(
5033 KeyParameterValue::BlockMode(BlockMode::GCM),
5034 SecurityLevel::TRUSTED_ENVIRONMENT,
5035 ),
5036 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5037 KeyParameter::new(
5038 KeyParameterValue::Digest(Digest::MD5),
5039 SecurityLevel::TRUSTED_ENVIRONMENT,
5040 ),
5041 KeyParameter::new(
5042 KeyParameterValue::Digest(Digest::SHA_2_224),
5043 SecurityLevel::TRUSTED_ENVIRONMENT,
5044 ),
5045 KeyParameter::new(
5046 KeyParameterValue::Digest(Digest::SHA_2_256),
5047 SecurityLevel::STRONGBOX,
5048 ),
5049 KeyParameter::new(
5050 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5051 SecurityLevel::TRUSTED_ENVIRONMENT,
5052 ),
5053 KeyParameter::new(
5054 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5055 SecurityLevel::TRUSTED_ENVIRONMENT,
5056 ),
5057 KeyParameter::new(
5058 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5059 SecurityLevel::STRONGBOX,
5060 ),
5061 KeyParameter::new(
5062 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5063 SecurityLevel::TRUSTED_ENVIRONMENT,
5064 ),
5065 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5066 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5067 KeyParameter::new(
5068 KeyParameterValue::EcCurve(EcCurve::P_224),
5069 SecurityLevel::TRUSTED_ENVIRONMENT,
5070 ),
5071 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5072 KeyParameter::new(
5073 KeyParameterValue::EcCurve(EcCurve::P_384),
5074 SecurityLevel::TRUSTED_ENVIRONMENT,
5075 ),
5076 KeyParameter::new(
5077 KeyParameterValue::EcCurve(EcCurve::P_521),
5078 SecurityLevel::TRUSTED_ENVIRONMENT,
5079 ),
5080 KeyParameter::new(
5081 KeyParameterValue::RSAPublicExponent(3),
5082 SecurityLevel::TRUSTED_ENVIRONMENT,
5083 ),
5084 KeyParameter::new(
5085 KeyParameterValue::IncludeUniqueID,
5086 SecurityLevel::TRUSTED_ENVIRONMENT,
5087 ),
5088 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5089 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5090 KeyParameter::new(
5091 KeyParameterValue::ActiveDateTime(1234567890),
5092 SecurityLevel::STRONGBOX,
5093 ),
5094 KeyParameter::new(
5095 KeyParameterValue::OriginationExpireDateTime(1234567890),
5096 SecurityLevel::TRUSTED_ENVIRONMENT,
5097 ),
5098 KeyParameter::new(
5099 KeyParameterValue::UsageExpireDateTime(1234567890),
5100 SecurityLevel::TRUSTED_ENVIRONMENT,
5101 ),
5102 KeyParameter::new(
5103 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5104 SecurityLevel::TRUSTED_ENVIRONMENT,
5105 ),
5106 KeyParameter::new(
5107 KeyParameterValue::MaxUsesPerBoot(1234567890),
5108 SecurityLevel::TRUSTED_ENVIRONMENT,
5109 ),
5110 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5111 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5112 KeyParameter::new(
5113 KeyParameterValue::NoAuthRequired,
5114 SecurityLevel::TRUSTED_ENVIRONMENT,
5115 ),
5116 KeyParameter::new(
5117 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5118 SecurityLevel::TRUSTED_ENVIRONMENT,
5119 ),
5120 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5121 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5122 KeyParameter::new(
5123 KeyParameterValue::TrustedUserPresenceRequired,
5124 SecurityLevel::TRUSTED_ENVIRONMENT,
5125 ),
5126 KeyParameter::new(
5127 KeyParameterValue::TrustedConfirmationRequired,
5128 SecurityLevel::TRUSTED_ENVIRONMENT,
5129 ),
5130 KeyParameter::new(
5131 KeyParameterValue::UnlockedDeviceRequired,
5132 SecurityLevel::TRUSTED_ENVIRONMENT,
5133 ),
5134 KeyParameter::new(
5135 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5136 SecurityLevel::SOFTWARE,
5137 ),
5138 KeyParameter::new(
5139 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5140 SecurityLevel::SOFTWARE,
5141 ),
5142 KeyParameter::new(
5143 KeyParameterValue::CreationDateTime(12345677890),
5144 SecurityLevel::SOFTWARE,
5145 ),
5146 KeyParameter::new(
5147 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5148 SecurityLevel::TRUSTED_ENVIRONMENT,
5149 ),
5150 KeyParameter::new(
5151 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5152 SecurityLevel::TRUSTED_ENVIRONMENT,
5153 ),
5154 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5155 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5156 KeyParameter::new(
5157 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5158 SecurityLevel::SOFTWARE,
5159 ),
5160 KeyParameter::new(
5161 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5162 SecurityLevel::TRUSTED_ENVIRONMENT,
5163 ),
5164 KeyParameter::new(
5165 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5166 SecurityLevel::TRUSTED_ENVIRONMENT,
5167 ),
5168 KeyParameter::new(
5169 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5170 SecurityLevel::TRUSTED_ENVIRONMENT,
5171 ),
5172 KeyParameter::new(
5173 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5174 SecurityLevel::TRUSTED_ENVIRONMENT,
5175 ),
5176 KeyParameter::new(
5177 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5178 SecurityLevel::TRUSTED_ENVIRONMENT,
5179 ),
5180 KeyParameter::new(
5181 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5182 SecurityLevel::TRUSTED_ENVIRONMENT,
5183 ),
5184 KeyParameter::new(
5185 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5186 SecurityLevel::TRUSTED_ENVIRONMENT,
5187 ),
5188 KeyParameter::new(
5189 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5190 SecurityLevel::TRUSTED_ENVIRONMENT,
5191 ),
5192 KeyParameter::new(
5193 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5194 SecurityLevel::TRUSTED_ENVIRONMENT,
5195 ),
5196 KeyParameter::new(
5197 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5198 SecurityLevel::TRUSTED_ENVIRONMENT,
5199 ),
5200 KeyParameter::new(
5201 KeyParameterValue::VendorPatchLevel(3),
5202 SecurityLevel::TRUSTED_ENVIRONMENT,
5203 ),
5204 KeyParameter::new(
5205 KeyParameterValue::BootPatchLevel(4),
5206 SecurityLevel::TRUSTED_ENVIRONMENT,
5207 ),
5208 KeyParameter::new(
5209 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5210 SecurityLevel::TRUSTED_ENVIRONMENT,
5211 ),
5212 KeyParameter::new(
5213 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5214 SecurityLevel::TRUSTED_ENVIRONMENT,
5215 ),
5216 KeyParameter::new(
5217 KeyParameterValue::MacLength(256),
5218 SecurityLevel::TRUSTED_ENVIRONMENT,
5219 ),
5220 KeyParameter::new(
5221 KeyParameterValue::ResetSinceIdRotation,
5222 SecurityLevel::TRUSTED_ENVIRONMENT,
5223 ),
5224 KeyParameter::new(
5225 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5226 SecurityLevel::TRUSTED_ENVIRONMENT,
5227 ),
Qi Wub9433b52020-12-01 14:52:46 +08005228 ];
5229 if let Some(value) = max_usage_count {
5230 params.push(KeyParameter::new(
5231 KeyParameterValue::UsageCountLimit(value),
5232 SecurityLevel::SOFTWARE,
5233 ));
5234 }
5235 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005236 }
5237
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005238 fn make_test_key_entry(
5239 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005240 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005241 namespace: i64,
5242 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005243 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005244 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005245 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005246 let mut blob_metadata = BlobMetaData::new();
5247 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5248 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5249 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5250 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5251 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5252
5253 db.set_blob(
5254 &key_id,
5255 SubComponentType::KEY_BLOB,
5256 Some(TEST_KEY_BLOB),
5257 Some(&blob_metadata),
5258 )?;
5259 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5260 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005261
5262 let params = make_test_params(max_usage_count);
5263 db.insert_keyparameter(&key_id, &params)?;
5264
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005265 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005266 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005267 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005268 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005269 Ok(key_id)
5270 }
5271
Qi Wub9433b52020-12-01 14:52:46 +08005272 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5273 let params = make_test_params(max_usage_count);
5274
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005275 let mut blob_metadata = BlobMetaData::new();
5276 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5277 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5278 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5279 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5280 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5281
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005282 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005283 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005284
5285 KeyEntry {
5286 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005287 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005288 cert: Some(TEST_CERT_BLOB.to_vec()),
5289 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005290 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005291 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005292 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005293 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005294 }
5295 }
5296
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005297 fn make_bootlevel_key_entry(
5298 db: &mut KeystoreDB,
5299 domain: Domain,
5300 namespace: i64,
5301 alias: &str,
5302 logical_only: bool,
5303 ) -> Result<KeyIdGuard> {
5304 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5305 let mut blob_metadata = BlobMetaData::new();
5306 if !logical_only {
5307 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5308 }
5309 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5310
5311 db.set_blob(
5312 &key_id,
5313 SubComponentType::KEY_BLOB,
5314 Some(TEST_KEY_BLOB),
5315 Some(&blob_metadata),
5316 )?;
5317 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5318 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5319
5320 let mut params = make_test_params(None);
5321 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5322
5323 db.insert_keyparameter(&key_id, &params)?;
5324
5325 let mut metadata = KeyMetaData::new();
5326 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5327 db.insert_key_metadata(&key_id, &metadata)?;
5328 rebind_alias(db, &key_id, alias, domain, namespace)?;
5329 Ok(key_id)
5330 }
5331
5332 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5333 let mut params = make_test_params(None);
5334 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5335
5336 let mut blob_metadata = BlobMetaData::new();
5337 if !logical_only {
5338 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5339 }
5340 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5341
5342 let mut metadata = KeyMetaData::new();
5343 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5344
5345 KeyEntry {
5346 id: key_id,
5347 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5348 cert: Some(TEST_CERT_BLOB.to_vec()),
5349 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5350 km_uuid: KEYSTORE_UUID,
5351 parameters: params,
5352 metadata,
5353 pure_cert: false,
5354 }
5355 }
5356
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005357 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005358 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005359 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005360 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005361 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005362 NO_PARAMS,
5363 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005364 Ok((
5365 row.get(0)?,
5366 row.get(1)?,
5367 row.get(2)?,
5368 row.get(3)?,
5369 row.get(4)?,
5370 row.get(5)?,
5371 row.get(6)?,
5372 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005373 },
5374 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005375
5376 println!("Key entry table rows:");
5377 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005378 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005379 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005380 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5381 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005382 );
5383 }
5384 Ok(())
5385 }
5386
5387 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005388 let mut stmt = db
5389 .conn
5390 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005391 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5392 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5393 })?;
5394
5395 println!("Grant table rows:");
5396 for r in rows {
5397 let (id, gt, ki, av) = r.unwrap();
5398 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5399 }
5400 Ok(())
5401 }
5402
Joel Galenson0891bc12020-07-20 10:37:03 -07005403 // Use a custom random number generator that repeats each number once.
5404 // This allows us to test repeated elements.
5405
5406 thread_local! {
5407 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5408 }
5409
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005410 fn reset_random() {
5411 RANDOM_COUNTER.with(|counter| {
5412 *counter.borrow_mut() = 0;
5413 })
5414 }
5415
Joel Galenson0891bc12020-07-20 10:37:03 -07005416 pub fn random() -> i64 {
5417 RANDOM_COUNTER.with(|counter| {
5418 let result = *counter.borrow() / 2;
5419 *counter.borrow_mut() += 1;
5420 result
5421 })
5422 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005423
5424 #[test]
5425 fn test_last_off_body() -> Result<()> {
5426 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005427 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005428 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005429 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005430 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005431 let one_second = Duration::from_secs(1);
5432 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005433 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005434 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005435 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005436 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005437 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005438 Ok(())
5439 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005440
5441 #[test]
5442 fn test_unbind_keys_for_user() -> Result<()> {
5443 let mut db = new_test_db()?;
5444 db.unbind_keys_for_user(1, false)?;
5445
5446 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5447 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5448 db.unbind_keys_for_user(2, false)?;
5449
Janis Danisevskis18313832021-05-17 13:30:32 -07005450 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5451 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005452
5453 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005454 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005455
5456 Ok(())
5457 }
5458
5459 #[test]
5460 fn test_store_super_key() -> Result<()> {
5461 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005462 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005463 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005464 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005465 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005466 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005467
5468 let (encrypted_super_key, metadata) =
5469 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005470 db.store_super_key(
5471 1,
5472 &USER_SUPER_KEY,
5473 &encrypted_super_key,
5474 &metadata,
5475 &KeyMetaData::new(),
5476 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005477
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005478 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005479 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005480
Paul Crowley7a658392021-03-18 17:08:20 -07005481 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005482 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5483 USER_SUPER_KEY.algorithm,
5484 key_entry,
5485 &pw,
5486 None,
5487 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005488
Paul Crowley7a658392021-03-18 17:08:20 -07005489 let decrypted_secret_bytes =
5490 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5491 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005492 Ok(())
5493 }
Seth Moore78c091f2021-04-09 21:38:30 +00005494
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005495 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005496 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005497 MetricsStorage::KEY_ENTRY,
5498 MetricsStorage::KEY_ENTRY_ID_INDEX,
5499 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5500 MetricsStorage::BLOB_ENTRY,
5501 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5502 MetricsStorage::KEY_PARAMETER,
5503 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5504 MetricsStorage::KEY_METADATA,
5505 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5506 MetricsStorage::GRANT,
5507 MetricsStorage::AUTH_TOKEN,
5508 MetricsStorage::BLOB_METADATA,
5509 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005510 ]
5511 }
5512
5513 /// Perform a simple check to ensure that we can query all the storage types
5514 /// that are supported by the DB. Check for reasonable values.
5515 #[test]
5516 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005517 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005518
5519 let mut db = new_test_db()?;
5520
5521 for t in get_valid_statsd_storage_types() {
5522 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005523 // AuthToken can be less than a page since it's in a btree, not sqlite
5524 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005525 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005526 } else {
5527 assert!(stat.size >= PAGE_SIZE);
5528 }
Seth Moore78c091f2021-04-09 21:38:30 +00005529 assert!(stat.size >= stat.unused_size);
5530 }
5531
5532 Ok(())
5533 }
5534
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005535 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005536 get_valid_statsd_storage_types()
5537 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005538 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005539 .collect()
5540 }
5541
5542 fn assert_storage_increased(
5543 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005544 increased_storage_types: Vec<MetricsStorage>,
5545 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005546 ) {
5547 for storage in increased_storage_types {
5548 // Verify the expected storage increased.
5549 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005550 let storage = storage;
5551 let old = &baseline[&storage.0];
5552 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005553 assert!(
5554 new.unused_size <= old.unused_size,
5555 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005556 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005557 new.unused_size,
5558 old.unused_size
5559 );
5560
5561 // Update the baseline with the new value so that it succeeds in the
5562 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005563 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005564 }
5565
5566 // Get an updated map of the storage and verify there were no unexpected changes.
5567 let updated_stats = get_storage_stats_map(db);
5568 assert_eq!(updated_stats.len(), baseline.len());
5569
5570 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005571 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005572 let mut s = String::new();
5573 for &k in map.keys() {
5574 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5575 .expect("string concat failed");
5576 }
5577 s
5578 };
5579
5580 assert!(
5581 updated_stats[&k].size == baseline[&k].size
5582 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5583 "updated_stats:\n{}\nbaseline:\n{}",
5584 stringify(&updated_stats),
5585 stringify(&baseline)
5586 );
5587 }
5588 }
5589
5590 #[test]
5591 fn test_verify_key_table_size_reporting() -> Result<()> {
5592 let mut db = new_test_db()?;
5593 let mut working_stats = get_storage_stats_map(&mut db);
5594
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005595 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005596 assert_storage_increased(
5597 &mut db,
5598 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005599 MetricsStorage::KEY_ENTRY,
5600 MetricsStorage::KEY_ENTRY_ID_INDEX,
5601 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005602 ],
5603 &mut working_stats,
5604 );
5605
5606 let mut blob_metadata = BlobMetaData::new();
5607 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5608 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5609 assert_storage_increased(
5610 &mut db,
5611 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005612 MetricsStorage::BLOB_ENTRY,
5613 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5614 MetricsStorage::BLOB_METADATA,
5615 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005616 ],
5617 &mut working_stats,
5618 );
5619
5620 let params = make_test_params(None);
5621 db.insert_keyparameter(&key_id, &params)?;
5622 assert_storage_increased(
5623 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005624 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005625 &mut working_stats,
5626 );
5627
5628 let mut metadata = KeyMetaData::new();
5629 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5630 db.insert_key_metadata(&key_id, &metadata)?;
5631 assert_storage_increased(
5632 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005633 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005634 &mut working_stats,
5635 );
5636
5637 let mut sum = 0;
5638 for stat in working_stats.values() {
5639 sum += stat.size;
5640 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005641 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005642 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5643
5644 Ok(())
5645 }
5646
5647 #[test]
5648 fn test_verify_auth_table_size_reporting() -> Result<()> {
5649 let mut db = new_test_db()?;
5650 let mut working_stats = get_storage_stats_map(&mut db);
5651 db.insert_auth_token(&HardwareAuthToken {
5652 challenge: 123,
5653 userId: 456,
5654 authenticatorId: 789,
5655 authenticatorType: kmhw_authenticator_type::ANY,
5656 timestamp: Timestamp { milliSeconds: 10 },
5657 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005658 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005659 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005660 Ok(())
5661 }
5662
5663 #[test]
5664 fn test_verify_grant_table_size_reporting() -> Result<()> {
5665 const OWNER: i64 = 1;
5666 let mut db = new_test_db()?;
5667 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5668
5669 let mut working_stats = get_storage_stats_map(&mut db);
5670 db.grant(
5671 &KeyDescriptor {
5672 domain: Domain::APP,
5673 nspace: 0,
5674 alias: Some(TEST_ALIAS.to_string()),
5675 blob: None,
5676 },
5677 OWNER as u32,
5678 123,
5679 key_perm_set![KeyPerm::use_()],
5680 |_, _| Ok(()),
5681 )?;
5682
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005683 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005684
5685 Ok(())
5686 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005687
5688 #[test]
5689 fn find_auth_token_entry_returns_latest() -> Result<()> {
5690 let mut db = new_test_db()?;
5691 db.insert_auth_token(&HardwareAuthToken {
5692 challenge: 123,
5693 userId: 456,
5694 authenticatorId: 789,
5695 authenticatorType: kmhw_authenticator_type::ANY,
5696 timestamp: Timestamp { milliSeconds: 10 },
5697 mac: b"mac0".to_vec(),
5698 });
5699 std::thread::sleep(std::time::Duration::from_millis(1));
5700 db.insert_auth_token(&HardwareAuthToken {
5701 challenge: 123,
5702 userId: 457,
5703 authenticatorId: 789,
5704 authenticatorType: kmhw_authenticator_type::ANY,
5705 timestamp: Timestamp { milliSeconds: 12 },
5706 mac: b"mac1".to_vec(),
5707 });
5708 std::thread::sleep(std::time::Duration::from_millis(1));
5709 db.insert_auth_token(&HardwareAuthToken {
5710 challenge: 123,
5711 userId: 458,
5712 authenticatorId: 789,
5713 authenticatorType: kmhw_authenticator_type::ANY,
5714 timestamp: Timestamp { milliSeconds: 3 },
5715 mac: b"mac2".to_vec(),
5716 });
5717 // All three entries are in the database
5718 assert_eq!(db.perboot.auth_tokens_len(), 3);
5719 // It selected the most recent timestamp
5720 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5721 Ok(())
5722 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005723
5724 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005725 fn test_load_key_descriptor() -> Result<()> {
5726 let mut db = new_test_db()?;
5727 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5728
5729 let key = db.load_key_descriptor(key_id)?.unwrap();
5730
5731 assert_eq!(key.domain, Domain::APP);
5732 assert_eq!(key.nspace, 1);
5733 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5734
5735 // No such id
5736 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5737 Ok(())
5738 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005739}