blob: e5a8e4ab7b842385b8b02af80aa2b2ad1a78b0e6 [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
Janis Danisevskis030ba022021-05-26 11:15:30 -070045pub(crate) mod utils;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -070046mod versioning;
Matthew Maurerd7815ca2021-05-06 21:58:45 -070047
Janis Danisevskis11bd2592022-01-04 19:59:26 -080048use crate::gc::Gc;
Hasini Gunasinghe1a8524b2022-05-10 08:49:53 +000049use crate::globals::get_keymint_dev_by_uuid;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080050use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080051use crate::key_parameter::{KeyParameter, Tag};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000052use crate::ks_err;
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000053use crate::metrics_store::log_rkp_error_stats;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070054use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000055use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080056use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070057 error::{Error as KsError, ErrorCode, ResponseCode},
58 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080059};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080060use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080061use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis030ba022021-05-26 11:15:30 -070062use utils as db_utils;
63use utils::SqlField;
Janis Danisevskis60400fe2020-08-26 15:24:42 -070064
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000065use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080066 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000067 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080068};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070069use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070070 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070071};
Max Bires2b2e6562020-09-22 11:22:36 -070072use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
73 AttestationPoolStatus::AttestationPoolStatus,
74};
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000075use android_security_metrics::aidl::android::security::metrics::{
76 StorageStats::StorageStats,
77 Storage::Storage as MetricsStorage,
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000078 RkpError::RkpError as MetricsRkpError,
Seth Moore78c091f2021-04-09 21:38:30 +000079};
Max Bires2b2e6562020-09-22 11:22:36 -070080
81use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080082use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000083use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070084#[cfg(not(test))]
85use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070086use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070087 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080088 types::FromSql,
89 types::FromSqlResult,
90 types::ToSqlOutput,
91 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080092 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070093};
Max Bires2b2e6562020-09-22 11:22:36 -070094
Janis Danisevskisaec14592020-11-12 09:41:49 -080095use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080096 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080097 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070098 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080099 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -0800100};
Max Bires2b2e6562020-09-22 11:22:36 -0700101
Joel Galenson0891bc12020-07-20 10:37:03 -0700102#[cfg(test)]
103use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -0700104
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800105impl_metadata!(
106 /// A set of metadata for key entries.
107 #[derive(Debug, Default, Eq, PartialEq)]
108 pub struct KeyMetaData;
109 /// A metadata entry for key entries.
110 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
111 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800112 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800113 CreationDate(DateTime) with accessor creation_date,
114 /// Expiration date for attestation keys.
115 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700116 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
117 /// provisioning
118 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
119 /// Vector representing the raw public key so results from the server can be matched
120 /// to the right entry
121 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700122 /// SEC1 public key for ECDH encryption
123 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800124 // --- ADD NEW META DATA FIELDS HERE ---
125 // For backwards compatibility add new entries only to
126 // end of this list and above this comment.
127 };
128);
129
130impl KeyMetaData {
131 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
132 let mut stmt = tx
133 .prepare(
134 "SELECT tag, data from persistent.keymetadata
135 WHERE keyentryid = ?;",
136 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000137 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800138
139 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
140
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000141 let mut rows = stmt
142 .query(params![key_id])
143 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800144 db_utils::with_rows_extract_all(&mut rows, |row| {
145 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
146 metadata.insert(
147 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700148 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800149 .context("Failed to read KeyMetaEntry.")?,
150 );
151 Ok(())
152 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000153 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800154
155 Ok(Self { data: metadata })
156 }
157
158 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
159 let mut stmt = tx
160 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000161 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800162 VALUES (?, ?, ?);",
163 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000164 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800165
166 let iter = self.data.iter();
167 for (tag, entry) in iter {
168 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000169 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800170 })?;
171 }
172 Ok(())
173 }
174}
175
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800176impl_metadata!(
177 /// A set of metadata for key blobs.
178 #[derive(Debug, Default, Eq, PartialEq)]
179 pub struct BlobMetaData;
180 /// A metadata entry for key blobs.
181 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
182 pub enum BlobMetaEntry {
183 /// If present, indicates that the blob is encrypted with another key or a key derived
184 /// from a password.
185 EncryptedBy(EncryptedBy) with accessor encrypted_by,
186 /// If the blob is password encrypted this field is set to the
187 /// salt used for the key derivation.
188 Salt(Vec<u8>) with accessor salt,
189 /// If the blob is encrypted, this field is set to the initialization vector.
190 Iv(Vec<u8>) with accessor iv,
191 /// If the blob is encrypted, this field holds the AEAD TAG.
192 AeadTag(Vec<u8>) with accessor aead_tag,
193 /// The uuid of the owning KeyMint instance.
194 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700195 /// If the key is ECDH encrypted, this is the ephemeral public key
196 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000197 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
198 /// of that key
199 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800200 // --- ADD NEW META DATA FIELDS HERE ---
201 // For backwards compatibility add new entries only to
202 // end of this list and above this comment.
203 };
204);
205
206impl BlobMetaData {
207 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
208 let mut stmt = tx
209 .prepare(
210 "SELECT tag, data from persistent.blobmetadata
211 WHERE blobentryid = ?;",
212 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000213 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800214
215 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
216
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000217 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800218 db_utils::with_rows_extract_all(&mut rows, |row| {
219 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
220 metadata.insert(
221 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700222 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800223 .context("Failed to read BlobMetaEntry.")?,
224 );
225 Ok(())
226 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000227 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800228
229 Ok(Self { data: metadata })
230 }
231
232 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
233 let mut stmt = tx
234 .prepare(
235 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
236 VALUES (?, ?, ?);",
237 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000238 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800239
240 let iter = self.data.iter();
241 for (tag, entry) in iter {
242 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000243 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800244 })?;
245 }
246 Ok(())
247 }
248}
249
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800250/// Indicates the type of the keyentry.
251#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
252pub enum KeyType {
253 /// This is a client key type. These keys are created or imported through the Keystore 2.0
254 /// AIDL interface android.system.keystore2.
255 Client,
256 /// This is a super key type. These keys are created by keystore itself and used to encrypt
257 /// other key blobs to provide LSKF binding.
258 Super,
259 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
260 Attestation,
261}
262
263impl ToSql for KeyType {
264 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
265 Ok(ToSqlOutput::Owned(Value::Integer(match self {
266 KeyType::Client => 0,
267 KeyType::Super => 1,
268 KeyType::Attestation => 2,
269 })))
270 }
271}
272
273impl FromSql for KeyType {
274 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
275 match i64::column_result(value)? {
276 0 => Ok(KeyType::Client),
277 1 => Ok(KeyType::Super),
278 2 => Ok(KeyType::Attestation),
279 v => Err(FromSqlError::OutOfRange(v)),
280 }
281 }
282}
283
Max Bires8e93d2b2021-01-14 13:17:59 -0800284/// Uuid representation that can be stored in the database.
285/// Right now it can only be initialized from SecurityLevel.
286/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
287#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
288pub struct Uuid([u8; 16]);
289
290impl Deref for Uuid {
291 type Target = [u8; 16];
292
293 fn deref(&self) -> &Self::Target {
294 &self.0
295 }
296}
297
298impl From<SecurityLevel> for Uuid {
299 fn from(sec_level: SecurityLevel) -> Self {
300 Self((sec_level.0 as u128).to_be_bytes())
301 }
302}
303
304impl ToSql for Uuid {
305 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
306 self.0.to_sql()
307 }
308}
309
310impl FromSql for Uuid {
311 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
312 let blob = Vec::<u8>::column_result(value)?;
313 if blob.len() != 16 {
314 return Err(FromSqlError::OutOfRange(blob.len() as i64));
315 }
316 let mut arr = [0u8; 16];
317 arr.copy_from_slice(&blob);
318 Ok(Self(arr))
319 }
320}
321
322/// Key entries that are not associated with any KeyMint instance, such as pure certificate
323/// entries are associated with this UUID.
324pub static KEYSTORE_UUID: Uuid = Uuid([
325 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
326]);
327
Seth Moore056106f2022-07-07 09:53:51 -0700328static EXPIRATION_BUFFER_MS: i64 = 12 * 60 * 60 * 1000;
Max Birescd7f7412022-02-11 13:47:36 -0800329
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800330/// Indicates how the sensitive part of this key blob is encrypted.
331#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
332pub enum EncryptedBy {
333 /// The keyblob is encrypted by a user password.
334 /// In the database this variant is represented as NULL.
335 Password,
336 /// The keyblob is encrypted by another key with wrapped key id.
337 /// In the database this variant is represented as non NULL value
338 /// that is convertible to i64, typically NUMERIC.
339 KeyId(i64),
340}
341
342impl ToSql for EncryptedBy {
343 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
344 match self {
345 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
346 Self::KeyId(id) => id.to_sql(),
347 }
348 }
349}
350
351impl FromSql for EncryptedBy {
352 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
353 match value {
354 ValueRef::Null => Ok(Self::Password),
355 _ => Ok(Self::KeyId(i64::column_result(value)?)),
356 }
357 }
358}
359
360/// A database representation of wall clock time. DateTime stores unix epoch time as
361/// i64 in milliseconds.
362#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
363pub struct DateTime(i64);
364
365/// Error type returned when creating DateTime or converting it from and to
366/// SystemTime.
367#[derive(thiserror::Error, Debug)]
368pub enum DateTimeError {
369 /// This is returned when SystemTime and Duration computations fail.
370 #[error(transparent)]
371 SystemTimeError(#[from] SystemTimeError),
372
373 /// This is returned when type conversions fail.
374 #[error(transparent)]
375 TypeConversion(#[from] std::num::TryFromIntError),
376
377 /// This is returned when checked time arithmetic failed.
378 #[error("Time arithmetic failed.")]
379 TimeArithmetic,
380}
381
382impl DateTime {
383 /// Constructs a new DateTime object denoting the current time. This may fail during
384 /// conversion to unix epoch time and during conversion to the internal i64 representation.
385 pub fn now() -> Result<Self, DateTimeError> {
386 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
387 }
388
389 /// Constructs a new DateTime object from milliseconds.
390 pub fn from_millis_epoch(millis: i64) -> Self {
391 Self(millis)
392 }
393
394 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700395 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800396 self.0
397 }
398
399 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700400 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800401 self.0 / 1000
402 }
403}
404
405impl ToSql for DateTime {
406 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
407 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
408 }
409}
410
411impl FromSql for DateTime {
412 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
413 Ok(Self(i64::column_result(value)?))
414 }
415}
416
417impl TryInto<SystemTime> for DateTime {
418 type Error = DateTimeError;
419
420 fn try_into(self) -> Result<SystemTime, Self::Error> {
421 // We want to construct a SystemTime representation equivalent to self, denoting
422 // a point in time THEN, but we cannot set the time directly. We can only construct
423 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
424 // and between EPOCH and THEN. With this common reference we can construct the
425 // duration between NOW and THEN which we can add to our SystemTime representation
426 // of NOW to get a SystemTime representation of THEN.
427 // Durations can only be positive, thus the if statement below.
428 let now = SystemTime::now();
429 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
430 let then_epoch = Duration::from_millis(self.0.try_into()?);
431 Ok(if now_epoch > then_epoch {
432 // then = now - (now_epoch - then_epoch)
433 now_epoch
434 .checked_sub(then_epoch)
435 .and_then(|d| now.checked_sub(d))
436 .ok_or(DateTimeError::TimeArithmetic)?
437 } else {
438 // then = now + (then_epoch - now_epoch)
439 then_epoch
440 .checked_sub(now_epoch)
441 .and_then(|d| now.checked_add(d))
442 .ok_or(DateTimeError::TimeArithmetic)?
443 })
444 }
445}
446
447impl TryFrom<SystemTime> for DateTime {
448 type Error = DateTimeError;
449
450 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
451 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
452 }
453}
454
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800455#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
456enum KeyLifeCycle {
457 /// Existing keys have a key ID but are not fully populated yet.
458 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
459 /// them to Unreferenced for garbage collection.
460 Existing,
461 /// A live key is fully populated and usable by clients.
462 Live,
463 /// An unreferenced key is scheduled for garbage collection.
464 Unreferenced,
465}
466
467impl ToSql for KeyLifeCycle {
468 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
469 match self {
470 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
471 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
472 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
473 }
474 }
475}
476
477impl FromSql for KeyLifeCycle {
478 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
479 match i64::column_result(value)? {
480 0 => Ok(KeyLifeCycle::Existing),
481 1 => Ok(KeyLifeCycle::Live),
482 2 => Ok(KeyLifeCycle::Unreferenced),
483 v => Err(FromSqlError::OutOfRange(v)),
484 }
485 }
486}
487
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700488/// Keys have a KeyMint blob component and optional public certificate and
489/// certificate chain components.
490/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
491/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800492#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700493pub struct KeyEntryLoadBits(u32);
494
495impl KeyEntryLoadBits {
496 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
497 pub const NONE: KeyEntryLoadBits = Self(0);
498 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
499 pub const KM: KeyEntryLoadBits = Self(1);
500 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
501 pub const PUBLIC: KeyEntryLoadBits = Self(2);
502 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
503 pub const BOTH: KeyEntryLoadBits = Self(3);
504
505 /// Returns true if this object indicates that the public components shall be loaded.
506 pub const fn load_public(&self) -> bool {
507 self.0 & Self::PUBLIC.0 != 0
508 }
509
510 /// Returns true if the object indicates that the KeyMint component shall be loaded.
511 pub const fn load_km(&self) -> bool {
512 self.0 & Self::KM.0 != 0
513 }
514}
515
Janis Danisevskisaec14592020-11-12 09:41:49 -0800516lazy_static! {
517 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
518}
519
520struct KeyIdLockDb {
521 locked_keys: Mutex<HashSet<i64>>,
522 cond_var: Condvar,
523}
524
525/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
526/// from the database a second time. Most functions manipulating the key blob database
527/// require a KeyIdGuard.
528#[derive(Debug)]
529pub struct KeyIdGuard(i64);
530
531impl KeyIdLockDb {
532 fn new() -> Self {
533 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
534 }
535
536 /// This function blocks until an exclusive lock for the given key entry id can
537 /// be acquired. It returns a guard object, that represents the lifecycle of the
538 /// acquired lock.
539 pub fn get(&self, key_id: i64) -> KeyIdGuard {
540 let mut locked_keys = self.locked_keys.lock().unwrap();
541 while locked_keys.contains(&key_id) {
542 locked_keys = self.cond_var.wait(locked_keys).unwrap();
543 }
544 locked_keys.insert(key_id);
545 KeyIdGuard(key_id)
546 }
547
548 /// This function attempts to acquire an exclusive lock on a given key id. If the
549 /// given key id is already taken the function returns None immediately. If a lock
550 /// can be acquired this function returns a guard object, that represents the
551 /// lifecycle of the acquired lock.
552 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
553 let mut locked_keys = self.locked_keys.lock().unwrap();
554 if locked_keys.insert(key_id) {
555 Some(KeyIdGuard(key_id))
556 } else {
557 None
558 }
559 }
560}
561
562impl KeyIdGuard {
563 /// Get the numeric key id of the locked key.
564 pub fn id(&self) -> i64 {
565 self.0
566 }
567}
568
569impl Drop for KeyIdGuard {
570 fn drop(&mut self) {
571 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
572 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800573 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800574 KEY_ID_LOCK.cond_var.notify_all();
575 }
576}
577
Max Bires8e93d2b2021-01-14 13:17:59 -0800578/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700579#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800580pub struct CertificateInfo {
581 cert: Option<Vec<u8>>,
582 cert_chain: Option<Vec<u8>>,
583}
584
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800585/// This type represents a Blob with its metadata and an optional superseded blob.
586#[derive(Debug)]
587pub struct BlobInfo<'a> {
588 blob: &'a [u8],
589 metadata: &'a BlobMetaData,
590 /// Superseded blobs are an artifact of legacy import. In some rare occasions
591 /// the key blob needs to be upgraded during import. In that case two
592 /// blob are imported, the superseded one will have to be imported first,
593 /// so that the garbage collector can reap it.
594 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
595}
596
597impl<'a> BlobInfo<'a> {
598 /// Create a new instance of blob info with blob and corresponding metadata
599 /// and no superseded blob info.
600 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
601 Self { blob, metadata, superseded_blob: None }
602 }
603
604 /// Create a new instance of blob info with blob and corresponding metadata
605 /// as well as superseded blob info.
606 pub fn new_with_superseded(
607 blob: &'a [u8],
608 metadata: &'a BlobMetaData,
609 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
610 ) -> Self {
611 Self { blob, metadata, superseded_blob }
612 }
613}
614
Max Bires8e93d2b2021-01-14 13:17:59 -0800615impl CertificateInfo {
616 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
617 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
618 Self { cert, cert_chain }
619 }
620
621 /// Take the cert
622 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
623 self.cert.take()
624 }
625
626 /// Take the cert chain
627 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
628 self.cert_chain.take()
629 }
630}
631
Max Bires2b2e6562020-09-22 11:22:36 -0700632/// This type represents a certificate chain with a private key corresponding to the leaf
633/// 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 -0700634pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800635 /// A KM key blob
636 pub private_key: ZVec,
637 /// A batch cert for private_key
638 pub batch_cert: Vec<u8>,
639 /// A full certificate chain from root signing authority to private_key, including batch_cert
640 /// for convenience.
641 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700642}
643
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700644/// This type represents a Keystore 2.0 key entry.
645/// An entry has a unique `id` by which it can be found in the database.
646/// It has a security level field, key parameters, and three optional fields
647/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800648#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700649pub struct KeyEntry {
650 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800651 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700652 cert: Option<Vec<u8>>,
653 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800654 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700655 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800656 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800657 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700658}
659
660impl KeyEntry {
661 /// Returns the unique id of the Key entry.
662 pub fn id(&self) -> i64 {
663 self.id
664 }
665 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800666 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
667 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700668 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800669 /// Extracts the Optional KeyMint blob including its metadata.
670 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
671 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700672 }
673 /// Exposes the optional public certificate.
674 pub fn cert(&self) -> &Option<Vec<u8>> {
675 &self.cert
676 }
677 /// Extracts the optional public certificate.
678 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
679 self.cert.take()
680 }
681 /// Exposes the optional public certificate chain.
682 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
683 &self.cert_chain
684 }
685 /// Extracts the optional public certificate_chain.
686 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
687 self.cert_chain.take()
688 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800689 /// Returns the uuid of the owning KeyMint instance.
690 pub fn km_uuid(&self) -> &Uuid {
691 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700692 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700693 /// Exposes the key parameters of this key entry.
694 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
695 &self.parameters
696 }
697 /// Consumes this key entry and extracts the keyparameters from it.
698 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
699 self.parameters
700 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800701 /// Exposes the key metadata of this key entry.
702 pub fn metadata(&self) -> &KeyMetaData {
703 &self.metadata
704 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800705 /// This returns true if the entry is a pure certificate entry with no
706 /// private key component.
707 pub fn pure_cert(&self) -> bool {
708 self.pure_cert
709 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000710 /// Consumes this key entry and extracts the keyparameters and metadata from it.
711 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
712 (self.parameters, self.metadata)
713 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700714}
715
716/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800717#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700718pub struct SubComponentType(u32);
719impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800720 /// Persistent identifier for a key blob.
721 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700722 /// Persistent identifier for a certificate blob.
723 pub const CERT: SubComponentType = Self(1);
724 /// Persistent identifier for a certificate chain blob.
725 pub const CERT_CHAIN: SubComponentType = Self(2);
726}
727
728impl ToSql for SubComponentType {
729 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
730 self.0.to_sql()
731 }
732}
733
734impl FromSql for SubComponentType {
735 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
736 Ok(Self(u32::column_result(value)?))
737 }
738}
739
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800740/// This trait is private to the database module. It is used to convey whether or not the garbage
741/// collector shall be invoked after a database access. All closures passed to
742/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
743/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
744/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
745/// `.need_gc()`.
746trait DoGc<T> {
747 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
748
749 fn no_gc(self) -> Result<(bool, T)>;
750
751 fn need_gc(self) -> Result<(bool, T)>;
752}
753
754impl<T> DoGc<T> for Result<T> {
755 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
756 self.map(|r| (need_gc, r))
757 }
758
759 fn no_gc(self) -> Result<(bool, T)> {
760 self.do_gc(false)
761 }
762
763 fn need_gc(self) -> Result<(bool, T)> {
764 self.do_gc(true)
765 }
766}
767
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700768/// KeystoreDB wraps a connection to an SQLite database and tracks its
769/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700770pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700771 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700772 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700773 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700774}
775
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000776/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000777/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000778#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
779pub struct MonotonicRawTime(i64);
780
781impl MonotonicRawTime {
782 /// Constructs a new MonotonicRawTime
783 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000784 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000785 }
786
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000787 /// Returns the value of MonotonicRawTime in milliseconds as i64
788 pub fn milliseconds(&self) -> i64 {
789 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000790 }
791
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000792 /// Returns the integer value of MonotonicRawTime as i64
793 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000794 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000795 }
796
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800797 /// Like i64::checked_sub.
798 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
799 self.0.checked_sub(other.0).map(Self)
800 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000801}
802
803impl ToSql for MonotonicRawTime {
804 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
805 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
806 }
807}
808
809impl FromSql for MonotonicRawTime {
810 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
811 Ok(Self(i64::column_result(value)?))
812 }
813}
814
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000815/// This struct encapsulates the information to be stored in the database about the auth tokens
816/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700817#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818pub struct AuthTokenEntry {
819 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000820 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000821 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822}
823
824impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000825 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000826 AuthTokenEntry { auth_token, time_received }
827 }
828
829 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800830 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000831 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800832 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
833 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000834 })
835 }
836
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000837 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800838 pub fn auth_token(&self) -> &HardwareAuthToken {
839 &self.auth_token
840 }
841
842 /// Returns the auth token wrapped by the AuthTokenEntry
843 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000844 self.auth_token
845 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800846
847 /// Returns the time that this auth token was received.
848 pub fn time_received(&self) -> MonotonicRawTime {
849 self.time_received
850 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000851
852 /// Returns the challenge value of the auth token.
853 pub fn challenge(&self) -> i64 {
854 self.auth_token.challenge
855 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000856}
857
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800858/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
859/// This object does not allow access to the database connection. But it keeps a database
860/// connection alive in order to keep the in memory per boot database alive.
861pub struct PerBootDbKeepAlive(Connection);
862
Joel Galenson26f4d012020-07-17 14:57:21 -0700863impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800864 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700865 const CURRENT_DB_VERSION: u32 = 1;
866 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800867
Seth Moore78c091f2021-04-09 21:38:30 +0000868 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700869 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000870
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700871 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800872 /// files persistent.sqlite and perboot.sqlite in the given directory.
873 /// It also attempts to initialize all of the tables.
874 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700875 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700876 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700877 let _wp = wd::watch_millis("KeystoreDB::new", 500);
878
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700879 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700880 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800881
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700882 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800883 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700884 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000885 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800886 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800887 })?;
888 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700889 }
890
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700891 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
892 // cryptographic binding to the boot level keys was implemented.
893 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
894 tx.execute(
895 "UPDATE persistent.keyentry SET state = ?
896 WHERE
897 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
898 AND
899 id NOT IN (
900 SELECT keyentryid FROM persistent.blobentry
901 WHERE id IN (
902 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
903 )
904 );",
905 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
906 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000907 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700908 Ok(1)
909 }
910
Janis Danisevskis66784c42021-01-27 08:40:25 -0800911 fn init_tables(tx: &Transaction) -> Result<()> {
912 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700913 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700914 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800915 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700916 domain INTEGER,
917 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800918 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800919 state INTEGER,
920 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700921 NO_PARAMS,
922 )
923 .context("Failed to initialize \"keyentry\" table.")?;
924
Janis Danisevskis66784c42021-01-27 08:40:25 -0800925 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800926 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
927 ON keyentry(id);",
928 NO_PARAMS,
929 )
930 .context("Failed to create index keyentry_id_index.")?;
931
932 tx.execute(
933 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
934 ON keyentry(domain, namespace, alias);",
935 NO_PARAMS,
936 )
937 .context("Failed to create index keyentry_domain_namespace_index.")?;
938
939 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700940 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
941 id INTEGER PRIMARY KEY,
942 subcomponent_type INTEGER,
943 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800944 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700945 NO_PARAMS,
946 )
947 .context("Failed to initialize \"blobentry\" table.")?;
948
Janis Danisevskis66784c42021-01-27 08:40:25 -0800949 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800950 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
951 ON blobentry(keyentryid);",
952 NO_PARAMS,
953 )
954 .context("Failed to create index blobentry_keyentryid_index.")?;
955
956 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800957 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
958 id INTEGER PRIMARY KEY,
959 blobentryid INTEGER,
960 tag INTEGER,
961 data ANY,
962 UNIQUE (blobentryid, tag));",
963 NO_PARAMS,
964 )
965 .context("Failed to initialize \"blobmetadata\" table.")?;
966
967 tx.execute(
968 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
969 ON blobmetadata(blobentryid);",
970 NO_PARAMS,
971 )
972 .context("Failed to create index blobmetadata_blobentryid_index.")?;
973
974 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700975 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000976 keyentryid INTEGER,
977 tag INTEGER,
978 data ANY,
979 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700980 NO_PARAMS,
981 )
982 .context("Failed to initialize \"keyparameter\" table.")?;
983
Janis Danisevskis66784c42021-01-27 08:40:25 -0800984 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800985 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
986 ON keyparameter(keyentryid);",
987 NO_PARAMS,
988 )
989 .context("Failed to create index keyparameter_keyentryid_index.")?;
990
991 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800992 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
993 keyentryid INTEGER,
994 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000995 data ANY,
996 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800997 NO_PARAMS,
998 )
999 .context("Failed to initialize \"keymetadata\" table.")?;
1000
Janis Danisevskis66784c42021-01-27 08:40:25 -08001001 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -08001002 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
1003 ON keymetadata(keyentryid);",
1004 NO_PARAMS,
1005 )
1006 .context("Failed to create index keymetadata_keyentryid_index.")?;
1007
1008 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001009 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001010 id INTEGER UNIQUE,
1011 grantee INTEGER,
1012 keyentryid INTEGER,
1013 access_vector INTEGER);",
1014 NO_PARAMS,
1015 )
1016 .context("Failed to initialize \"grant\" table.")?;
1017
Joel Galenson0891bc12020-07-20 10:37:03 -07001018 Ok(())
1019 }
1020
Seth Moore472fcbb2021-05-12 10:07:51 -07001021 fn make_persistent_path(db_root: &Path) -> Result<String> {
1022 // Build the path to the sqlite file.
1023 let mut persistent_path = db_root.to_path_buf();
1024 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1025
1026 // Now convert them to strings prefixed with "file:"
1027 let mut persistent_path_str = "file:".to_owned();
1028 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1029
1030 Ok(persistent_path_str)
1031 }
1032
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001033 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001034 let conn =
1035 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1036
Janis Danisevskis66784c42021-01-27 08:40:25 -08001037 loop {
1038 if let Err(e) = conn
1039 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1040 .context("Failed to attach database persistent.")
1041 {
1042 if Self::is_locked_error(&e) {
1043 std::thread::sleep(std::time::Duration::from_micros(500));
1044 continue;
1045 } else {
1046 return Err(e);
1047 }
1048 }
1049 break;
1050 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001051
Matthew Maurer4fb19112021-05-06 15:40:44 -07001052 // Drop the cache size from default (2M) to 0.5M
1053 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1054 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001055
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001056 Ok(conn)
1057 }
1058
Seth Moore78c091f2021-04-09 21:38:30 +00001059 fn do_table_size_query(
1060 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001061 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001062 query: &str,
1063 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001064 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001065 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001066 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001067 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001068 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001069 })
1070 .no_gc()
1071 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001072 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001073 }
1074
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001075 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001076 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001077 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001078 "SELECT page_count * page_size, freelist_count * page_size
1079 FROM pragma_page_count('persistent'),
1080 pragma_page_size('persistent'),
1081 persistent.pragma_freelist_count();",
1082 &[],
1083 )
1084 }
1085
1086 fn get_table_size(
1087 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001088 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001089 schema: &str,
1090 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001091 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001092 self.do_table_size_query(
1093 storage_type,
1094 "SELECT pgsize,unused FROM dbstat(?1)
1095 WHERE name=?2 AND aggregate=TRUE;",
1096 &[schema, table],
1097 )
1098 }
1099
1100 /// Fetches a storage statisitics atom for a given storage type. For storage
1101 /// types that map to a table, information about the table's storage is
1102 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001103 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001104 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1105
Seth Moore78c091f2021-04-09 21:38:30 +00001106 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 MetricsStorage::DATABASE => self.get_total_size(),
1108 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001109 self.get_table_size(storage_type, "persistent", "keyentry")
1110 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001111 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001112 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1113 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001114 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001115 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1116 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001117 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001118 self.get_table_size(storage_type, "persistent", "blobentry")
1119 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001120 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001121 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1122 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001123 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001124 self.get_table_size(storage_type, "persistent", "keyparameter")
1125 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001126 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001127 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1128 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001129 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001130 self.get_table_size(storage_type, "persistent", "keymetadata")
1131 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001132 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001133 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1134 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001135 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1136 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001137 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1138 // reportable
1139 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001140 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001141 storage_type,
1142 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001143 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001144 unused_size: 0,
1145 })
Seth Moore78c091f2021-04-09 21:38:30 +00001146 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001147 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001148 self.get_table_size(storage_type, "persistent", "blobmetadata")
1149 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001150 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001151 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1152 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001153 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001154 }
1155 }
1156
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001157 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001158 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1159 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001160 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1161 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001162 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001163 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001164 blob_ids_to_delete: &[i64],
1165 max_blobs: usize,
1166 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001167 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001168 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001169 // Delete the given blobs.
1170 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001171 tx.execute(
1172 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001173 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001174 )
1175 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001176 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1177 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001178 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001179
1180 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1181
Janis Danisevskis3395f862021-05-06 10:54:17 -07001182 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1183 let result: Vec<(i64, Vec<u8>)> = {
1184 let mut stmt = tx
1185 .prepare(
1186 "SELECT id, blob FROM persistent.blobentry
1187 WHERE subcomponent_type = ?
1188 AND (
1189 id NOT IN (
1190 SELECT MAX(id) FROM persistent.blobentry
1191 WHERE subcomponent_type = ?
1192 GROUP BY keyentryid, subcomponent_type
1193 )
1194 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1195 ) LIMIT ?;",
1196 )
1197 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001198
Janis Danisevskis3395f862021-05-06 10:54:17 -07001199 let rows = stmt
1200 .query_map(
1201 params![
1202 SubComponentType::KEY_BLOB,
1203 SubComponentType::KEY_BLOB,
1204 max_blobs as i64,
1205 ],
1206 |row| Ok((row.get(0)?, row.get(1)?)),
1207 )
1208 .context("Trying to query superseded blob.")?;
1209
1210 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1211 .context("Trying to extract superseded blobs.")?
1212 };
1213
1214 let result = result
1215 .into_iter()
1216 .map(|(blob_id, blob)| {
1217 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1218 })
1219 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1220 .context("Trying to load blob metadata.")?;
1221 if !result.is_empty() {
1222 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001223 }
1224
1225 // We did not find any superseded key blob, so let's remove other superseded blob in
1226 // one transaction.
1227 tx.execute(
1228 "DELETE FROM persistent.blobentry
1229 WHERE NOT subcomponent_type = ?
1230 AND (
1231 id NOT IN (
1232 SELECT MAX(id) FROM persistent.blobentry
1233 WHERE NOT subcomponent_type = ?
1234 GROUP BY keyentryid, subcomponent_type
1235 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1236 );",
1237 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1238 )
1239 .context("Trying to purge superseded blobs.")?;
1240
Janis Danisevskis3395f862021-05-06 10:54:17 -07001241 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001242 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001243 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001244 }
1245
1246 /// This maintenance function should be called only once before the database is used for the
1247 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1248 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1249 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1250 /// Keystore crashed at some point during key generation. Callers may want to log such
1251 /// occurrences.
1252 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1253 /// it to `KeyLifeCycle::Live` may have grants.
1254 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001255 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1256
Janis Danisevskis66784c42021-01-27 08:40:25 -08001257 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1258 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001259 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1260 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1261 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001262 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001263 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001264 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001265 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001266 }
1267
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001268 /// Checks if a key exists with given key type and key descriptor properties.
1269 pub fn key_exists(
1270 &mut self,
1271 domain: Domain,
1272 nspace: i64,
1273 alias: &str,
1274 key_type: KeyType,
1275 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001276 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1277
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001278 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1279 let key_descriptor =
1280 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001281 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001282 match result {
1283 Ok(_) => Ok(true),
1284 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1285 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001286 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001287 },
1288 }
1289 .no_gc()
1290 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001291 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001292 }
1293
Hasini Gunasingheda895552021-01-27 19:34:37 +00001294 /// Stores a super key in the database.
1295 pub fn store_super_key(
1296 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001297 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001298 key_type: &SuperKeyType,
1299 blob: &[u8],
1300 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001301 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001302 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001303 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1304
Hasini Gunasingheda895552021-01-27 19:34:37 +00001305 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1306 let key_id = Self::insert_with_retry(|id| {
1307 tx.execute(
1308 "INSERT into persistent.keyentry
1309 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001310 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001311 params![
1312 id,
1313 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001314 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001315 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001316 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001317 KeyLifeCycle::Live,
1318 &KEYSTORE_UUID,
1319 ],
1320 )
1321 })
1322 .context("Failed to insert into keyentry table.")?;
1323
Paul Crowley8d5b2532021-03-19 10:53:07 -07001324 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1325
Hasini Gunasingheda895552021-01-27 19:34:37 +00001326 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001327 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001328 key_id,
1329 SubComponentType::KEY_BLOB,
1330 Some(blob),
1331 Some(blob_metadata),
1332 )
1333 .context("Failed to store key blob.")?;
1334
1335 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1336 .context("Trying to load key components.")
1337 .no_gc()
1338 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001339 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001340 }
1341
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001342 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001343 pub fn load_super_key(
1344 &mut self,
1345 key_type: &SuperKeyType,
1346 user_id: u32,
1347 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001348 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1349
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001350 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1351 let key_descriptor = KeyDescriptor {
1352 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001353 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001354 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001355 blob: None,
1356 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001357 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001358 match id {
1359 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001360 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001361 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001362 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1363 }
1364 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1365 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001366 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001367 },
1368 }
1369 .no_gc()
1370 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001371 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001372 }
1373
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001374 /// Atomically loads a key entry and associated metadata or creates it using the
1375 /// callback create_new_key callback. The callback is called during a database
1376 /// transaction. This means that implementers should be mindful about using
1377 /// blocking operations such as IPC or grabbing mutexes.
1378 pub fn get_or_create_key_with<F>(
1379 &mut self,
1380 domain: Domain,
1381 namespace: i64,
1382 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001383 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001384 create_new_key: F,
1385 ) -> Result<(KeyIdGuard, KeyEntry)>
1386 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001387 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001388 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001389 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1390
Janis Danisevskis66784c42021-01-27 08:40:25 -08001391 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1392 let id = {
1393 let mut stmt = tx
1394 .prepare(
1395 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001396 WHERE
1397 key_type = ?
1398 AND domain = ?
1399 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001400 AND alias = ?
1401 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001402 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001403 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 let mut rows = stmt
1405 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001406 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001407
Janis Danisevskis66784c42021-01-27 08:40:25 -08001408 db_utils::with_rows_extract_one(&mut rows, |row| {
1409 Ok(match row {
1410 Some(r) => r.get(0).context("Failed to unpack id.")?,
1411 None => None,
1412 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001413 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001414 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001415 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001416
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 let (id, entry) = match id {
1418 Some(id) => (
1419 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001420 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001421 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001422
Janis Danisevskis66784c42021-01-27 08:40:25 -08001423 None => {
1424 let id = Self::insert_with_retry(|id| {
1425 tx.execute(
1426 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001427 (id, key_type, domain, namespace, alias, state, km_uuid)
1428 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001429 params![
1430 id,
1431 KeyType::Super,
1432 domain.0,
1433 namespace,
1434 alias,
1435 KeyLifeCycle::Live,
1436 km_uuid,
1437 ],
1438 )
1439 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001440 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001441
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001442 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001443 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001444 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001445 id,
1446 SubComponentType::KEY_BLOB,
1447 Some(&blob),
1448 Some(&metadata),
1449 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001450 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001451 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001452 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001453 KeyEntry {
1454 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001455 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001456 pure_cert: false,
1457 ..Default::default()
1458 },
1459 )
1460 }
1461 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001462 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001463 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001464 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001465 }
1466
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001467 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001468 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1469 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001470 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1471 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001472 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001473 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001474 loop {
1475 match self
1476 .conn
1477 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001478 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001479 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1480 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001481 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001482 Ok(result)
1483 }) {
1484 Ok(result) => break Ok(result),
1485 Err(e) => {
1486 if Self::is_locked_error(&e) {
1487 std::thread::sleep(std::time::Duration::from_micros(500));
1488 continue;
1489 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001490 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001491 }
1492 }
1493 }
1494 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001495 .map(|(need_gc, result)| {
1496 if need_gc {
1497 if let Some(ref gc) = self.gc {
1498 gc.notify_gc();
1499 }
1500 }
1501 result
1502 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001503 }
1504
1505 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001506 matches!(
1507 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1508 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1509 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1510 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001511 }
1512
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001513 /// Creates a new key entry and allocates a new randomized id for the new key.
1514 /// The key id gets associated with a domain and namespace but not with an alias.
1515 /// To complete key generation `rebind_alias` should be called after all of the
1516 /// key artifacts, i.e., blobs and parameters have been associated with the new
1517 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1518 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001519 pub fn create_key_entry(
1520 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001521 domain: &Domain,
1522 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001523 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001524 km_uuid: &Uuid,
1525 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001526 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1527
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001529 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001530 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001531 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001532 }
1533
1534 fn create_key_entry_internal(
1535 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001536 domain: &Domain,
1537 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001538 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001539 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001540 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001541 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001542 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001543 _ => {
1544 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001545 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001546 }
1547 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001548 Ok(KEY_ID_LOCK.get(
1549 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001550 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001551 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001552 (id, key_type, domain, namespace, alias, state, km_uuid)
1553 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001554 params![
1555 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001556 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001557 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001558 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001559 KeyLifeCycle::Existing,
1560 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001561 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001562 )
1563 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001564 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001565 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001566 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001567
Max Bires2b2e6562020-09-22 11:22:36 -07001568 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1569 /// The key id gets associated with a domain and namespace later but not with an alias. The
1570 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1571 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1572 /// a key.
1573 pub fn create_attestation_key_entry(
1574 &mut self,
1575 maced_public_key: &[u8],
1576 raw_public_key: &[u8],
1577 private_key: &[u8],
1578 km_uuid: &Uuid,
1579 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001580 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1581
Max Bires2b2e6562020-09-22 11:22:36 -07001582 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1583 let key_id = KEY_ID_LOCK.get(
1584 Self::insert_with_retry(|id| {
1585 tx.execute(
1586 "INSERT into persistent.keyentry
1587 (id, key_type, domain, namespace, alias, state, km_uuid)
1588 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1589 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1590 )
1591 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001592 .context(ks_err!())?,
Max Bires2b2e6562020-09-22 11:22:36 -07001593 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001594 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001595 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001596 key_id.0,
1597 SubComponentType::KEY_BLOB,
1598 Some(private_key),
1599 None,
1600 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001601 let mut metadata = KeyMetaData::new();
1602 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1603 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001604 metadata.store_in_db(key_id.0, tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001605 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001606 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001607 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001608 }
1609
Janis Danisevskis377d1002021-01-27 19:07:48 -08001610 /// Set a new blob and associates it with the given key id. Each blob
1611 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001612 /// Each key can have one of each sub component type associated. If more
1613 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001614 /// will get garbage collected.
1615 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1616 /// removed by setting blob to None.
1617 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001618 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001619 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001620 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001621 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001622 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001623 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001624 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1625
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001626 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001627 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001628 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001629 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001630 }
1631
Janis Danisevskiseed69842021-02-18 20:04:10 -08001632 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1633 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1634 /// We use this to insert key blobs into the database which can then be garbage collected
1635 /// lazily by the key garbage collector.
1636 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001637 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1638
Janis Danisevskiseed69842021-02-18 20:04:10 -08001639 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1640 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001641 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001642 Self::UNASSIGNED_KEY_ID,
1643 SubComponentType::KEY_BLOB,
1644 Some(blob),
1645 Some(blob_metadata),
1646 )
1647 .need_gc()
1648 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001649 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001650 }
1651
Janis Danisevskis377d1002021-01-27 19:07:48 -08001652 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001653 tx: &Transaction,
1654 key_id: i64,
1655 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001656 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001657 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001658 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001659 match (blob, sc_type) {
1660 (Some(blob), _) => {
1661 tx.execute(
1662 "INSERT INTO persistent.blobentry
1663 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1664 params![sc_type, key_id, blob],
1665 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001666 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001667 if let Some(blob_metadata) = blob_metadata {
1668 let blob_id = tx
1669 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1670 row.get(0)
1671 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001672 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001673 blob_metadata
1674 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001675 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001676 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001677 }
1678 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1679 tx.execute(
1680 "DELETE FROM persistent.blobentry
1681 WHERE subcomponent_type = ? AND keyentryid = ?;",
1682 params![sc_type, key_id],
1683 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001684 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001685 }
1686 (None, _) => {
1687 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001688 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001689 }
1690 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001691 Ok(())
1692 }
1693
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001694 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1695 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001696 #[cfg(test)]
1697 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001698 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001699 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001700 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001701 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001702 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001703
Janis Danisevskis66784c42021-01-27 08:40:25 -08001704 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001705 tx: &Transaction,
1706 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001707 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001708 ) -> Result<()> {
1709 let mut stmt = tx
1710 .prepare(
1711 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1712 VALUES (?, ?, ?, ?);",
1713 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001714 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001715
Janis Danisevskis66784c42021-01-27 08:40:25 -08001716 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001717 stmt.insert(params![
1718 key_id.0,
1719 p.get_tag().0,
1720 p.key_parameter_value(),
1721 p.security_level().0
1722 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001723 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001724 }
1725 Ok(())
1726 }
1727
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001728 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001729 #[cfg(test)]
1730 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001731 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001732 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001734 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001735 }
1736
Max Bires2b2e6562020-09-22 11:22:36 -07001737 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1738 /// on the public key.
1739 pub fn store_signed_attestation_certificate_chain(
1740 &mut self,
1741 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001742 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001743 cert_chain: &[u8],
1744 expiration_date: i64,
1745 km_uuid: &Uuid,
1746 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001747 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1748
Max Bires2b2e6562020-09-22 11:22:36 -07001749 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1750 let mut stmt = tx
1751 .prepare(
1752 "SELECT keyentryid
1753 FROM persistent.keymetadata
1754 WHERE tag = ? AND data = ? AND keyentryid IN
1755 (SELECT id
1756 FROM persistent.keyentry
1757 WHERE
1758 alias IS NULL AND
1759 domain IS NULL AND
1760 namespace IS NULL AND
1761 key_type = ? AND
1762 km_uuid = ?);",
1763 )
1764 .context("Failed to store attestation certificate chain.")?;
1765 let mut rows = stmt
1766 .query(params![
1767 KeyMetaData::AttestationRawPubKey,
1768 raw_public_key,
1769 KeyType::Attestation,
1770 km_uuid
1771 ])
1772 .context("Failed to fetch keyid")?;
1773 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1774 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1775 .get(0)
1776 .context("Failed to unpack id.")
1777 })
1778 .context("Failed to get key_id.")?;
1779 let num_updated = tx
1780 .execute(
1781 "UPDATE persistent.keyentry
1782 SET alias = ?
1783 WHERE id = ?;",
1784 params!["signed", key_id],
1785 )
1786 .context("Failed to update alias.")?;
1787 if num_updated != 1 {
1788 return Err(KsError::sys()).context("Alias not updated for the key.");
1789 }
1790 let mut metadata = KeyMetaData::new();
1791 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1792 expiration_date,
1793 )));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001794 metadata.store_in_db(key_id, tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001795 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001796 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001797 key_id,
1798 SubComponentType::CERT_CHAIN,
1799 Some(cert_chain),
1800 None,
1801 )
1802 .context("Failed to insert cert chain")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001803 Self::set_blob_internal(tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
Max Biresb2e1d032021-02-08 21:35:05 -08001804 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001805 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001806 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001807 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001808 }
1809
1810 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1811 /// currently have a key assigned to it.
1812 pub fn assign_attestation_key(
1813 &mut self,
1814 domain: Domain,
1815 namespace: i64,
1816 km_uuid: &Uuid,
1817 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001818 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1819
Max Bires2b2e6562020-09-22 11:22:36 -07001820 match domain {
1821 Domain::APP | Domain::SELINUX => {}
1822 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001823 return Err(KsError::sys())
1824 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Max Bires2b2e6562020-09-22 11:22:36 -07001825 }
1826 }
1827 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1828 let result = tx
1829 .execute(
1830 "UPDATE persistent.keyentry
1831 SET domain=?1, namespace=?2
1832 WHERE
1833 id =
1834 (SELECT MIN(id)
1835 FROM persistent.keyentry
1836 WHERE ALIAS IS NOT NULL
1837 AND domain IS NULL
1838 AND key_type IS ?3
1839 AND state IS ?4
1840 AND km_uuid IS ?5)
1841 AND
1842 (SELECT COUNT(*)
1843 FROM persistent.keyentry
1844 WHERE domain=?1
1845 AND namespace=?2
1846 AND key_type IS ?3
1847 AND state IS ?4
1848 AND km_uuid IS ?5) = 0;",
1849 params![
1850 domain.0 as u32,
1851 namespace,
1852 KeyType::Attestation,
1853 KeyLifeCycle::Live,
1854 km_uuid,
1855 ],
1856 )
1857 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001858 if result == 0 {
Hasini Gunasinghe1a8524b2022-05-10 08:49:53 +00001859 let (_, hw_info) = get_keymint_dev_by_uuid(km_uuid)
1860 .context("Error in retrieving keymint device by UUID.")?;
1861 log_rkp_error_stats(MetricsRkpError::OUT_OF_KEYS, &hw_info.securityLevel);
Max Bires01f8af22021-03-02 23:24:50 -08001862 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1863 } else if result > 1 {
1864 return Err(KsError::sys())
1865 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001866 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001867 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001868 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001869 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001870 }
1871
1872 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1873 /// provisioning server, or the maximum number available if there are not num_keys number of
1874 /// entries in the table.
1875 pub fn fetch_unsigned_attestation_keys(
1876 &mut self,
1877 num_keys: i32,
1878 km_uuid: &Uuid,
1879 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001880 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1881
Max Bires2b2e6562020-09-22 11:22:36 -07001882 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1883 let mut stmt = tx
1884 .prepare(
1885 "SELECT data
1886 FROM persistent.keymetadata
1887 WHERE tag = ? AND keyentryid IN
1888 (SELECT id
1889 FROM persistent.keyentry
1890 WHERE
1891 alias IS NULL AND
1892 domain IS NULL AND
1893 namespace IS NULL AND
1894 key_type = ? AND
1895 km_uuid = ?
1896 LIMIT ?);",
1897 )
1898 .context("Failed to prepare statement")?;
1899 let rows = stmt
1900 .query_map(
1901 params![
1902 KeyMetaData::AttestationMacedPublicKey,
1903 KeyType::Attestation,
1904 km_uuid,
1905 num_keys
1906 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001907 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001908 )?
1909 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1910 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001911 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001912 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001913 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001914 }
1915
1916 /// Removes any keys that have expired as of the current time. Returns the number of keys
1917 /// marked unreferenced that are bound to be garbage collected.
1918 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001919 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1920
Max Bires2b2e6562020-09-22 11:22:36 -07001921 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1922 let mut stmt = tx
1923 .prepare(
1924 "SELECT keyentryid, data
1925 FROM persistent.keymetadata
1926 WHERE tag = ? AND keyentryid IN
1927 (SELECT id
1928 FROM persistent.keyentry
1929 WHERE key_type = ?);",
1930 )
1931 .context("Failed to prepare query")?;
1932 let key_ids_to_check = stmt
1933 .query_map(
1934 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1935 |row| Ok((row.get(0)?, row.get(1)?)),
1936 )?
1937 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1938 .context("Failed to get date metadata")?;
Max Birescd7f7412022-02-11 13:47:36 -08001939 // Calculate curr_time with a discount factor to avoid a key that's milliseconds away
1940 // from expiration dodging this delete call.
Max Bires2b2e6562020-09-22 11:22:36 -07001941 let curr_time = DateTime::from_millis_epoch(
Max Birescd7f7412022-02-11 13:47:36 -08001942 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
1943 + EXPIRATION_BUFFER_MS,
Max Bires2b2e6562020-09-22 11:22:36 -07001944 );
1945 let mut num_deleted = 0;
1946 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001947 if Self::mark_unreferenced(tx, id)? {
Max Bires2b2e6562020-09-22 11:22:36 -07001948 num_deleted += 1;
1949 }
1950 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001951 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001952 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001953 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001954 }
1955
Max Bires60d7ed12021-03-05 15:59:22 -08001956 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1957 /// they are in. This is useful primarily as a testing mechanism.
1958 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001959 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1960
Max Bires60d7ed12021-03-05 15:59:22 -08001961 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1962 let mut stmt = tx
1963 .prepare(
1964 "SELECT id FROM persistent.keyentry
1965 WHERE key_type IS ?;",
1966 )
1967 .context("Failed to prepare statement")?;
1968 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001969 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001970 .collect::<rusqlite::Result<Vec<i64>>>()
1971 .context("Failed to execute statement")?;
1972 let num_deleted = keys_to_delete
1973 .iter()
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001974 .map(|id| Self::mark_unreferenced(tx, *id))
Max Bires60d7ed12021-03-05 15:59:22 -08001975 .collect::<Result<Vec<bool>>>()
1976 .context("Failed to execute mark_unreferenced on a keyid")?
1977 .into_iter()
1978 .filter(|result| *result)
1979 .count() as i64;
1980 Ok(num_deleted).do_gc(num_deleted != 0)
1981 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001982 .context(ks_err!())
Max Bires60d7ed12021-03-05 15:59:22 -08001983 }
1984
Max Bires2b2e6562020-09-22 11:22:36 -07001985 /// Counts the number of keys that will expire by the provided epoch date and the number of
1986 /// keys not currently assigned to a domain.
1987 pub fn get_attestation_pool_status(
1988 &mut self,
1989 date: i64,
1990 km_uuid: &Uuid,
1991 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001992 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1993
Max Bires2b2e6562020-09-22 11:22:36 -07001994 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1995 let mut stmt = tx.prepare(
1996 "SELECT data
1997 FROM persistent.keymetadata
1998 WHERE tag = ? AND keyentryid IN
1999 (SELECT id
2000 FROM persistent.keyentry
2001 WHERE alias IS NOT NULL
2002 AND key_type = ?
2003 AND km_uuid = ?
2004 AND state = ?);",
2005 )?;
2006 let times = stmt
2007 .query_map(
2008 params![
2009 KeyMetaData::AttestationExpirationDate,
2010 KeyType::Attestation,
2011 km_uuid,
2012 KeyLifeCycle::Live
2013 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002014 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002015 )?
2016 .collect::<rusqlite::Result<Vec<DateTime>>>()
2017 .context("Failed to execute metadata statement")?;
2018 let expiring =
2019 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2020 as i32;
2021 stmt = tx.prepare(
2022 "SELECT alias, domain
2023 FROM persistent.keyentry
2024 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2025 )?;
2026 let rows = stmt
2027 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2028 Ok((row.get(0)?, row.get(1)?))
2029 })?
2030 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2031 .context("Failed to execute keyentry statement")?;
2032 let mut unassigned = 0i32;
2033 let mut attested = 0i32;
2034 let total = rows.len() as i32;
2035 for (alias, domain) in rows {
2036 match (alias, domain) {
2037 (Some(_alias), None) => {
2038 attested += 1;
2039 unassigned += 1;
2040 }
2041 (Some(_alias), Some(_domain)) => {
2042 attested += 1;
2043 }
2044 _ => {}
2045 }
2046 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002047 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002048 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002049 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07002050 }
2051
Max Bires55620ff2022-02-11 13:34:15 -08002052 fn query_kid_for_attestation_key_and_cert_chain(
2053 &self,
2054 tx: &Transaction,
2055 domain: Domain,
2056 namespace: i64,
2057 km_uuid: &Uuid,
2058 ) -> Result<Option<i64>> {
2059 let mut stmt = tx.prepare(
2060 "SELECT id
2061 FROM persistent.keyentry
2062 WHERE key_type = ?
2063 AND domain = ?
2064 AND namespace = ?
2065 AND state = ?
2066 AND km_uuid = ?;",
2067 )?;
2068 let rows = stmt
2069 .query_map(
2070 params![
2071 KeyType::Attestation,
2072 domain.0 as u32,
2073 namespace,
2074 KeyLifeCycle::Live,
2075 km_uuid
2076 ],
2077 |row| row.get(0),
2078 )?
2079 .collect::<rusqlite::Result<Vec<i64>>>()
2080 .context("query failed.")?;
2081 if rows.is_empty() {
2082 return Ok(None);
2083 }
2084 Ok(Some(rows[0]))
2085 }
2086
Max Bires2b2e6562020-09-22 11:22:36 -07002087 /// Fetches the private key and corresponding certificate chain assigned to a
2088 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2089 /// not assigned, or one CertificateChain.
2090 pub fn retrieve_attestation_key_and_cert_chain(
2091 &mut self,
2092 domain: Domain,
2093 namespace: i64,
2094 km_uuid: &Uuid,
Max Bires55620ff2022-02-11 13:34:15 -08002095 ) -> Result<Option<(KeyIdGuard, CertificateChain)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002096 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2097
Max Bires2b2e6562020-09-22 11:22:36 -07002098 match domain {
2099 Domain::APP | Domain::SELINUX => {}
2100 _ => {
2101 return Err(KsError::sys())
2102 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2103 }
2104 }
Max Bires55620ff2022-02-11 13:34:15 -08002105
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002106 self.delete_expired_attestation_keys()
2107 .context(ks_err!("Failed to prune expired attestation keys",))?;
2108 let tx = self
2109 .conn
2110 .unchecked_transaction()
2111 .context(ks_err!("Failed to initialize transaction."))?;
Chariseea1e1c482022-02-26 01:26:35 +00002112 let key_id: i64 = match self
2113 .query_kid_for_attestation_key_and_cert_chain(&tx, domain, namespace, km_uuid)?
2114 {
Max Bires55620ff2022-02-11 13:34:15 -08002115 None => return Ok(None),
Chariseea1e1c482022-02-26 01:26:35 +00002116 Some(kid) => kid,
2117 };
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002118 tx.commit().context(ks_err!("Failed to commit keyid query"))?;
Max Bires55620ff2022-02-11 13:34:15 -08002119 let key_id_guard = KEY_ID_LOCK.get(key_id);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002120 let tx = self
2121 .conn
2122 .unchecked_transaction()
2123 .context(ks_err!("Failed to initialize transaction."))?;
Max Bires55620ff2022-02-11 13:34:15 -08002124 let mut stmt = tx.prepare(
2125 "SELECT subcomponent_type, blob
2126 FROM persistent.blobentry
2127 WHERE keyentryid = ?;",
2128 )?;
2129 let rows = stmt
2130 .query_map(params![key_id_guard.id()], |row| Ok((row.get(0)?, row.get(1)?)))?
2131 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
2132 .context("query failed.")?;
2133 if rows.is_empty() {
2134 return Ok(None);
2135 } else if rows.len() != 3 {
2136 return Err(KsError::sys()).context(format!(
2137 concat!(
2138 "Expected to get a single attestation",
2139 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2140 ),
2141 rows.len()
2142 ));
2143 }
2144 let mut km_blob: Vec<u8> = Vec::new();
2145 let mut cert_chain_blob: Vec<u8> = Vec::new();
2146 let mut batch_cert_blob: Vec<u8> = Vec::new();
2147 for row in rows {
2148 let sub_type: SubComponentType = row.0;
2149 match sub_type {
2150 SubComponentType::KEY_BLOB => {
2151 km_blob = row.1;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002152 }
Max Bires55620ff2022-02-11 13:34:15 -08002153 SubComponentType::CERT_CHAIN => {
2154 cert_chain_blob = row.1;
2155 }
2156 SubComponentType::CERT => {
2157 batch_cert_blob = row.1;
2158 }
2159 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002160 }
Max Bires55620ff2022-02-11 13:34:15 -08002161 }
2162 Ok(Some((
2163 key_id_guard,
2164 CertificateChain {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002165 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002166 batch_cert: batch_cert_blob,
2167 cert_chain: cert_chain_blob,
Max Bires55620ff2022-02-11 13:34:15 -08002168 },
2169 )))
Max Bires2b2e6562020-09-22 11:22:36 -07002170 }
2171
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002172 /// Updates the alias column of the given key id `newid` with the given alias,
2173 /// and atomically, removes the alias, domain, and namespace from another row
2174 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002175 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2176 /// collector.
2177 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002178 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002179 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002180 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002181 domain: &Domain,
2182 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002183 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002184 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002185 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002186 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002187 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002188 return Err(KsError::sys())
2189 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002190 }
2191 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002192 let updated = tx
2193 .execute(
2194 "UPDATE persistent.keyentry
2195 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002196 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2197 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002198 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002199 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002200 let result = tx
2201 .execute(
2202 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002203 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002204 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002205 params![
2206 alias,
2207 KeyLifeCycle::Live,
2208 newid.0,
2209 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002210 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002211 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002212 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002213 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002214 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002215 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002216 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002217 return Err(KsError::sys()).context(ks_err!(
2218 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002219 result
2220 ));
2221 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002222 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002223 }
2224
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002225 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2226 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2227 pub fn migrate_key_namespace(
2228 &mut self,
2229 key_id_guard: KeyIdGuard,
2230 destination: &KeyDescriptor,
2231 caller_uid: u32,
2232 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2233 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002234 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2235
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002236 let destination = match destination.domain {
2237 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2238 Domain::SELINUX => (*destination).clone(),
2239 domain => {
2240 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2241 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2242 }
2243 };
2244
2245 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002246 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002247
2248 let alias = destination
2249 .alias
2250 .as_ref()
2251 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002252 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002253
2254 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2255 // Query the destination location. If there is a key, the migration request fails.
2256 if tx
2257 .query_row(
2258 "SELECT id FROM persistent.keyentry
2259 WHERE alias = ? AND domain = ? AND namespace = ?;",
2260 params![alias, destination.domain.0, destination.nspace],
2261 |_| Ok(()),
2262 )
2263 .optional()
2264 .context("Failed to query destination.")?
2265 .is_some()
2266 {
2267 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2268 .context("Target already exists.");
2269 }
2270
2271 let updated = tx
2272 .execute(
2273 "UPDATE persistent.keyentry
2274 SET alias = ?, domain = ?, namespace = ?
2275 WHERE id = ?;",
2276 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2277 )
2278 .context("Failed to update key entry.")?;
2279
2280 if updated != 1 {
2281 return Err(KsError::sys())
2282 .context(format!("Update succeeded, but {} rows were updated.", updated));
2283 }
2284 Ok(()).no_gc()
2285 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002286 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002287 }
2288
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002289 /// Store a new key in a single transaction.
2290 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2291 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002292 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2293 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07002294 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002295 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002296 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002297 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002298 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002299 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002300 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08002301 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002302 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002303 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002304 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002305 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2306
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002307 let (alias, domain, namespace) = match key {
2308 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2309 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2310 (alias, key.domain, nspace)
2311 }
2312 _ => {
2313 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002314 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002315 }
2316 };
2317 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002318 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002319 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002320 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
2321
2322 // In some occasions the key blob is already upgraded during the import.
2323 // In order to make sure it gets properly deleted it is inserted into the
2324 // database here and then immediately replaced by the superseding blob.
2325 // The garbage collector will then subject the blob to deleteKey of the
2326 // KM back end to permanently invalidate the key.
2327 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
2328 Self::set_blob_internal(
2329 tx,
2330 key_id.id(),
2331 SubComponentType::KEY_BLOB,
2332 Some(blob),
2333 Some(blob_metadata),
2334 )
2335 .context("Trying to insert superseded key blob.")?;
2336 true
2337 } else {
2338 false
2339 };
2340
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002341 Self::set_blob_internal(
2342 tx,
2343 key_id.id(),
2344 SubComponentType::KEY_BLOB,
2345 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002346 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002347 )
2348 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002349 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002350 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002351 .context("Trying to insert the certificate.")?;
2352 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002353 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002354 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002355 tx,
2356 key_id.id(),
2357 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002358 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002359 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002360 )
2361 .context("Trying to insert the certificate chain.")?;
2362 }
2363 Self::insert_keyparameter_internal(tx, &key_id, params)
2364 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002365 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002366 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002367 .context("Trying to rebind alias.")?
2368 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002369 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002370 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002371 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002372 }
2373
Janis Danisevskis377d1002021-01-27 19:07:48 -08002374 /// Store a new certificate
2375 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2376 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002377 pub fn store_new_certificate(
2378 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002379 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002380 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002381 cert: &[u8],
2382 km_uuid: &Uuid,
2383 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002384 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2385
Janis Danisevskis377d1002021-01-27 19:07:48 -08002386 let (alias, domain, namespace) = match key {
2387 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2388 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2389 (alias, key.domain, nspace)
2390 }
2391 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002392 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2393 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08002394 }
2395 };
2396 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002397 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002398 .context("Trying to create new key entry.")?;
2399
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002400 Self::set_blob_internal(
2401 tx,
2402 key_id.id(),
2403 SubComponentType::CERT_CHAIN,
2404 Some(cert),
2405 None,
2406 )
2407 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002408
2409 let mut metadata = KeyMetaData::new();
2410 metadata.add(KeyMetaEntry::CreationDate(
2411 DateTime::now().context("Trying to make creation time.")?,
2412 ));
2413
2414 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2415
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002416 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002417 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002418 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002419 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002420 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08002421 }
2422
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002423 // Helper function loading the key_id given the key descriptor
2424 // tuple comprising domain, namespace, and alias.
2425 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002426 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002427 let alias = key
2428 .alias
2429 .as_ref()
2430 .map_or_else(|| Err(KsError::sys()), Ok)
2431 .context("In load_key_entry_id: Alias must be specified.")?;
2432 let mut stmt = tx
2433 .prepare(
2434 "SELECT id FROM persistent.keyentry
2435 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002436 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002437 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002439 AND alias = ?
2440 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002441 )
2442 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2443 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002444 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002445 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002446 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002447 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002448 .get(0)
2449 .context("Failed to unpack id.")
2450 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002451 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002452 }
2453
2454 /// This helper function completes the access tuple of a key, which is required
2455 /// to perform access control. The strategy depends on the `domain` field in the
2456 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002457 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002458 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002459 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002460 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002461 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002462 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002463 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002464 /// `namespace`.
2465 /// In each case the information returned is sufficient to perform the access
2466 /// check and the key id can be used to load further key artifacts.
2467 fn load_access_tuple(
2468 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002469 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002470 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002471 caller_uid: u32,
2472 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2473 match key.domain {
2474 // Domain App or SELinux. In this case we load the key_id from
2475 // the keyentry database for further loading of key components.
2476 // We already have the full access tuple to perform access control.
2477 // The only distinction is that we use the caller_uid instead
2478 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002479 // Domain::APP.
2480 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002481 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002482 if access_key.domain == Domain::APP {
2483 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002484 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002485 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002486 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002487
2488 Ok((key_id, access_key, None))
2489 }
2490
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002491 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002492 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002493 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002494 let mut stmt = tx
2495 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002496 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002497 WHERE grantee = ? AND id = ? AND
2498 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002499 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002500 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002501 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002502 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002503 .context("Domain:Grant: query failed.")?;
2504 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002505 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002506 let r =
2507 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002508 Ok((
2509 r.get(0).context("Failed to unpack key_id.")?,
2510 r.get(1).context("Failed to unpack access_vector.")?,
2511 ))
2512 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002513 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002514 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002515 }
2516
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002517 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002518 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002519 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002520 let (domain, namespace): (Domain, i64) = {
2521 let mut stmt = tx
2522 .prepare(
2523 "SELECT domain, namespace FROM persistent.keyentry
2524 WHERE
2525 id = ?
2526 AND state = ?;",
2527 )
2528 .context("Domain::KEY_ID: prepare statement failed")?;
2529 let mut rows = stmt
2530 .query(params![key.nspace, KeyLifeCycle::Live])
2531 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002532 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002533 let r =
2534 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002535 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002536 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002537 r.get(1).context("Failed to unpack namespace.")?,
2538 ))
2539 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002540 .context("Domain::KEY_ID.")?
2541 };
2542
2543 // We may use a key by id after loading it by grant.
2544 // In this case we have to check if the caller has a grant for this particular
2545 // key. We can skip this if we already know that the caller is the owner.
2546 // But we cannot know this if domain is anything but App. E.g. in the case
2547 // of Domain::SELINUX we have to speculatively check for grants because we have to
2548 // consult the SEPolicy before we know if the caller is the owner.
2549 let access_vector: Option<KeyPermSet> =
2550 if domain != Domain::APP || namespace != caller_uid as i64 {
2551 let access_vector: Option<i32> = tx
2552 .query_row(
2553 "SELECT access_vector FROM persistent.grant
2554 WHERE grantee = ? AND keyentryid = ?;",
2555 params![caller_uid as i64, key.nspace],
2556 |row| row.get(0),
2557 )
2558 .optional()
2559 .context("Domain::KEY_ID: query grant failed.")?;
2560 access_vector.map(|p| p.into())
2561 } else {
2562 None
2563 };
2564
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002565 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002566 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002567 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002568 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002569
Janis Danisevskis45760022021-01-19 16:34:10 -08002570 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002571 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002572 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002573 }
2574 }
2575
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002576 fn load_blob_components(
2577 key_id: i64,
2578 load_bits: KeyEntryLoadBits,
2579 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002580 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002581 let mut stmt = tx
2582 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002583 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002584 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2585 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002586 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002587
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002588 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002589
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002590 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002591 let mut cert_blob: Option<Vec<u8>> = None;
2592 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002593 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002594 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002595 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002596 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002597 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002598 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2599 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002600 key_blob = Some((
2601 row.get(0).context("Failed to extract key blob id.")?,
2602 row.get(2).context("Failed to extract key blob.")?,
2603 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002604 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002605 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002606 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002607 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002608 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002609 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002610 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002611 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002612 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002613 (SubComponentType::CERT, _, _)
2614 | (SubComponentType::CERT_CHAIN, _, _)
2615 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002616 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2617 }
2618 Ok(())
2619 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002620 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002621
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002622 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2623 Ok(Some((
2624 blob,
2625 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002626 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002627 )))
2628 })?;
2629
2630 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002631 }
2632
2633 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2634 let mut stmt = tx
2635 .prepare(
2636 "SELECT tag, data, security_level from persistent.keyparameter
2637 WHERE keyentryid = ?;",
2638 )
2639 .context("In load_key_parameters: prepare statement failed.")?;
2640
2641 let mut parameters: Vec<KeyParameter> = Vec::new();
2642
2643 let mut rows =
2644 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002645 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002646 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2647 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002648 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002649 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002650 .context("Failed to read KeyParameter.")?,
2651 );
2652 Ok(())
2653 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002654 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002655
2656 Ok(parameters)
2657 }
2658
Qi Wub9433b52020-12-01 14:52:46 +08002659 /// Decrements the usage count of a limited use key. This function first checks whether the
2660 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2661 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2662 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002663 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002664 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2665
Qi Wub9433b52020-12-01 14:52:46 +08002666 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2667 let limit: Option<i32> = tx
2668 .query_row(
2669 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2670 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2671 |row| row.get(0),
2672 )
2673 .optional()
2674 .context("Trying to load usage count")?;
2675
2676 let limit = limit
2677 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2678 .context("The Key no longer exists. Key is exhausted.")?;
2679
2680 tx.execute(
2681 "UPDATE persistent.keyparameter
2682 SET data = data - 1
2683 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2684 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2685 )
2686 .context("Failed to update key usage count.")?;
2687
2688 match limit {
2689 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002690 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002691 .context("Trying to mark limited use key for deletion."),
2692 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002693 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002694 }
2695 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002696 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002697 }
2698
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002699 /// Load a key entry by the given key descriptor.
2700 /// It uses the `check_permission` callback to verify if the access is allowed
2701 /// given the key access tuple read from the database using `load_access_tuple`.
2702 /// With `load_bits` the caller may specify which blobs shall be loaded from
2703 /// the blob database.
2704 pub fn load_key_entry(
2705 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002706 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002707 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002708 load_bits: KeyEntryLoadBits,
2709 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002710 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2711 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002712 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2713
Janis Danisevskis66784c42021-01-27 08:40:25 -08002714 loop {
2715 match self.load_key_entry_internal(
2716 key,
2717 key_type,
2718 load_bits,
2719 caller_uid,
2720 &check_permission,
2721 ) {
2722 Ok(result) => break Ok(result),
2723 Err(e) => {
2724 if Self::is_locked_error(&e) {
2725 std::thread::sleep(std::time::Duration::from_micros(500));
2726 continue;
2727 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002728 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002729 }
2730 }
2731 }
2732 }
2733 }
2734
2735 fn load_key_entry_internal(
2736 &mut self,
2737 key: &KeyDescriptor,
2738 key_type: KeyType,
2739 load_bits: KeyEntryLoadBits,
2740 caller_uid: u32,
2741 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002742 ) -> Result<(KeyIdGuard, KeyEntry)> {
2743 // KEY ID LOCK 1/2
2744 // If we got a key descriptor with a key id we can get the lock right away.
2745 // Otherwise we have to defer it until we know the key id.
2746 let key_id_guard = match key.domain {
2747 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2748 _ => None,
2749 };
2750
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002751 let tx = self
2752 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002753 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002754 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002755
2756 // Load the key_id and complete the access control tuple.
2757 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002758 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002759
2760 // Perform access control. It is vital that we return here if the permission is denied.
2761 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002762 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002763
Janis Danisevskisaec14592020-11-12 09:41:49 -08002764 // KEY ID LOCK 2/2
2765 // If we did not get a key id lock by now, it was because we got a key descriptor
2766 // without a key id. At this point we got the key id, so we can try and get a lock.
2767 // However, we cannot block here, because we are in the middle of the transaction.
2768 // So first we try to get the lock non blocking. If that fails, we roll back the
2769 // transaction and block until we get the lock. After we successfully got the lock,
2770 // we start a new transaction and load the access tuple again.
2771 //
2772 // We don't need to perform access control again, because we already established
2773 // that the caller had access to the given key. But we need to make sure that the
2774 // key id still exists. So we have to load the key entry by key id this time.
2775 let (key_id_guard, tx) = match key_id_guard {
2776 None => match KEY_ID_LOCK.try_get(key_id) {
2777 None => {
2778 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002779 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002780
Janis Danisevskisaec14592020-11-12 09:41:49 -08002781 // Block until we have a key id lock.
2782 let key_id_guard = KEY_ID_LOCK.get(key_id);
2783
2784 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002785 let tx = self
2786 .conn
2787 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002788 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002789
2790 Self::load_access_tuple(
2791 &tx,
2792 // This time we have to load the key by the retrieved key id, because the
2793 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002794 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002795 domain: Domain::KEY_ID,
2796 nspace: key_id,
2797 ..Default::default()
2798 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002799 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002800 caller_uid,
2801 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002802 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002803 (key_id_guard, tx)
2804 }
2805 Some(l) => (l, tx),
2806 },
2807 Some(key_id_guard) => (key_id_guard, tx),
2808 };
2809
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002810 let key_entry =
2811 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002812
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002813 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002814
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002815 Ok((key_id_guard, key_entry))
2816 }
2817
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002818 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002819 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002820 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2821 .context("Trying to delete keyentry.")?;
2822 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2823 .context("Trying to delete keymetadata.")?;
2824 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2825 .context("Trying to delete keyparameters.")?;
2826 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2827 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002828 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002829 }
2830
2831 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002832 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002833 pub fn unbind_key(
2834 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002835 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002836 key_type: KeyType,
2837 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002838 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002839 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002840 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2841
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002842 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2843 let (key_id, access_key_descriptor, access_vector) =
2844 Self::load_access_tuple(tx, key, key_type, caller_uid)
2845 .context("Trying to get access tuple.")?;
2846
2847 // Perform access control. It is vital that we return here if the permission is denied.
2848 // So do not touch that '?' at the end.
2849 check_permission(&access_key_descriptor, access_vector)
2850 .context("While checking permission.")?;
2851
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002852 Self::mark_unreferenced(tx, key_id)
2853 .map(|need_gc| (need_gc, ()))
2854 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002855 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002856 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002857 }
2858
Max Bires8e93d2b2021-01-14 13:17:59 -08002859 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2860 tx.query_row(
2861 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2862 params![key_id],
2863 |row| row.get(0),
2864 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002865 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002866 }
2867
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002868 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2869 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2870 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002871 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2872
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002873 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002874 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002875 }
2876 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2877 tx.execute(
2878 "DELETE FROM persistent.keymetadata
2879 WHERE keyentryid IN (
2880 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002881 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002882 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002883 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002884 )
2885 .context("Trying to delete keymetadata.")?;
2886 tx.execute(
2887 "DELETE FROM persistent.keyparameter
2888 WHERE keyentryid IN (
2889 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002890 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002891 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002892 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002893 )
2894 .context("Trying to delete keyparameters.")?;
2895 tx.execute(
2896 "DELETE FROM persistent.grant
2897 WHERE keyentryid IN (
2898 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002899 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002900 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002901 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002902 )
2903 .context("Trying to delete grants.")?;
2904 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002905 "DELETE FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002906 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?);",
2907 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002908 )
2909 .context("Trying to delete keyentry.")?;
2910 Ok(()).need_gc()
2911 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002912 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002913 }
2914
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002915 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2916 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2917 {
2918 tx.execute(
2919 "DELETE FROM persistent.keymetadata
2920 WHERE keyentryid IN (
2921 SELECT id FROM persistent.keyentry
2922 WHERE state = ?
2923 );",
2924 params![KeyLifeCycle::Unreferenced],
2925 )
2926 .context("Trying to delete keymetadata.")?;
2927 tx.execute(
2928 "DELETE FROM persistent.keyparameter
2929 WHERE keyentryid IN (
2930 SELECT id FROM persistent.keyentry
2931 WHERE state = ?
2932 );",
2933 params![KeyLifeCycle::Unreferenced],
2934 )
2935 .context("Trying to delete keyparameters.")?;
2936 tx.execute(
2937 "DELETE FROM persistent.grant
2938 WHERE keyentryid IN (
2939 SELECT id FROM persistent.keyentry
2940 WHERE state = ?
2941 );",
2942 params![KeyLifeCycle::Unreferenced],
2943 )
2944 .context("Trying to delete grants.")?;
2945 tx.execute(
2946 "DELETE FROM persistent.keyentry
2947 WHERE state = ?;",
2948 params![KeyLifeCycle::Unreferenced],
2949 )
2950 .context("Trying to delete keyentry.")?;
2951 Result::<()>::Ok(())
2952 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002953 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002954 }
2955
Hasini Gunasingheda895552021-01-27 19:34:37 +00002956 /// Delete the keys created on behalf of the user, denoted by the user id.
2957 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2958 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2959 /// The caller of this function should notify the gc if the returned value is true.
2960 pub fn unbind_keys_for_user(
2961 &mut self,
2962 user_id: u32,
2963 keep_non_super_encrypted_keys: bool,
2964 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002965 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2966
Hasini Gunasingheda895552021-01-27 19:34:37 +00002967 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2968 let mut stmt = tx
2969 .prepare(&format!(
2970 "SELECT id from persistent.keyentry
2971 WHERE (
2972 key_type = ?
2973 AND domain = ?
2974 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2975 AND state = ?
2976 ) OR (
2977 key_type = ?
2978 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002979 AND state = ?
2980 );",
2981 aid_user_offset = AID_USER_OFFSET
2982 ))
2983 .context(concat!(
2984 "In unbind_keys_for_user. ",
2985 "Failed to prepare the query to find the keys created by apps."
2986 ))?;
2987
2988 let mut rows = stmt
2989 .query(params![
2990 // WHERE client key:
2991 KeyType::Client,
2992 Domain::APP.0 as u32,
2993 user_id,
2994 KeyLifeCycle::Live,
2995 // OR super key:
2996 KeyType::Super,
2997 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002998 KeyLifeCycle::Live
2999 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003000 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00003001
3002 let mut key_ids: Vec<i64> = Vec::new();
3003 db_utils::with_rows_extract_all(&mut rows, |row| {
3004 key_ids
3005 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
3006 Ok(())
3007 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003008 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00003009
3010 let mut notify_gc = false;
3011 for key_id in key_ids {
3012 if keep_non_super_encrypted_keys {
3013 // Load metadata and filter out non-super-encrypted keys.
3014 if let (_, Some((_, blob_metadata)), _, _) =
3015 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003016 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00003017 {
3018 if blob_metadata.encrypted_by().is_none() {
3019 continue;
3020 }
3021 }
3022 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003023 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00003024 .context("In unbind_keys_for_user.")?
3025 || notify_gc;
3026 }
3027 Ok(()).do_gc(notify_gc)
3028 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003029 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00003030 }
3031
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003032 fn load_key_components(
3033 tx: &Transaction,
3034 load_bits: KeyEntryLoadBits,
3035 key_id: i64,
3036 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003037 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003038
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003039 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003040 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003041
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003042 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08003043 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003044
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003045 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08003046 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003047
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003048 Ok(KeyEntry {
3049 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003050 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003051 cert: cert_blob,
3052 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003053 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003054 parameters,
3055 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003056 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003057 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003058 }
3059
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003060 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3061 /// The key descriptors will have the domain, nspace, and alias field set.
3062 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07003063 pub fn list(
3064 &mut self,
3065 domain: Domain,
3066 namespace: i64,
3067 key_type: KeyType,
3068 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003069 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3070
Janis Danisevskis66784c42021-01-27 08:40:25 -08003071 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3072 let mut stmt = tx
3073 .prepare(
3074 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07003075 WHERE domain = ?
3076 AND namespace = ?
3077 AND alias IS NOT NULL
3078 AND state = ?
3079 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003080 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003081 .context(ks_err!("Failed to prepare."))?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003082
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003084 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003085 .context(ks_err!("Failed to query."))?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003086
Janis Danisevskis66784c42021-01-27 08:40:25 -08003087 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3088 db_utils::with_rows_extract_all(&mut rows, |row| {
3089 descriptors.push(KeyDescriptor {
3090 domain,
3091 nspace: namespace,
3092 alias: Some(row.get(0).context("Trying to extract alias.")?),
3093 blob: None,
3094 });
3095 Ok(())
3096 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003097 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003098 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003099 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003100 }
3101
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003102 /// Adds a grant to the grant table.
3103 /// Like `load_key_entry` this function loads the access tuple before
3104 /// it uses the callback for a permission check. Upon success,
3105 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3106 /// grant table. The new row will have a randomized id, which is used as
3107 /// grant id in the namespace field of the resulting KeyDescriptor.
3108 pub fn grant(
3109 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003110 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003111 caller_uid: u32,
3112 grantee_uid: u32,
3113 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003114 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003115 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003116 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3117
Janis Danisevskis66784c42021-01-27 08:40:25 -08003118 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3119 // Load the key_id and complete the access control tuple.
3120 // We ignore the access vector here because grants cannot be granted.
3121 // The access vector returned here expresses the permissions the
3122 // grantee has if key.domain == Domain::GRANT. But this vector
3123 // cannot include the grant permission by design, so there is no way the
3124 // subsequent permission check can pass.
3125 // We could check key.domain == Domain::GRANT and fail early.
3126 // But even if we load the access tuple by grant here, the permission
3127 // check denies the attempt to create a grant by grant descriptor.
3128 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003129 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003130
Janis Danisevskis66784c42021-01-27 08:40:25 -08003131 // Perform access control. It is vital that we return here if the permission
3132 // was denied. So do not touch that '?' at the end of the line.
3133 // This permission check checks if the caller has the grant permission
3134 // for the given key and in addition to all of the permissions
3135 // expressed in `access_vector`.
3136 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003137 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003138
Janis Danisevskis66784c42021-01-27 08:40:25 -08003139 let grant_id = if let Some(grant_id) = tx
3140 .query_row(
3141 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003142 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003143 params![key_id, grantee_uid],
3144 |row| row.get(0),
3145 )
3146 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003147 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08003148 {
3149 tx.execute(
3150 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003151 SET access_vector = ?
3152 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003153 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003154 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003155 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003156 grant_id
3157 } else {
3158 Self::insert_with_retry(|id| {
3159 tx.execute(
3160 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3161 VALUES (?, ?, ?, ?);",
3162 params![id, grantee_uid, key_id, i32::from(access_vector)],
3163 )
3164 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003165 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08003166 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003167
Janis Danisevskis66784c42021-01-27 08:40:25 -08003168 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003169 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003170 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003171 }
3172
3173 /// This function checks permissions like `grant` and `load_key_entry`
3174 /// before removing a grant from the grant table.
3175 pub fn ungrant(
3176 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003177 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003178 caller_uid: u32,
3179 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003180 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003181 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003182 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3183
Janis Danisevskis66784c42021-01-27 08:40:25 -08003184 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3185 // Load the key_id and complete the access control tuple.
3186 // We ignore the access vector here because grants cannot be granted.
3187 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003188 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003189
Janis Danisevskis66784c42021-01-27 08:40:25 -08003190 // Perform access control. We must return here if the permission
3191 // was denied. So do not touch the '?' at the end of this line.
3192 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003193 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003194
Janis Danisevskis66784c42021-01-27 08:40:25 -08003195 tx.execute(
3196 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003197 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003198 params![key_id, grantee_uid],
3199 )
3200 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003201
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003202 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003203 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003204 }
3205
Joel Galenson845f74b2020-09-09 14:11:55 -07003206 // Generates a random id and passes it to the given function, which will
3207 // try to insert it into a database. If that insertion fails, retry;
3208 // otherwise return the id.
3209 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3210 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003211 let newid: i64 = match random() {
3212 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3213 i => i,
3214 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003215 match inserter(newid) {
3216 // If the id already existed, try again.
3217 Err(rusqlite::Error::SqliteFailure(
3218 libsqlite3_sys::Error {
3219 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3220 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3221 },
3222 _,
3223 )) => (),
3224 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003225 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07003226 }
3227 _ => return Ok(newid),
3228 }
3229 }
3230 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003231
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003232 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3233 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3234 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3235 auth_token.clone(),
3236 MonotonicRawTime::now(),
3237 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003238 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003239
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003240 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003241 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003242 where
3243 F: Fn(&AuthTokenEntry) -> bool,
3244 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003245 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003246 }
3247
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003248 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003249 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3250 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003251 }
3252
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003253 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003254 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3255 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003256 }
3257
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003258 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003259 fn get_last_off_body(&self) -> MonotonicRawTime {
3260 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003261 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003262
3263 /// Load descriptor of a key by key id
3264 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3265 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3266
3267 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3268 tx.query_row(
3269 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3270 params![key_id],
3271 |row| {
3272 Ok(KeyDescriptor {
3273 domain: Domain(row.get(0)?),
3274 nspace: row.get(1)?,
3275 alias: row.get(2)?,
3276 blob: None,
3277 })
3278 },
3279 )
3280 .optional()
3281 .context("Trying to load key descriptor")
3282 .no_gc()
3283 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003284 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01003285 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003286}
3287
3288#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08003289pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07003290
3291 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003292 use crate::key_parameter::{
3293 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3294 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3295 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003296 use crate::key_perm_set;
3297 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08003298 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003299 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003300 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3301 HardwareAuthToken::HardwareAuthToken,
3302 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003303 };
3304 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003305 Timestamp::Timestamp,
3306 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003307 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003308 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003309 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003310 use std::collections::BTreeMap;
3311 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003312 use std::sync::atomic::{AtomicU8, Ordering};
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003313 use std::sync::{Arc, RwLock};
Janis Danisevskisaec14592020-11-12 09:41:49 -08003314 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003315 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003316 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003317 #[cfg(disabled)]
3318 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003319
Seth Moore7ee79f92021-12-07 11:42:49 -08003320 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003321 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003322
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003323 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003324 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003325 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003326 })?;
3327 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003328 }
3329
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003330 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3331 where
3332 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3333 {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003334 let super_key: Arc<RwLock<SuperKeyManager>> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003335
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003336 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003337 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003338
Janis Danisevskis3395f862021-05-06 10:54:17 -07003339 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003340 }
3341
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003342 fn rebind_alias(
3343 db: &mut KeystoreDB,
3344 newid: &KeyIdGuard,
3345 alias: &str,
3346 domain: Domain,
3347 namespace: i64,
3348 ) -> Result<bool> {
3349 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003350 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003351 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003352 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003353 }
3354
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003355 #[test]
3356 fn datetime() -> Result<()> {
3357 let conn = Connection::open_in_memory()?;
3358 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3359 let now = SystemTime::now();
3360 let duration = Duration::from_secs(1000);
3361 let then = now.checked_sub(duration).unwrap();
3362 let soon = now.checked_add(duration).unwrap();
3363 conn.execute(
3364 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3365 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3366 )?;
3367 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3368 let mut rows = stmt.query(NO_PARAMS)?;
3369 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3370 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3371 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3372 assert!(rows.next()?.is_none());
3373 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3374 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3375 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3376 Ok(())
3377 }
3378
Joel Galenson0891bc12020-07-20 10:37:03 -07003379 // Ensure that we're using the "injected" random function, not the real one.
3380 #[test]
3381 fn test_mocked_random() {
3382 let rand1 = random();
3383 let rand2 = random();
3384 let rand3 = random();
3385 if rand1 == rand2 {
3386 assert_eq!(rand2 + 1, rand3);
3387 } else {
3388 assert_eq!(rand1 + 1, rand2);
3389 assert_eq!(rand2, rand3);
3390 }
3391 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003392
Joel Galenson26f4d012020-07-17 14:57:21 -07003393 // Test that we have the correct tables.
3394 #[test]
3395 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003396 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003397 let tables = db
3398 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003399 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003400 .query_map(params![], |row| row.get(0))?
3401 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003402 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003403 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003404 assert_eq!(tables[1], "blobmetadata");
3405 assert_eq!(tables[2], "grant");
3406 assert_eq!(tables[3], "keyentry");
3407 assert_eq!(tables[4], "keymetadata");
3408 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003409 Ok(())
3410 }
3411
3412 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003413 fn test_auth_token_table_invariant() -> Result<()> {
3414 let mut db = new_test_db()?;
3415 let auth_token1 = HardwareAuthToken {
3416 challenge: i64::MAX,
3417 userId: 200,
3418 authenticatorId: 200,
3419 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3420 timestamp: Timestamp { milliSeconds: 500 },
3421 mac: String::from("mac").into_bytes(),
3422 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003423 db.insert_auth_token(&auth_token1);
3424 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003425 assert_eq!(auth_tokens_returned.len(), 1);
3426
3427 // insert another auth token with the same values for the columns in the UNIQUE constraint
3428 // of the auth token table and different value for timestamp
3429 let auth_token2 = HardwareAuthToken {
3430 challenge: i64::MAX,
3431 userId: 200,
3432 authenticatorId: 200,
3433 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3434 timestamp: Timestamp { milliSeconds: 600 },
3435 mac: String::from("mac").into_bytes(),
3436 };
3437
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003438 db.insert_auth_token(&auth_token2);
3439 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003440 assert_eq!(auth_tokens_returned.len(), 1);
3441
3442 if let Some(auth_token) = auth_tokens_returned.pop() {
3443 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3444 }
3445
3446 // insert another auth token with the different values for the columns in the UNIQUE
3447 // constraint of the auth token table
3448 let auth_token3 = HardwareAuthToken {
3449 challenge: i64::MAX,
3450 userId: 201,
3451 authenticatorId: 200,
3452 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3453 timestamp: Timestamp { milliSeconds: 600 },
3454 mac: String::from("mac").into_bytes(),
3455 };
3456
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003457 db.insert_auth_token(&auth_token3);
3458 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003459 assert_eq!(auth_tokens_returned.len(), 2);
3460
3461 Ok(())
3462 }
3463
3464 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003465 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3466 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003467 }
3468
3469 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003470 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003471 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003472 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003473
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003474 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003475 let entries = get_keyentry(&db)?;
3476 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003477
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003478 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003479
3480 let entries_new = get_keyentry(&db)?;
3481 assert_eq!(entries, entries_new);
3482 Ok(())
3483 }
3484
3485 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003486 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003487 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3488 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003489 }
3490
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003491 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003492
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003493 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3494 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003495
3496 let entries = get_keyentry(&db)?;
3497 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003498 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3499 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003500
3501 // Test that we must pass in a valid Domain.
3502 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003503 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003504 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003505 );
3506 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003507 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003508 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003509 );
3510 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003511 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003512 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003513 );
3514
3515 Ok(())
3516 }
3517
Joel Galenson33c04ad2020-08-03 11:04:38 -07003518 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003519 fn test_add_unsigned_key() -> Result<()> {
3520 let mut db = new_test_db()?;
3521 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3522 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3523 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3524 db.create_attestation_key_entry(
3525 &public_key,
3526 &raw_public_key,
3527 &private_key,
3528 &KEYSTORE_UUID,
3529 )?;
3530 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3531 assert_eq!(keys.len(), 1);
3532 assert_eq!(keys[0], public_key);
3533 Ok(())
3534 }
3535
3536 #[test]
3537 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3538 let mut db = new_test_db()?;
Max Birescd7f7412022-02-11 13:47:36 -08003539 let expiration_date: i64 =
3540 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3541 + EXPIRATION_BUFFER_MS
3542 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003543 let namespace: i64 = 30;
3544 let base_byte: u8 = 1;
3545 let loaded_values =
3546 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3547 let chain =
3548 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Chris Wailes3877f292021-07-26 19:24:18 -07003549 assert!(chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003550 let (_, cert_chain) = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003551 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003552 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3553 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003554 Ok(())
3555 }
3556
3557 #[test]
3558 fn test_get_attestation_pool_status() -> Result<()> {
3559 let mut db = new_test_db()?;
3560 let namespace: i64 = 30;
3561 load_attestation_key_pool(
3562 &mut db, 10, /* expiration */
3563 namespace, 0x01, /* base_byte */
3564 )?;
3565 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3566 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3567 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3568 assert_eq!(status.expiring, 0);
3569 assert_eq!(status.attested, 3);
3570 assert_eq!(status.unassigned, 0);
3571 assert_eq!(status.total, 3);
3572 assert_eq!(
3573 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3574 1
3575 );
3576 assert_eq!(
3577 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3578 2
3579 );
3580 assert_eq!(
3581 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3582 3
3583 );
3584 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3585 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3586 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3587 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003588 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003589 db.create_attestation_key_entry(
3590 &public_key,
3591 &raw_public_key,
3592 &private_key,
3593 &KEYSTORE_UUID,
3594 )?;
3595 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3596 assert_eq!(status.attested, 3);
3597 assert_eq!(status.unassigned, 0);
3598 assert_eq!(status.total, 4);
3599 db.store_signed_attestation_certificate_chain(
3600 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003601 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003602 &cert_chain,
3603 20,
3604 &KEYSTORE_UUID,
3605 )?;
3606 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3607 assert_eq!(status.attested, 4);
3608 assert_eq!(status.unassigned, 1);
3609 assert_eq!(status.total, 4);
3610 Ok(())
3611 }
3612
3613 #[test]
3614 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003615 let temp_dir =
3616 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3617 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003618 let expiration_date: i64 =
Max Birescd7f7412022-02-11 13:47:36 -08003619 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3620 + EXPIRATION_BUFFER_MS
3621 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003622 let namespace: i64 = 30;
3623 let namespace_del1: i64 = 45;
3624 let namespace_del2: i64 = 60;
3625 let entry_values = load_attestation_key_pool(
3626 &mut db,
3627 expiration_date,
3628 namespace,
3629 0x01, /* base_byte */
3630 )?;
3631 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
Max Birescd7f7412022-02-11 13:47:36 -08003632 load_attestation_key_pool(&mut db, expiration_date - 10001, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003633
3634 let blob_entry_row_count: u32 = db
3635 .conn
3636 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3637 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003638 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3639 // one key, one certificate chain, and one certificate.
3640 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003641
Max Bires2b2e6562020-09-22 11:22:36 -07003642 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3643
3644 let mut cert_chain =
3645 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003646 assert!(cert_chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003647 let (_, value) = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003648 assert_eq!(entry_values.batch_cert, value.batch_cert);
3649 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003650 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003651
3652 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3653 Domain::APP,
3654 namespace_del1,
3655 &KEYSTORE_UUID,
3656 )?;
Chariseea1e1c482022-02-26 01:26:35 +00003657 assert!(cert_chain.is_none());
Max Bires2b2e6562020-09-22 11:22:36 -07003658 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3659 Domain::APP,
3660 namespace_del2,
3661 &KEYSTORE_UUID,
3662 )?;
Chariseea1e1c482022-02-26 01:26:35 +00003663 assert!(cert_chain.is_none());
Max Bires2b2e6562020-09-22 11:22:36 -07003664
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003665 // Give the garbage collector half a second to catch up.
3666 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003667
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003668 let blob_entry_row_count: u32 = db
3669 .conn
3670 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3671 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003672 // There shound be 3 blob entries left, because we deleted two of the attestation
3673 // key entries with three blobs each.
3674 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003675
Max Bires2b2e6562020-09-22 11:22:36 -07003676 Ok(())
3677 }
3678
Max Birescd7f7412022-02-11 13:47:36 -08003679 fn compare_rem_prov_values(
3680 expected: &RemoteProvValues,
3681 actual: Option<(KeyIdGuard, CertificateChain)>,
3682 ) {
3683 assert!(actual.is_some());
3684 let (_, value) = actual.unwrap();
3685 assert_eq!(expected.batch_cert, value.batch_cert);
3686 assert_eq!(expected.cert_chain, value.cert_chain);
3687 assert_eq!(expected.priv_key, value.private_key.to_vec());
3688 }
3689
3690 #[test]
3691 fn test_dont_remove_valid_certs() -> Result<()> {
3692 let temp_dir =
3693 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3694 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
3695 let expiration_date: i64 =
3696 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3697 + EXPIRATION_BUFFER_MS
3698 + 10000;
3699 let namespace1: i64 = 30;
3700 let namespace2: i64 = 45;
3701 let namespace3: i64 = 60;
3702 let entry_values1 = load_attestation_key_pool(
3703 &mut db,
3704 expiration_date,
3705 namespace1,
3706 0x01, /* base_byte */
3707 )?;
3708 let entry_values2 =
3709 load_attestation_key_pool(&mut db, expiration_date + 40000, namespace2, 0x02)?;
3710 let entry_values3 =
3711 load_attestation_key_pool(&mut db, expiration_date - 9000, namespace3, 0x03)?;
3712
3713 let blob_entry_row_count: u32 = db
3714 .conn
3715 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3716 .expect("Failed to get blob entry row count.");
3717 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3718 // one key, one certificate chain, and one certificate.
3719 assert_eq!(blob_entry_row_count, 9);
3720
3721 let mut cert_chain =
3722 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace1, &KEYSTORE_UUID)?;
3723 compare_rem_prov_values(&entry_values1, cert_chain);
3724
3725 cert_chain =
3726 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace2, &KEYSTORE_UUID)?;
3727 compare_rem_prov_values(&entry_values2, cert_chain);
3728
3729 cert_chain =
3730 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace3, &KEYSTORE_UUID)?;
3731 compare_rem_prov_values(&entry_values3, cert_chain);
3732
3733 // Give the garbage collector half a second to catch up.
3734 std::thread::sleep(Duration::from_millis(500));
3735
3736 let blob_entry_row_count: u32 = db
3737 .conn
3738 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3739 .expect("Failed to get blob entry row count.");
3740 // There shound be 9 blob entries left, because all three keys are valid with
3741 // three blobs each.
3742 assert_eq!(blob_entry_row_count, 9);
3743
3744 Ok(())
3745 }
Max Bires2b2e6562020-09-22 11:22:36 -07003746 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003747 fn test_delete_all_attestation_keys() -> Result<()> {
3748 let mut db = new_test_db()?;
3749 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3750 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003751 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003752 let result = db.delete_all_attestation_keys()?;
3753
3754 // Give the garbage collector half a second to catch up.
3755 std::thread::sleep(Duration::from_millis(500));
3756
3757 // Attestation keys should be deleted, and the regular key should remain.
3758 assert_eq!(result, 2);
3759
3760 Ok(())
3761 }
3762
3763 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003764 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003765 fn extractor(
3766 ke: &KeyEntryRow,
3767 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3768 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003769 }
3770
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003771 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003772 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3773 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003774 let entries = get_keyentry(&db)?;
3775 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003776 assert_eq!(
3777 extractor(&entries[0]),
3778 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3779 );
3780 assert_eq!(
3781 extractor(&entries[1]),
3782 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3783 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003784
3785 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003786 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003787 let entries = get_keyentry(&db)?;
3788 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003789 assert_eq!(
3790 extractor(&entries[0]),
3791 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3792 );
3793 assert_eq!(
3794 extractor(&entries[1]),
3795 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3796 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003797
3798 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003799 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003800 let entries = get_keyentry(&db)?;
3801 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003802 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3803 assert_eq!(
3804 extractor(&entries[1]),
3805 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3806 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003807
3808 // Test that we must pass in a valid Domain.
3809 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003810 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003811 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003812 );
3813 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003814 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003815 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003816 );
3817 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003818 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003819 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003820 );
3821
3822 // Test that we correctly handle setting an alias for something that does not exist.
3823 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003824 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003825 "Expected to update a single entry but instead updated 0",
3826 );
3827 // Test that we correctly abort the transaction in this case.
3828 let entries = get_keyentry(&db)?;
3829 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003830 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3831 assert_eq!(
3832 extractor(&entries[1]),
3833 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3834 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003835
3836 Ok(())
3837 }
3838
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003839 #[test]
3840 fn test_grant_ungrant() -> Result<()> {
3841 const CALLER_UID: u32 = 15;
3842 const GRANTEE_UID: u32 = 12;
3843 const SELINUX_NAMESPACE: i64 = 7;
3844
3845 let mut db = new_test_db()?;
3846 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003847 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3848 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3849 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003850 )?;
3851 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003852 domain: super::Domain::APP,
3853 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003854 alias: Some("key".to_string()),
3855 blob: None,
3856 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003857 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3858 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003859
3860 // Reset totally predictable random number generator in case we
3861 // are not the first test running on this thread.
3862 reset_random();
3863 let next_random = 0i64;
3864
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003865 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003866 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003867 assert_eq!(*a, PVEC1);
3868 assert_eq!(
3869 *k,
3870 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003871 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003872 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003873 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003874 alias: Some("key".to_string()),
3875 blob: None,
3876 }
3877 );
3878 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003879 })
3880 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003881
3882 assert_eq!(
3883 app_granted_key,
3884 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003885 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003886 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003887 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003888 alias: None,
3889 blob: None,
3890 }
3891 );
3892
3893 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003894 domain: super::Domain::SELINUX,
3895 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003896 alias: Some("yek".to_string()),
3897 blob: None,
3898 };
3899
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003900 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003901 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003902 assert_eq!(*a, PVEC1);
3903 assert_eq!(
3904 *k,
3905 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003906 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003907 // namespace must be the supplied SELinux
3908 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003909 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003910 alias: Some("yek".to_string()),
3911 blob: None,
3912 }
3913 );
3914 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003915 })
3916 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003917
3918 assert_eq!(
3919 selinux_granted_key,
3920 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003921 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003922 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003923 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003924 alias: None,
3925 blob: None,
3926 }
3927 );
3928
3929 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003930 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003931 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003932 assert_eq!(*a, PVEC2);
3933 assert_eq!(
3934 *k,
3935 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003936 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003937 // namespace must be the supplied SELinux
3938 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003939 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003940 alias: Some("yek".to_string()),
3941 blob: None,
3942 }
3943 );
3944 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003945 })
3946 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003947
3948 assert_eq!(
3949 selinux_granted_key,
3950 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003951 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003952 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003953 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003954 alias: None,
3955 blob: None,
3956 }
3957 );
3958
3959 {
3960 // Limiting scope of stmt, because it borrows db.
3961 let mut stmt = db
3962 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003963 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003964 let mut rows =
3965 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3966 Ok((
3967 row.get(0)?,
3968 row.get(1)?,
3969 row.get(2)?,
3970 KeyPermSet::from(row.get::<_, i32>(3)?),
3971 ))
3972 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003973
3974 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003975 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003976 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003977 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003978 assert!(rows.next().is_none());
3979 }
3980
3981 debug_dump_keyentry_table(&mut db)?;
3982 println!("app_key {:?}", app_key);
3983 println!("selinux_key {:?}", selinux_key);
3984
Janis Danisevskis66784c42021-01-27 08:40:25 -08003985 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3986 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003987
3988 Ok(())
3989 }
3990
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003991 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003992 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3993 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3994
3995 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003996 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003997 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003998 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003999 let mut blob_metadata = BlobMetaData::new();
4000 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4001 db.set_blob(
4002 &key_id,
4003 SubComponentType::KEY_BLOB,
4004 Some(TEST_KEY_BLOB),
4005 Some(&blob_metadata),
4006 )?;
4007 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4008 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004009 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004010
4011 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004012 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004013 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004014 )?;
4015 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004016 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
4017 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004018 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004019 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004020 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004021 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004022 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004023 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004024 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004025
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004026 drop(rows);
4027 drop(stmt);
4028
4029 assert_eq!(
4030 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4031 BlobMetaData::load_from_db(id, tx).no_gc()
4032 })
4033 .expect("Should find blob metadata."),
4034 blob_metadata
4035 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004036 Ok(())
4037 }
4038
4039 static TEST_ALIAS: &str = "my super duper key";
4040
4041 #[test]
4042 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
4043 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004044 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004045 .context("test_insert_and_load_full_keyentry_domain_app")?
4046 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004047 let (_key_guard, key_entry) = db
4048 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004049 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004050 domain: Domain::APP,
4051 nspace: 0,
4052 alias: Some(TEST_ALIAS.to_string()),
4053 blob: None,
4054 },
4055 KeyType::Client,
4056 KeyEntryLoadBits::BOTH,
4057 1,
4058 |_k, _av| Ok(()),
4059 )
4060 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004061 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004062
4063 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004064 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004065 domain: Domain::APP,
4066 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004067 alias: Some(TEST_ALIAS.to_string()),
4068 blob: None,
4069 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004070 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004071 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004072 |_, _| Ok(()),
4073 )
4074 .unwrap();
4075
4076 assert_eq!(
4077 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4078 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004079 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004080 domain: Domain::APP,
4081 nspace: 0,
4082 alias: Some(TEST_ALIAS.to_string()),
4083 blob: None,
4084 },
4085 KeyType::Client,
4086 KeyEntryLoadBits::NONE,
4087 1,
4088 |_k, _av| Ok(()),
4089 )
4090 .unwrap_err()
4091 .root_cause()
4092 .downcast_ref::<KsError>()
4093 );
4094
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004095 Ok(())
4096 }
4097
4098 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004099 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4100 let mut db = new_test_db()?;
4101
4102 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004103 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004104 domain: Domain::APP,
4105 nspace: 1,
4106 alias: Some(TEST_ALIAS.to_string()),
4107 blob: None,
4108 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004109 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004110 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004111 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004112 )
4113 .expect("Trying to insert cert.");
4114
4115 let (_key_guard, mut key_entry) = db
4116 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004117 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004118 domain: Domain::APP,
4119 nspace: 1,
4120 alias: Some(TEST_ALIAS.to_string()),
4121 blob: None,
4122 },
4123 KeyType::Client,
4124 KeyEntryLoadBits::PUBLIC,
4125 1,
4126 |_k, _av| Ok(()),
4127 )
4128 .expect("Trying to read certificate entry.");
4129
4130 assert!(key_entry.pure_cert());
4131 assert!(key_entry.cert().is_none());
4132 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4133
4134 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004135 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004136 domain: Domain::APP,
4137 nspace: 1,
4138 alias: Some(TEST_ALIAS.to_string()),
4139 blob: None,
4140 },
4141 KeyType::Client,
4142 1,
4143 |_, _| Ok(()),
4144 )
4145 .unwrap();
4146
4147 assert_eq!(
4148 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4149 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004150 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004151 domain: Domain::APP,
4152 nspace: 1,
4153 alias: Some(TEST_ALIAS.to_string()),
4154 blob: None,
4155 },
4156 KeyType::Client,
4157 KeyEntryLoadBits::NONE,
4158 1,
4159 |_k, _av| Ok(()),
4160 )
4161 .unwrap_err()
4162 .root_cause()
4163 .downcast_ref::<KsError>()
4164 );
4165
4166 Ok(())
4167 }
4168
4169 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004170 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4171 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004172 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004173 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4174 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004175 let (_key_guard, key_entry) = db
4176 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004177 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004178 domain: Domain::SELINUX,
4179 nspace: 1,
4180 alias: Some(TEST_ALIAS.to_string()),
4181 blob: None,
4182 },
4183 KeyType::Client,
4184 KeyEntryLoadBits::BOTH,
4185 1,
4186 |_k, _av| Ok(()),
4187 )
4188 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004189 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004190
4191 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004192 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004193 domain: Domain::SELINUX,
4194 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004195 alias: Some(TEST_ALIAS.to_string()),
4196 blob: None,
4197 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004198 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004199 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004200 |_, _| Ok(()),
4201 )
4202 .unwrap();
4203
4204 assert_eq!(
4205 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4206 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004207 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004208 domain: Domain::SELINUX,
4209 nspace: 1,
4210 alias: Some(TEST_ALIAS.to_string()),
4211 blob: None,
4212 },
4213 KeyType::Client,
4214 KeyEntryLoadBits::NONE,
4215 1,
4216 |_k, _av| Ok(()),
4217 )
4218 .unwrap_err()
4219 .root_cause()
4220 .downcast_ref::<KsError>()
4221 );
4222
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004223 Ok(())
4224 }
4225
4226 #[test]
4227 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4228 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004229 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004230 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4231 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004232 let (_, key_entry) = db
4233 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004234 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004235 KeyType::Client,
4236 KeyEntryLoadBits::BOTH,
4237 1,
4238 |_k, _av| Ok(()),
4239 )
4240 .unwrap();
4241
Qi Wub9433b52020-12-01 14:52:46 +08004242 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004243
4244 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004245 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004246 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004247 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004248 |_, _| Ok(()),
4249 )
4250 .unwrap();
4251
4252 assert_eq!(
4253 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4254 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004255 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004256 KeyType::Client,
4257 KeyEntryLoadBits::NONE,
4258 1,
4259 |_k, _av| Ok(()),
4260 )
4261 .unwrap_err()
4262 .root_cause()
4263 .downcast_ref::<KsError>()
4264 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004265
4266 Ok(())
4267 }
4268
4269 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004270 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4271 let mut db = new_test_db()?;
4272 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4273 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4274 .0;
4275 // Update the usage count of the limited use key.
4276 db.check_and_update_key_usage_count(key_id)?;
4277
4278 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004279 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004280 KeyType::Client,
4281 KeyEntryLoadBits::BOTH,
4282 1,
4283 |_k, _av| Ok(()),
4284 )?;
4285
4286 // The usage count is decremented now.
4287 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4288
4289 Ok(())
4290 }
4291
4292 #[test]
4293 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4294 let mut db = new_test_db()?;
4295 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4296 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4297 .0;
4298 // Update the usage count of the limited use key.
4299 db.check_and_update_key_usage_count(key_id).expect(concat!(
4300 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4301 "This should succeed."
4302 ));
4303
4304 // Try to update the exhausted limited use key.
4305 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4306 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4307 "This should fail."
4308 ));
4309 assert_eq!(
4310 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4311 e.root_cause().downcast_ref::<KsError>().unwrap()
4312 );
4313
4314 Ok(())
4315 }
4316
4317 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004318 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4319 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004320 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004321 .context("test_insert_and_load_full_keyentry_from_grant")?
4322 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004323
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004324 let granted_key = db
4325 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004326 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004327 domain: Domain::APP,
4328 nspace: 0,
4329 alias: Some(TEST_ALIAS.to_string()),
4330 blob: None,
4331 },
4332 1,
4333 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004334 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004335 |_k, _av| Ok(()),
4336 )
4337 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004338
4339 debug_dump_grant_table(&mut db)?;
4340
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004341 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004342 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4343 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004344 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08004345 Ok(())
4346 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004347 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004348
Qi Wub9433b52020-12-01 14:52:46 +08004349 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004350
Janis Danisevskis66784c42021-01-27 08:40:25 -08004351 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004352
4353 assert_eq!(
4354 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4355 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004356 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004357 KeyType::Client,
4358 KeyEntryLoadBits::NONE,
4359 2,
4360 |_k, _av| Ok(()),
4361 )
4362 .unwrap_err()
4363 .root_cause()
4364 .downcast_ref::<KsError>()
4365 );
4366
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004367 Ok(())
4368 }
4369
Janis Danisevskis45760022021-01-19 16:34:10 -08004370 // This test attempts to load a key by key id while the caller is not the owner
4371 // but a grant exists for the given key and the caller.
4372 #[test]
4373 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4374 let mut db = new_test_db()?;
4375 const OWNER_UID: u32 = 1u32;
4376 const GRANTEE_UID: u32 = 2u32;
4377 const SOMEONE_ELSE_UID: u32 = 3u32;
4378 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4379 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4380 .0;
4381
4382 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004383 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004384 domain: Domain::APP,
4385 nspace: 0,
4386 alias: Some(TEST_ALIAS.to_string()),
4387 blob: None,
4388 },
4389 OWNER_UID,
4390 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004391 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08004392 |_k, _av| Ok(()),
4393 )
4394 .unwrap();
4395
4396 debug_dump_grant_table(&mut db)?;
4397
4398 let id_descriptor =
4399 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4400
4401 let (_, key_entry) = db
4402 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004403 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004404 KeyType::Client,
4405 KeyEntryLoadBits::BOTH,
4406 GRANTEE_UID,
4407 |k, av| {
4408 assert_eq!(Domain::APP, k.domain);
4409 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004410 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08004411 Ok(())
4412 },
4413 )
4414 .unwrap();
4415
4416 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4417
4418 let (_, key_entry) = db
4419 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004420 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004421 KeyType::Client,
4422 KeyEntryLoadBits::BOTH,
4423 SOMEONE_ELSE_UID,
4424 |k, av| {
4425 assert_eq!(Domain::APP, k.domain);
4426 assert_eq!(OWNER_UID as i64, k.nspace);
4427 assert!(av.is_none());
4428 Ok(())
4429 },
4430 )
4431 .unwrap();
4432
4433 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4434
Janis Danisevskis66784c42021-01-27 08:40:25 -08004435 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004436
4437 assert_eq!(
4438 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4439 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004440 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004441 KeyType::Client,
4442 KeyEntryLoadBits::NONE,
4443 GRANTEE_UID,
4444 |_k, _av| Ok(()),
4445 )
4446 .unwrap_err()
4447 .root_cause()
4448 .downcast_ref::<KsError>()
4449 );
4450
4451 Ok(())
4452 }
4453
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004454 // Creates a key migrates it to a different location and then tries to access it by the old
4455 // and new location.
4456 #[test]
4457 fn test_migrate_key_app_to_app() -> Result<()> {
4458 let mut db = new_test_db()?;
4459 const SOURCE_UID: u32 = 1u32;
4460 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004461 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4462 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004463 let key_id_guard =
4464 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4465 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4466
4467 let source_descriptor: KeyDescriptor = KeyDescriptor {
4468 domain: Domain::APP,
4469 nspace: -1,
4470 alias: Some(SOURCE_ALIAS.to_string()),
4471 blob: None,
4472 };
4473
4474 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4475 domain: Domain::APP,
4476 nspace: -1,
4477 alias: Some(DESTINATION_ALIAS.to_string()),
4478 blob: None,
4479 };
4480
4481 let key_id = key_id_guard.id();
4482
4483 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4484 Ok(())
4485 })
4486 .unwrap();
4487
4488 let (_, key_entry) = db
4489 .load_key_entry(
4490 &destination_descriptor,
4491 KeyType::Client,
4492 KeyEntryLoadBits::BOTH,
4493 DESTINATION_UID,
4494 |k, av| {
4495 assert_eq!(Domain::APP, k.domain);
4496 assert_eq!(DESTINATION_UID as i64, k.nspace);
4497 assert!(av.is_none());
4498 Ok(())
4499 },
4500 )
4501 .unwrap();
4502
4503 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4504
4505 assert_eq!(
4506 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4507 db.load_key_entry(
4508 &source_descriptor,
4509 KeyType::Client,
4510 KeyEntryLoadBits::NONE,
4511 SOURCE_UID,
4512 |_k, _av| Ok(()),
4513 )
4514 .unwrap_err()
4515 .root_cause()
4516 .downcast_ref::<KsError>()
4517 );
4518
4519 Ok(())
4520 }
4521
4522 // Creates a key migrates it to a different location and then tries to access it by the old
4523 // and new location.
4524 #[test]
4525 fn test_migrate_key_app_to_selinux() -> Result<()> {
4526 let mut db = new_test_db()?;
4527 const SOURCE_UID: u32 = 1u32;
4528 const DESTINATION_UID: u32 = 2u32;
4529 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004530 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4531 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004532 let key_id_guard =
4533 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4534 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4535
4536 let source_descriptor: KeyDescriptor = KeyDescriptor {
4537 domain: Domain::APP,
4538 nspace: -1,
4539 alias: Some(SOURCE_ALIAS.to_string()),
4540 blob: None,
4541 };
4542
4543 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4544 domain: Domain::SELINUX,
4545 nspace: DESTINATION_NAMESPACE,
4546 alias: Some(DESTINATION_ALIAS.to_string()),
4547 blob: None,
4548 };
4549
4550 let key_id = key_id_guard.id();
4551
4552 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4553 Ok(())
4554 })
4555 .unwrap();
4556
4557 let (_, key_entry) = db
4558 .load_key_entry(
4559 &destination_descriptor,
4560 KeyType::Client,
4561 KeyEntryLoadBits::BOTH,
4562 DESTINATION_UID,
4563 |k, av| {
4564 assert_eq!(Domain::SELINUX, k.domain);
4565 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4566 assert!(av.is_none());
4567 Ok(())
4568 },
4569 )
4570 .unwrap();
4571
4572 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4573
4574 assert_eq!(
4575 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4576 db.load_key_entry(
4577 &source_descriptor,
4578 KeyType::Client,
4579 KeyEntryLoadBits::NONE,
4580 SOURCE_UID,
4581 |_k, _av| Ok(()),
4582 )
4583 .unwrap_err()
4584 .root_cause()
4585 .downcast_ref::<KsError>()
4586 );
4587
4588 Ok(())
4589 }
4590
4591 // Creates two keys and tries to migrate the first to the location of the second which
4592 // is expected to fail.
4593 #[test]
4594 fn test_migrate_key_destination_occupied() -> Result<()> {
4595 let mut db = new_test_db()?;
4596 const SOURCE_UID: u32 = 1u32;
4597 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004598 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4599 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004600 let key_id_guard =
4601 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4602 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4603 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4604 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4605
4606 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4607 domain: Domain::APP,
4608 nspace: -1,
4609 alias: Some(DESTINATION_ALIAS.to_string()),
4610 blob: None,
4611 };
4612
4613 assert_eq!(
4614 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4615 db.migrate_key_namespace(
4616 key_id_guard,
4617 &destination_descriptor,
4618 DESTINATION_UID,
4619 |_k| Ok(())
4620 )
4621 .unwrap_err()
4622 .root_cause()
4623 .downcast_ref::<KsError>()
4624 );
4625
4626 Ok(())
4627 }
4628
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004629 #[test]
4630 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004631 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4632 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4633 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004634 const UID: u32 = 33;
4635 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4636 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4637 let key_id_untouched1 =
4638 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4639 let key_id_untouched2 =
4640 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4641 let key_id_deleted =
4642 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4643
4644 let (_, key_entry) = db
4645 .load_key_entry(
4646 &KeyDescriptor {
4647 domain: Domain::APP,
4648 nspace: -1,
4649 alias: Some(ALIAS1.to_string()),
4650 blob: None,
4651 },
4652 KeyType::Client,
4653 KeyEntryLoadBits::BOTH,
4654 UID,
4655 |k, av| {
4656 assert_eq!(Domain::APP, k.domain);
4657 assert_eq!(UID as i64, k.nspace);
4658 assert!(av.is_none());
4659 Ok(())
4660 },
4661 )
4662 .unwrap();
4663 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4664 let (_, key_entry) = db
4665 .load_key_entry(
4666 &KeyDescriptor {
4667 domain: Domain::APP,
4668 nspace: -1,
4669 alias: Some(ALIAS2.to_string()),
4670 blob: None,
4671 },
4672 KeyType::Client,
4673 KeyEntryLoadBits::BOTH,
4674 UID,
4675 |k, av| {
4676 assert_eq!(Domain::APP, k.domain);
4677 assert_eq!(UID as i64, k.nspace);
4678 assert!(av.is_none());
4679 Ok(())
4680 },
4681 )
4682 .unwrap();
4683 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4684 let (_, key_entry) = db
4685 .load_key_entry(
4686 &KeyDescriptor {
4687 domain: Domain::APP,
4688 nspace: -1,
4689 alias: Some(ALIAS3.to_string()),
4690 blob: None,
4691 },
4692 KeyType::Client,
4693 KeyEntryLoadBits::BOTH,
4694 UID,
4695 |k, av| {
4696 assert_eq!(Domain::APP, k.domain);
4697 assert_eq!(UID as i64, k.nspace);
4698 assert!(av.is_none());
4699 Ok(())
4700 },
4701 )
4702 .unwrap();
4703 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4704
4705 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4706 KeystoreDB::from_0_to_1(tx).no_gc()
4707 })
4708 .unwrap();
4709
4710 let (_, key_entry) = db
4711 .load_key_entry(
4712 &KeyDescriptor {
4713 domain: Domain::APP,
4714 nspace: -1,
4715 alias: Some(ALIAS1.to_string()),
4716 blob: None,
4717 },
4718 KeyType::Client,
4719 KeyEntryLoadBits::BOTH,
4720 UID,
4721 |k, av| {
4722 assert_eq!(Domain::APP, k.domain);
4723 assert_eq!(UID as i64, k.nspace);
4724 assert!(av.is_none());
4725 Ok(())
4726 },
4727 )
4728 .unwrap();
4729 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4730 let (_, key_entry) = db
4731 .load_key_entry(
4732 &KeyDescriptor {
4733 domain: Domain::APP,
4734 nspace: -1,
4735 alias: Some(ALIAS2.to_string()),
4736 blob: None,
4737 },
4738 KeyType::Client,
4739 KeyEntryLoadBits::BOTH,
4740 UID,
4741 |k, av| {
4742 assert_eq!(Domain::APP, k.domain);
4743 assert_eq!(UID as i64, k.nspace);
4744 assert!(av.is_none());
4745 Ok(())
4746 },
4747 )
4748 .unwrap();
4749 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4750 assert_eq!(
4751 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4752 db.load_key_entry(
4753 &KeyDescriptor {
4754 domain: Domain::APP,
4755 nspace: -1,
4756 alias: Some(ALIAS3.to_string()),
4757 blob: None,
4758 },
4759 KeyType::Client,
4760 KeyEntryLoadBits::BOTH,
4761 UID,
4762 |k, av| {
4763 assert_eq!(Domain::APP, k.domain);
4764 assert_eq!(UID as i64, k.nspace);
4765 assert!(av.is_none());
4766 Ok(())
4767 },
4768 )
4769 .unwrap_err()
4770 .root_cause()
4771 .downcast_ref::<KsError>()
4772 );
4773 }
4774
Janis Danisevskisaec14592020-11-12 09:41:49 -08004775 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4776
Janis Danisevskisaec14592020-11-12 09:41:49 -08004777 #[test]
4778 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4779 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004780 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4781 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004782 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004783 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004784 .context("test_insert_and_load_full_keyentry_domain_app")?
4785 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004786 let (_key_guard, key_entry) = db
4787 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004788 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004789 domain: Domain::APP,
4790 nspace: 0,
4791 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4792 blob: None,
4793 },
4794 KeyType::Client,
4795 KeyEntryLoadBits::BOTH,
4796 33,
4797 |_k, _av| Ok(()),
4798 )
4799 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004800 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004801 let state = Arc::new(AtomicU8::new(1));
4802 let state2 = state.clone();
4803
4804 // Spawning a second thread that attempts to acquire the key id lock
4805 // for the same key as the primary thread. The primary thread then
4806 // waits, thereby forcing the secondary thread into the second stage
4807 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4808 // The test succeeds if the secondary thread observes the transition
4809 // of `state` from 1 to 2, despite having a whole second to overtake
4810 // the primary thread.
4811 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004812 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004813 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004814 assert!(db
4815 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004816 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004817 domain: Domain::APP,
4818 nspace: 0,
4819 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4820 blob: None,
4821 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004822 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004823 KeyEntryLoadBits::BOTH,
4824 33,
4825 |_k, _av| Ok(()),
4826 )
4827 .is_ok());
4828 // We should only see a 2 here because we can only return
4829 // from load_key_entry when the `_key_guard` expires,
4830 // which happens at the end of the scope.
4831 assert_eq!(2, state2.load(Ordering::Relaxed));
4832 });
4833
4834 thread::sleep(std::time::Duration::from_millis(1000));
4835
4836 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4837
4838 // Return the handle from this scope so we can join with the
4839 // secondary thread after the key id lock has expired.
4840 handle
4841 // This is where the `_key_guard` goes out of scope,
4842 // which is the reason for concurrent load_key_entry on the same key
4843 // to unblock.
4844 };
4845 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4846 // main test thread. We will not see failing asserts in secondary threads otherwise.
4847 handle.join().unwrap();
4848 Ok(())
4849 }
4850
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004851 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004852 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004853 let temp_dir =
4854 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4855
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004856 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4857 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004858
4859 let _tx1 = db1
4860 .conn
4861 .transaction_with_behavior(TransactionBehavior::Immediate)
4862 .expect("Failed to create first transaction.");
4863
4864 let error = db2
4865 .conn
4866 .transaction_with_behavior(TransactionBehavior::Immediate)
4867 .context("Transaction begin failed.")
4868 .expect_err("This should fail.");
4869 let root_cause = error.root_cause();
4870 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4871 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4872 {
4873 return;
4874 }
4875 panic!(
4876 "Unexpected error {:?} \n{:?} \n{:?}",
4877 error,
4878 root_cause,
4879 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4880 )
4881 }
4882
4883 #[cfg(disabled)]
4884 #[test]
4885 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4886 let temp_dir = Arc::new(
4887 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4888 .expect("Failed to create temp dir."),
4889 );
4890
4891 let test_begin = Instant::now();
4892
Janis Danisevskis66784c42021-01-27 08:40:25 -08004893 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004894 let mut db =
4895 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004896 const OPEN_DB_COUNT: u32 = 50u32;
4897
4898 let mut actual_key_count = KEY_COUNT;
4899 // First insert KEY_COUNT keys.
4900 for count in 0..KEY_COUNT {
4901 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4902 actual_key_count = count;
4903 break;
4904 }
4905 let alias = format!("test_alias_{}", count);
4906 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4907 .expect("Failed to make key entry.");
4908 }
4909
4910 // Insert more keys from a different thread and into a different namespace.
4911 let temp_dir1 = temp_dir.clone();
4912 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004913 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4914 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004915
4916 for count in 0..actual_key_count {
4917 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4918 return;
4919 }
4920 let alias = format!("test_alias_{}", count);
4921 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4922 .expect("Failed to make key entry.");
4923 }
4924
4925 // then unbind them again.
4926 for count in 0..actual_key_count {
4927 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4928 return;
4929 }
4930 let key = KeyDescriptor {
4931 domain: Domain::APP,
4932 nspace: -1,
4933 alias: Some(format!("test_alias_{}", count)),
4934 blob: None,
4935 };
4936 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4937 }
4938 });
4939
4940 // And start unbinding the first set of keys.
4941 let temp_dir2 = temp_dir.clone();
4942 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004943 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4944 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004945
4946 for count in 0..actual_key_count {
4947 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4948 return;
4949 }
4950 let key = KeyDescriptor {
4951 domain: Domain::APP,
4952 nspace: -1,
4953 alias: Some(format!("test_alias_{}", count)),
4954 blob: None,
4955 };
4956 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4957 }
4958 });
4959
Janis Danisevskis66784c42021-01-27 08:40:25 -08004960 // While a lot of inserting and deleting is going on we have to open database connections
4961 // successfully and use them.
4962 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4963 // out of scope.
4964 #[allow(clippy::redundant_clone)]
4965 let temp_dir4 = temp_dir.clone();
4966 let handle4 = thread::spawn(move || {
4967 for count in 0..OPEN_DB_COUNT {
4968 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4969 return;
4970 }
Seth Moore444b51a2021-06-11 09:49:49 -07004971 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4972 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004973
4974 let alias = format!("test_alias_{}", count);
4975 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4976 .expect("Failed to make key entry.");
4977 let key = KeyDescriptor {
4978 domain: Domain::APP,
4979 nspace: -1,
4980 alias: Some(alias),
4981 blob: None,
4982 };
4983 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4984 }
4985 });
4986
4987 handle1.join().expect("Thread 1 panicked.");
4988 handle2.join().expect("Thread 2 panicked.");
4989 handle4.join().expect("Thread 4 panicked.");
4990
Janis Danisevskis66784c42021-01-27 08:40:25 -08004991 Ok(())
4992 }
4993
4994 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004995 fn list() -> Result<()> {
4996 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004997 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004998 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4999 (Domain::APP, 1, "test1"),
5000 (Domain::APP, 1, "test2"),
5001 (Domain::APP, 1, "test3"),
5002 (Domain::APP, 1, "test4"),
5003 (Domain::APP, 1, "test5"),
5004 (Domain::APP, 1, "test6"),
5005 (Domain::APP, 1, "test7"),
5006 (Domain::APP, 2, "test1"),
5007 (Domain::APP, 2, "test2"),
5008 (Domain::APP, 2, "test3"),
5009 (Domain::APP, 2, "test4"),
5010 (Domain::APP, 2, "test5"),
5011 (Domain::APP, 2, "test6"),
5012 (Domain::APP, 2, "test8"),
5013 (Domain::SELINUX, 100, "test1"),
5014 (Domain::SELINUX, 100, "test2"),
5015 (Domain::SELINUX, 100, "test3"),
5016 (Domain::SELINUX, 100, "test4"),
5017 (Domain::SELINUX, 100, "test5"),
5018 (Domain::SELINUX, 100, "test6"),
5019 (Domain::SELINUX, 100, "test9"),
5020 ];
5021
5022 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
5023 .iter()
5024 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08005025 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
5026 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005027 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
5028 });
5029 (entry.id(), *ns)
5030 })
5031 .collect();
5032
5033 for (domain, namespace) in
5034 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
5035 {
5036 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
5037 .iter()
5038 .filter_map(|(domain, ns, alias)| match ns {
5039 ns if *ns == *namespace => Some(KeyDescriptor {
5040 domain: *domain,
5041 nspace: *ns,
5042 alias: Some(alias.to_string()),
5043 blob: None,
5044 }),
5045 _ => None,
5046 })
5047 .collect();
5048 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07005049 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005050 list_result.sort();
5051 assert_eq!(list_o_descriptors, list_result);
5052
5053 let mut list_o_ids: Vec<i64> = list_o_descriptors
5054 .into_iter()
5055 .map(|d| {
5056 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005057 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08005058 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005059 KeyType::Client,
5060 KeyEntryLoadBits::NONE,
5061 *namespace as u32,
5062 |_, _| Ok(()),
5063 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005064 .unwrap();
5065 entry.id()
5066 })
5067 .collect();
5068 list_o_ids.sort_unstable();
5069 let mut loaded_entries: Vec<i64> = list_o_keys
5070 .iter()
5071 .filter_map(|(id, ns)| match ns {
5072 ns if *ns == *namespace => Some(*id),
5073 _ => None,
5074 })
5075 .collect();
5076 loaded_entries.sort_unstable();
5077 assert_eq!(list_o_ids, loaded_entries);
5078 }
Janis Danisevskis18313832021-05-17 13:30:32 -07005079 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005080
5081 Ok(())
5082 }
5083
Joel Galenson0891bc12020-07-20 10:37:03 -07005084 // Helpers
5085
5086 // Checks that the given result is an error containing the given string.
5087 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
5088 let error_str = format!(
5089 "{:#?}",
5090 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
5091 );
5092 assert!(
5093 error_str.contains(target),
5094 "The string \"{}\" should contain \"{}\"",
5095 error_str,
5096 target
5097 );
5098 }
5099
Joel Galenson2aab4432020-07-22 15:27:57 -07005100 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07005101 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005102 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005103 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005104 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005105 namespace: Option<i64>,
5106 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005107 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08005108 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005109 }
5110
5111 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
5112 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07005113 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07005114 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07005115 Ok(KeyEntryRow {
5116 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005117 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07005118 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07005119 namespace: row.get(3)?,
5120 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005121 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08005122 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07005123 })
5124 })?
5125 .map(|r| r.context("Could not read keyentry row."))
5126 .collect::<Result<Vec<_>>>()
5127 }
5128
Max Biresb2e1d032021-02-08 21:35:05 -08005129 struct RemoteProvValues {
5130 cert_chain: Vec<u8>,
5131 priv_key: Vec<u8>,
5132 batch_cert: Vec<u8>,
5133 }
5134
Max Bires2b2e6562020-09-22 11:22:36 -07005135 fn load_attestation_key_pool(
5136 db: &mut KeystoreDB,
5137 expiration_date: i64,
5138 namespace: i64,
5139 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08005140 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07005141 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
5142 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
5143 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5144 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005145 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005146 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5147 db.store_signed_attestation_certificate_chain(
5148 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005149 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005150 &cert_chain,
5151 expiration_date,
5152 &KEYSTORE_UUID,
5153 )?;
5154 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005155 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005156 }
5157
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005158 // Note: The parameters and SecurityLevel associations are nonsensical. This
5159 // collection is only used to check if the parameters are preserved as expected by the
5160 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005161 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5162 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005163 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5164 KeyParameter::new(
5165 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5166 SecurityLevel::TRUSTED_ENVIRONMENT,
5167 ),
5168 KeyParameter::new(
5169 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5170 SecurityLevel::TRUSTED_ENVIRONMENT,
5171 ),
5172 KeyParameter::new(
5173 KeyParameterValue::Algorithm(Algorithm::RSA),
5174 SecurityLevel::TRUSTED_ENVIRONMENT,
5175 ),
5176 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5177 KeyParameter::new(
5178 KeyParameterValue::BlockMode(BlockMode::ECB),
5179 SecurityLevel::TRUSTED_ENVIRONMENT,
5180 ),
5181 KeyParameter::new(
5182 KeyParameterValue::BlockMode(BlockMode::GCM),
5183 SecurityLevel::TRUSTED_ENVIRONMENT,
5184 ),
5185 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5186 KeyParameter::new(
5187 KeyParameterValue::Digest(Digest::MD5),
5188 SecurityLevel::TRUSTED_ENVIRONMENT,
5189 ),
5190 KeyParameter::new(
5191 KeyParameterValue::Digest(Digest::SHA_2_224),
5192 SecurityLevel::TRUSTED_ENVIRONMENT,
5193 ),
5194 KeyParameter::new(
5195 KeyParameterValue::Digest(Digest::SHA_2_256),
5196 SecurityLevel::STRONGBOX,
5197 ),
5198 KeyParameter::new(
5199 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5200 SecurityLevel::TRUSTED_ENVIRONMENT,
5201 ),
5202 KeyParameter::new(
5203 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5204 SecurityLevel::TRUSTED_ENVIRONMENT,
5205 ),
5206 KeyParameter::new(
5207 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5208 SecurityLevel::STRONGBOX,
5209 ),
5210 KeyParameter::new(
5211 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5212 SecurityLevel::TRUSTED_ENVIRONMENT,
5213 ),
5214 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5215 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5216 KeyParameter::new(
5217 KeyParameterValue::EcCurve(EcCurve::P_224),
5218 SecurityLevel::TRUSTED_ENVIRONMENT,
5219 ),
5220 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5221 KeyParameter::new(
5222 KeyParameterValue::EcCurve(EcCurve::P_384),
5223 SecurityLevel::TRUSTED_ENVIRONMENT,
5224 ),
5225 KeyParameter::new(
5226 KeyParameterValue::EcCurve(EcCurve::P_521),
5227 SecurityLevel::TRUSTED_ENVIRONMENT,
5228 ),
5229 KeyParameter::new(
5230 KeyParameterValue::RSAPublicExponent(3),
5231 SecurityLevel::TRUSTED_ENVIRONMENT,
5232 ),
5233 KeyParameter::new(
5234 KeyParameterValue::IncludeUniqueID,
5235 SecurityLevel::TRUSTED_ENVIRONMENT,
5236 ),
5237 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5238 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5239 KeyParameter::new(
5240 KeyParameterValue::ActiveDateTime(1234567890),
5241 SecurityLevel::STRONGBOX,
5242 ),
5243 KeyParameter::new(
5244 KeyParameterValue::OriginationExpireDateTime(1234567890),
5245 SecurityLevel::TRUSTED_ENVIRONMENT,
5246 ),
5247 KeyParameter::new(
5248 KeyParameterValue::UsageExpireDateTime(1234567890),
5249 SecurityLevel::TRUSTED_ENVIRONMENT,
5250 ),
5251 KeyParameter::new(
5252 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5253 SecurityLevel::TRUSTED_ENVIRONMENT,
5254 ),
5255 KeyParameter::new(
5256 KeyParameterValue::MaxUsesPerBoot(1234567890),
5257 SecurityLevel::TRUSTED_ENVIRONMENT,
5258 ),
5259 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5260 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5261 KeyParameter::new(
5262 KeyParameterValue::NoAuthRequired,
5263 SecurityLevel::TRUSTED_ENVIRONMENT,
5264 ),
5265 KeyParameter::new(
5266 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5267 SecurityLevel::TRUSTED_ENVIRONMENT,
5268 ),
5269 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5270 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5271 KeyParameter::new(
5272 KeyParameterValue::TrustedUserPresenceRequired,
5273 SecurityLevel::TRUSTED_ENVIRONMENT,
5274 ),
5275 KeyParameter::new(
5276 KeyParameterValue::TrustedConfirmationRequired,
5277 SecurityLevel::TRUSTED_ENVIRONMENT,
5278 ),
5279 KeyParameter::new(
5280 KeyParameterValue::UnlockedDeviceRequired,
5281 SecurityLevel::TRUSTED_ENVIRONMENT,
5282 ),
5283 KeyParameter::new(
5284 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5285 SecurityLevel::SOFTWARE,
5286 ),
5287 KeyParameter::new(
5288 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5289 SecurityLevel::SOFTWARE,
5290 ),
5291 KeyParameter::new(
5292 KeyParameterValue::CreationDateTime(12345677890),
5293 SecurityLevel::SOFTWARE,
5294 ),
5295 KeyParameter::new(
5296 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5297 SecurityLevel::TRUSTED_ENVIRONMENT,
5298 ),
5299 KeyParameter::new(
5300 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5301 SecurityLevel::TRUSTED_ENVIRONMENT,
5302 ),
5303 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5304 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5305 KeyParameter::new(
5306 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5307 SecurityLevel::SOFTWARE,
5308 ),
5309 KeyParameter::new(
5310 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5311 SecurityLevel::TRUSTED_ENVIRONMENT,
5312 ),
5313 KeyParameter::new(
5314 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5315 SecurityLevel::TRUSTED_ENVIRONMENT,
5316 ),
5317 KeyParameter::new(
5318 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5319 SecurityLevel::TRUSTED_ENVIRONMENT,
5320 ),
5321 KeyParameter::new(
5322 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5323 SecurityLevel::TRUSTED_ENVIRONMENT,
5324 ),
5325 KeyParameter::new(
5326 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5327 SecurityLevel::TRUSTED_ENVIRONMENT,
5328 ),
5329 KeyParameter::new(
5330 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5331 SecurityLevel::TRUSTED_ENVIRONMENT,
5332 ),
5333 KeyParameter::new(
5334 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5335 SecurityLevel::TRUSTED_ENVIRONMENT,
5336 ),
5337 KeyParameter::new(
5338 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5339 SecurityLevel::TRUSTED_ENVIRONMENT,
5340 ),
5341 KeyParameter::new(
5342 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5343 SecurityLevel::TRUSTED_ENVIRONMENT,
5344 ),
5345 KeyParameter::new(
5346 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5347 SecurityLevel::TRUSTED_ENVIRONMENT,
5348 ),
5349 KeyParameter::new(
5350 KeyParameterValue::VendorPatchLevel(3),
5351 SecurityLevel::TRUSTED_ENVIRONMENT,
5352 ),
5353 KeyParameter::new(
5354 KeyParameterValue::BootPatchLevel(4),
5355 SecurityLevel::TRUSTED_ENVIRONMENT,
5356 ),
5357 KeyParameter::new(
5358 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5359 SecurityLevel::TRUSTED_ENVIRONMENT,
5360 ),
5361 KeyParameter::new(
5362 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5363 SecurityLevel::TRUSTED_ENVIRONMENT,
5364 ),
5365 KeyParameter::new(
5366 KeyParameterValue::MacLength(256),
5367 SecurityLevel::TRUSTED_ENVIRONMENT,
5368 ),
5369 KeyParameter::new(
5370 KeyParameterValue::ResetSinceIdRotation,
5371 SecurityLevel::TRUSTED_ENVIRONMENT,
5372 ),
5373 KeyParameter::new(
5374 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5375 SecurityLevel::TRUSTED_ENVIRONMENT,
5376 ),
Qi Wub9433b52020-12-01 14:52:46 +08005377 ];
5378 if let Some(value) = max_usage_count {
5379 params.push(KeyParameter::new(
5380 KeyParameterValue::UsageCountLimit(value),
5381 SecurityLevel::SOFTWARE,
5382 ));
5383 }
5384 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005385 }
5386
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005387 fn make_test_key_entry(
5388 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005389 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005390 namespace: i64,
5391 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005392 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005393 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005394 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005395 let mut blob_metadata = BlobMetaData::new();
5396 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5397 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5398 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5399 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5400 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5401
5402 db.set_blob(
5403 &key_id,
5404 SubComponentType::KEY_BLOB,
5405 Some(TEST_KEY_BLOB),
5406 Some(&blob_metadata),
5407 )?;
5408 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5409 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005410
5411 let params = make_test_params(max_usage_count);
5412 db.insert_keyparameter(&key_id, &params)?;
5413
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005414 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005415 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005416 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005417 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005418 Ok(key_id)
5419 }
5420
Qi Wub9433b52020-12-01 14:52:46 +08005421 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5422 let params = make_test_params(max_usage_count);
5423
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005424 let mut blob_metadata = BlobMetaData::new();
5425 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5426 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5427 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5428 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5429 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5430
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005431 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005432 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005433
5434 KeyEntry {
5435 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005436 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005437 cert: Some(TEST_CERT_BLOB.to_vec()),
5438 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005439 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005440 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005441 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005442 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005443 }
5444 }
5445
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005446 fn make_bootlevel_key_entry(
5447 db: &mut KeystoreDB,
5448 domain: Domain,
5449 namespace: i64,
5450 alias: &str,
5451 logical_only: bool,
5452 ) -> Result<KeyIdGuard> {
5453 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5454 let mut blob_metadata = BlobMetaData::new();
5455 if !logical_only {
5456 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5457 }
5458 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5459
5460 db.set_blob(
5461 &key_id,
5462 SubComponentType::KEY_BLOB,
5463 Some(TEST_KEY_BLOB),
5464 Some(&blob_metadata),
5465 )?;
5466 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5467 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5468
5469 let mut params = make_test_params(None);
5470 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5471
5472 db.insert_keyparameter(&key_id, &params)?;
5473
5474 let mut metadata = KeyMetaData::new();
5475 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5476 db.insert_key_metadata(&key_id, &metadata)?;
5477 rebind_alias(db, &key_id, alias, domain, namespace)?;
5478 Ok(key_id)
5479 }
5480
5481 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5482 let mut params = make_test_params(None);
5483 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5484
5485 let mut blob_metadata = BlobMetaData::new();
5486 if !logical_only {
5487 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5488 }
5489 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5490
5491 let mut metadata = KeyMetaData::new();
5492 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5493
5494 KeyEntry {
5495 id: key_id,
5496 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5497 cert: Some(TEST_CERT_BLOB.to_vec()),
5498 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5499 km_uuid: KEYSTORE_UUID,
5500 parameters: params,
5501 metadata,
5502 pure_cert: false,
5503 }
5504 }
5505
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005506 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005507 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005508 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005509 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005510 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005511 NO_PARAMS,
5512 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005513 Ok((
5514 row.get(0)?,
5515 row.get(1)?,
5516 row.get(2)?,
5517 row.get(3)?,
5518 row.get(4)?,
5519 row.get(5)?,
5520 row.get(6)?,
5521 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005522 },
5523 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005524
5525 println!("Key entry table rows:");
5526 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005527 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005528 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005529 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5530 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005531 );
5532 }
5533 Ok(())
5534 }
5535
5536 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005537 let mut stmt = db
5538 .conn
5539 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005540 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5541 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5542 })?;
5543
5544 println!("Grant table rows:");
5545 for r in rows {
5546 let (id, gt, ki, av) = r.unwrap();
5547 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5548 }
5549 Ok(())
5550 }
5551
Joel Galenson0891bc12020-07-20 10:37:03 -07005552 // Use a custom random number generator that repeats each number once.
5553 // This allows us to test repeated elements.
5554
5555 thread_local! {
5556 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5557 }
5558
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005559 fn reset_random() {
5560 RANDOM_COUNTER.with(|counter| {
5561 *counter.borrow_mut() = 0;
5562 })
5563 }
5564
Joel Galenson0891bc12020-07-20 10:37:03 -07005565 pub fn random() -> i64 {
5566 RANDOM_COUNTER.with(|counter| {
5567 let result = *counter.borrow() / 2;
5568 *counter.borrow_mut() += 1;
5569 result
5570 })
5571 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005572
5573 #[test]
5574 fn test_last_off_body() -> Result<()> {
5575 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005576 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005577 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005578 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005579 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005580 let one_second = Duration::from_secs(1);
5581 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005582 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005583 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005584 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005585 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005586 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005587 Ok(())
5588 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005589
5590 #[test]
5591 fn test_unbind_keys_for_user() -> Result<()> {
5592 let mut db = new_test_db()?;
5593 db.unbind_keys_for_user(1, false)?;
5594
5595 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5596 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5597 db.unbind_keys_for_user(2, false)?;
5598
Janis Danisevskis18313832021-05-17 13:30:32 -07005599 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5600 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005601
5602 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005603 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005604
5605 Ok(())
5606 }
5607
5608 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005609 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5610 let mut db = new_test_db()?;
5611 let super_key = keystore2_crypto::generate_aes256_key()?;
5612 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5613 let (encrypted_super_key, metadata) =
5614 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5615
5616 let key_name_enc = SuperKeyType {
5617 alias: "test_super_key_1",
5618 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5619 };
5620
5621 let key_name_nonenc = SuperKeyType {
5622 alias: "test_super_key_2",
5623 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5624 };
5625
5626 // Install two super keys.
5627 db.store_super_key(
5628 1,
5629 &key_name_nonenc,
5630 &super_key,
5631 &BlobMetaData::new(),
5632 &KeyMetaData::new(),
5633 )?;
5634 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5635
5636 // Check that both can be found in the database.
5637 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5638 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5639
5640 // Install the same keys for a different user.
5641 db.store_super_key(
5642 2,
5643 &key_name_nonenc,
5644 &super_key,
5645 &BlobMetaData::new(),
5646 &KeyMetaData::new(),
5647 )?;
5648 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5649
5650 // Check that the second pair of keys can be found in the database.
5651 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5652 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5653
5654 // Delete only encrypted keys.
5655 db.unbind_keys_for_user(1, true)?;
5656
5657 // The encrypted superkey should be gone now.
5658 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5659 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5660
5661 // Reinsert the encrypted key.
5662 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5663
5664 // Check that both can be found in the database, again..
5665 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5666 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5667
5668 // Delete all even unencrypted keys.
5669 db.unbind_keys_for_user(1, false)?;
5670
5671 // Both should be gone now.
5672 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5673 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5674
5675 // Check that the second pair of keys was untouched.
5676 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5677 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5678
5679 Ok(())
5680 }
5681
5682 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005683 fn test_store_super_key() -> Result<()> {
5684 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005685 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005686 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005687 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005688 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005689 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005690
5691 let (encrypted_super_key, metadata) =
5692 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005693 db.store_super_key(
5694 1,
5695 &USER_SUPER_KEY,
5696 &encrypted_super_key,
5697 &metadata,
5698 &KeyMetaData::new(),
5699 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005700
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005701 // Check if super key exists.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005702 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005703
Paul Crowley7a658392021-03-18 17:08:20 -07005704 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005705 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5706 USER_SUPER_KEY.algorithm,
5707 key_entry,
5708 &pw,
5709 None,
5710 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005711
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005712 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005713 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005714
Hasini Gunasingheda895552021-01-27 19:34:37 +00005715 Ok(())
5716 }
Seth Moore78c091f2021-04-09 21:38:30 +00005717
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005718 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005719 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005720 MetricsStorage::KEY_ENTRY,
5721 MetricsStorage::KEY_ENTRY_ID_INDEX,
5722 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5723 MetricsStorage::BLOB_ENTRY,
5724 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5725 MetricsStorage::KEY_PARAMETER,
5726 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5727 MetricsStorage::KEY_METADATA,
5728 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5729 MetricsStorage::GRANT,
5730 MetricsStorage::AUTH_TOKEN,
5731 MetricsStorage::BLOB_METADATA,
5732 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005733 ]
5734 }
5735
5736 /// Perform a simple check to ensure that we can query all the storage types
5737 /// that are supported by the DB. Check for reasonable values.
5738 #[test]
5739 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005740 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005741
5742 let mut db = new_test_db()?;
5743
5744 for t in get_valid_statsd_storage_types() {
5745 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005746 // AuthToken can be less than a page since it's in a btree, not sqlite
5747 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005748 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005749 } else {
5750 assert!(stat.size >= PAGE_SIZE);
5751 }
Seth Moore78c091f2021-04-09 21:38:30 +00005752 assert!(stat.size >= stat.unused_size);
5753 }
5754
5755 Ok(())
5756 }
5757
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005758 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005759 get_valid_statsd_storage_types()
5760 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005761 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005762 .collect()
5763 }
5764
5765 fn assert_storage_increased(
5766 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005767 increased_storage_types: Vec<MetricsStorage>,
5768 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005769 ) {
5770 for storage in increased_storage_types {
5771 // Verify the expected storage increased.
5772 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005773 let storage = storage;
5774 let old = &baseline[&storage.0];
5775 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005776 assert!(
5777 new.unused_size <= old.unused_size,
5778 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005779 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005780 new.unused_size,
5781 old.unused_size
5782 );
5783
5784 // Update the baseline with the new value so that it succeeds in the
5785 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005786 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005787 }
5788
5789 // Get an updated map of the storage and verify there were no unexpected changes.
5790 let updated_stats = get_storage_stats_map(db);
5791 assert_eq!(updated_stats.len(), baseline.len());
5792
5793 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005794 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005795 let mut s = String::new();
5796 for &k in map.keys() {
5797 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5798 .expect("string concat failed");
5799 }
5800 s
5801 };
5802
5803 assert!(
5804 updated_stats[&k].size == baseline[&k].size
5805 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5806 "updated_stats:\n{}\nbaseline:\n{}",
5807 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005808 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005809 );
5810 }
5811 }
5812
5813 #[test]
5814 fn test_verify_key_table_size_reporting() -> Result<()> {
5815 let mut db = new_test_db()?;
5816 let mut working_stats = get_storage_stats_map(&mut db);
5817
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005818 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005819 assert_storage_increased(
5820 &mut db,
5821 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005822 MetricsStorage::KEY_ENTRY,
5823 MetricsStorage::KEY_ENTRY_ID_INDEX,
5824 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005825 ],
5826 &mut working_stats,
5827 );
5828
5829 let mut blob_metadata = BlobMetaData::new();
5830 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5831 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5832 assert_storage_increased(
5833 &mut db,
5834 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005835 MetricsStorage::BLOB_ENTRY,
5836 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5837 MetricsStorage::BLOB_METADATA,
5838 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005839 ],
5840 &mut working_stats,
5841 );
5842
5843 let params = make_test_params(None);
5844 db.insert_keyparameter(&key_id, &params)?;
5845 assert_storage_increased(
5846 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005847 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005848 &mut working_stats,
5849 );
5850
5851 let mut metadata = KeyMetaData::new();
5852 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5853 db.insert_key_metadata(&key_id, &metadata)?;
5854 assert_storage_increased(
5855 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005856 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005857 &mut working_stats,
5858 );
5859
5860 let mut sum = 0;
5861 for stat in working_stats.values() {
5862 sum += stat.size;
5863 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005864 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005865 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5866
5867 Ok(())
5868 }
5869
5870 #[test]
5871 fn test_verify_auth_table_size_reporting() -> Result<()> {
5872 let mut db = new_test_db()?;
5873 let mut working_stats = get_storage_stats_map(&mut db);
5874 db.insert_auth_token(&HardwareAuthToken {
5875 challenge: 123,
5876 userId: 456,
5877 authenticatorId: 789,
5878 authenticatorType: kmhw_authenticator_type::ANY,
5879 timestamp: Timestamp { milliSeconds: 10 },
5880 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005881 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005882 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005883 Ok(())
5884 }
5885
5886 #[test]
5887 fn test_verify_grant_table_size_reporting() -> Result<()> {
5888 const OWNER: i64 = 1;
5889 let mut db = new_test_db()?;
5890 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5891
5892 let mut working_stats = get_storage_stats_map(&mut db);
5893 db.grant(
5894 &KeyDescriptor {
5895 domain: Domain::APP,
5896 nspace: 0,
5897 alias: Some(TEST_ALIAS.to_string()),
5898 blob: None,
5899 },
5900 OWNER as u32,
5901 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005902 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005903 |_, _| Ok(()),
5904 )?;
5905
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005906 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005907
5908 Ok(())
5909 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005910
5911 #[test]
5912 fn find_auth_token_entry_returns_latest() -> Result<()> {
5913 let mut db = new_test_db()?;
5914 db.insert_auth_token(&HardwareAuthToken {
5915 challenge: 123,
5916 userId: 456,
5917 authenticatorId: 789,
5918 authenticatorType: kmhw_authenticator_type::ANY,
5919 timestamp: Timestamp { milliSeconds: 10 },
5920 mac: b"mac0".to_vec(),
5921 });
5922 std::thread::sleep(std::time::Duration::from_millis(1));
5923 db.insert_auth_token(&HardwareAuthToken {
5924 challenge: 123,
5925 userId: 457,
5926 authenticatorId: 789,
5927 authenticatorType: kmhw_authenticator_type::ANY,
5928 timestamp: Timestamp { milliSeconds: 12 },
5929 mac: b"mac1".to_vec(),
5930 });
5931 std::thread::sleep(std::time::Duration::from_millis(1));
5932 db.insert_auth_token(&HardwareAuthToken {
5933 challenge: 123,
5934 userId: 458,
5935 authenticatorId: 789,
5936 authenticatorType: kmhw_authenticator_type::ANY,
5937 timestamp: Timestamp { milliSeconds: 3 },
5938 mac: b"mac2".to_vec(),
5939 });
5940 // All three entries are in the database
5941 assert_eq!(db.perboot.auth_tokens_len(), 3);
5942 // It selected the most recent timestamp
5943 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5944 Ok(())
5945 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005946
5947 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005948 fn test_load_key_descriptor() -> Result<()> {
5949 let mut db = new_test_db()?;
5950 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5951
5952 let key = db.load_key_descriptor(key_id)?.unwrap();
5953
5954 assert_eq!(key.domain, Domain::APP);
5955 assert_eq!(key.nspace, 1);
5956 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5957
5958 // No such id
5959 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5960 Ok(())
5961 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005962}