blob: c9c28f6d7349e491a3b5188fc4b6719de4ae85dc [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)
Charisee03e00842023-01-25 01:41:23 +0000833 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 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);
Seth Moored7ad8562023-01-23 09:28:56 -08001862 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS_TRANSIENT_ERROR))
1863 .context("Out of keys.");
Max Bires01f8af22021-03-02 23:24:50 -08001864 } else if result > 1 {
1865 return Err(KsError::sys())
1866 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001867 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001868 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001869 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001870 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001871 }
1872
1873 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1874 /// provisioning server, or the maximum number available if there are not num_keys number of
1875 /// entries in the table.
1876 pub fn fetch_unsigned_attestation_keys(
1877 &mut self,
1878 num_keys: i32,
1879 km_uuid: &Uuid,
1880 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001881 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1882
Max Bires2b2e6562020-09-22 11:22:36 -07001883 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1884 let mut stmt = tx
1885 .prepare(
1886 "SELECT data
1887 FROM persistent.keymetadata
1888 WHERE tag = ? AND keyentryid IN
1889 (SELECT id
1890 FROM persistent.keyentry
1891 WHERE
1892 alias IS NULL AND
1893 domain IS NULL AND
1894 namespace IS NULL AND
1895 key_type = ? AND
1896 km_uuid = ?
1897 LIMIT ?);",
1898 )
1899 .context("Failed to prepare statement")?;
1900 let rows = stmt
1901 .query_map(
1902 params![
1903 KeyMetaData::AttestationMacedPublicKey,
1904 KeyType::Attestation,
1905 km_uuid,
1906 num_keys
1907 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001908 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001909 )?
1910 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1911 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001912 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001913 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001914 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001915 }
1916
1917 /// Removes any keys that have expired as of the current time. Returns the number of keys
1918 /// marked unreferenced that are bound to be garbage collected.
1919 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001920 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1921
Max Bires2b2e6562020-09-22 11:22:36 -07001922 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1923 let mut stmt = tx
1924 .prepare(
1925 "SELECT keyentryid, data
1926 FROM persistent.keymetadata
1927 WHERE tag = ? AND keyentryid IN
1928 (SELECT id
1929 FROM persistent.keyentry
1930 WHERE key_type = ?);",
1931 )
1932 .context("Failed to prepare query")?;
1933 let key_ids_to_check = stmt
1934 .query_map(
1935 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1936 |row| Ok((row.get(0)?, row.get(1)?)),
1937 )?
1938 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1939 .context("Failed to get date metadata")?;
Max Birescd7f7412022-02-11 13:47:36 -08001940 // Calculate curr_time with a discount factor to avoid a key that's milliseconds away
1941 // from expiration dodging this delete call.
Max Bires2b2e6562020-09-22 11:22:36 -07001942 let curr_time = DateTime::from_millis_epoch(
Max Birescd7f7412022-02-11 13:47:36 -08001943 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
1944 + EXPIRATION_BUFFER_MS,
Max Bires2b2e6562020-09-22 11:22:36 -07001945 );
1946 let mut num_deleted = 0;
1947 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 -07001948 if Self::mark_unreferenced(tx, id)? {
Max Bires2b2e6562020-09-22 11:22:36 -07001949 num_deleted += 1;
1950 }
1951 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001952 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001953 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001954 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07001955 }
1956
Max Bires60d7ed12021-03-05 15:59:22 -08001957 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1958 /// they are in. This is useful primarily as a testing mechanism.
1959 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001960 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1961
Max Bires60d7ed12021-03-05 15:59:22 -08001962 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1963 let mut stmt = tx
1964 .prepare(
1965 "SELECT id FROM persistent.keyentry
1966 WHERE key_type IS ?;",
1967 )
1968 .context("Failed to prepare statement")?;
1969 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001970 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001971 .collect::<rusqlite::Result<Vec<i64>>>()
1972 .context("Failed to execute statement")?;
1973 let num_deleted = keys_to_delete
1974 .iter()
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001975 .map(|id| Self::mark_unreferenced(tx, *id))
Max Bires60d7ed12021-03-05 15:59:22 -08001976 .collect::<Result<Vec<bool>>>()
1977 .context("Failed to execute mark_unreferenced on a keyid")?
1978 .into_iter()
1979 .filter(|result| *result)
1980 .count() as i64;
1981 Ok(num_deleted).do_gc(num_deleted != 0)
1982 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001983 .context(ks_err!())
Max Bires60d7ed12021-03-05 15:59:22 -08001984 }
1985
Max Bires2b2e6562020-09-22 11:22:36 -07001986 /// Counts the number of keys that will expire by the provided epoch date and the number of
1987 /// keys not currently assigned to a domain.
1988 pub fn get_attestation_pool_status(
1989 &mut self,
1990 date: i64,
1991 km_uuid: &Uuid,
1992 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001993 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1994
Max Bires2b2e6562020-09-22 11:22:36 -07001995 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1996 let mut stmt = tx.prepare(
1997 "SELECT data
1998 FROM persistent.keymetadata
1999 WHERE tag = ? AND keyentryid IN
2000 (SELECT id
2001 FROM persistent.keyentry
2002 WHERE alias IS NOT NULL
2003 AND key_type = ?
2004 AND km_uuid = ?
2005 AND state = ?);",
2006 )?;
2007 let times = stmt
2008 .query_map(
2009 params![
2010 KeyMetaData::AttestationExpirationDate,
2011 KeyType::Attestation,
2012 km_uuid,
2013 KeyLifeCycle::Live
2014 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002015 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002016 )?
2017 .collect::<rusqlite::Result<Vec<DateTime>>>()
2018 .context("Failed to execute metadata statement")?;
2019 let expiring =
2020 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2021 as i32;
2022 stmt = tx.prepare(
2023 "SELECT alias, domain
2024 FROM persistent.keyentry
2025 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2026 )?;
2027 let rows = stmt
2028 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2029 Ok((row.get(0)?, row.get(1)?))
2030 })?
2031 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2032 .context("Failed to execute keyentry statement")?;
2033 let mut unassigned = 0i32;
2034 let mut attested = 0i32;
2035 let total = rows.len() as i32;
2036 for (alias, domain) in rows {
2037 match (alias, domain) {
2038 (Some(_alias), None) => {
2039 attested += 1;
2040 unassigned += 1;
2041 }
2042 (Some(_alias), Some(_domain)) => {
2043 attested += 1;
2044 }
2045 _ => {}
2046 }
2047 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002048 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002049 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002050 .context(ks_err!())
Max Bires2b2e6562020-09-22 11:22:36 -07002051 }
2052
Max Bires55620ff2022-02-11 13:34:15 -08002053 fn query_kid_for_attestation_key_and_cert_chain(
2054 &self,
2055 tx: &Transaction,
2056 domain: Domain,
2057 namespace: i64,
2058 km_uuid: &Uuid,
2059 ) -> Result<Option<i64>> {
2060 let mut stmt = tx.prepare(
2061 "SELECT id
2062 FROM persistent.keyentry
2063 WHERE key_type = ?
2064 AND domain = ?
2065 AND namespace = ?
2066 AND state = ?
2067 AND km_uuid = ?;",
2068 )?;
2069 let rows = stmt
2070 .query_map(
2071 params![
2072 KeyType::Attestation,
2073 domain.0 as u32,
2074 namespace,
2075 KeyLifeCycle::Live,
2076 km_uuid
2077 ],
2078 |row| row.get(0),
2079 )?
2080 .collect::<rusqlite::Result<Vec<i64>>>()
2081 .context("query failed.")?;
2082 if rows.is_empty() {
2083 return Ok(None);
2084 }
2085 Ok(Some(rows[0]))
2086 }
2087
Max Bires2b2e6562020-09-22 11:22:36 -07002088 /// Fetches the private key and corresponding certificate chain assigned to a
2089 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2090 /// not assigned, or one CertificateChain.
2091 pub fn retrieve_attestation_key_and_cert_chain(
2092 &mut self,
2093 domain: Domain,
2094 namespace: i64,
2095 km_uuid: &Uuid,
Max Bires55620ff2022-02-11 13:34:15 -08002096 ) -> Result<Option<(KeyIdGuard, CertificateChain)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002097 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2098
Max Bires2b2e6562020-09-22 11:22:36 -07002099 match domain {
2100 Domain::APP | Domain::SELINUX => {}
2101 _ => {
2102 return Err(KsError::sys())
2103 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2104 }
2105 }
Max Bires55620ff2022-02-11 13:34:15 -08002106
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002107 self.delete_expired_attestation_keys()
2108 .context(ks_err!("Failed to prune expired attestation keys",))?;
2109 let tx = self
2110 .conn
2111 .unchecked_transaction()
2112 .context(ks_err!("Failed to initialize transaction."))?;
Chariseea1e1c482022-02-26 01:26:35 +00002113 let key_id: i64 = match self
2114 .query_kid_for_attestation_key_and_cert_chain(&tx, domain, namespace, km_uuid)?
2115 {
Max Bires55620ff2022-02-11 13:34:15 -08002116 None => return Ok(None),
Chariseea1e1c482022-02-26 01:26:35 +00002117 Some(kid) => kid,
2118 };
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002119 tx.commit().context(ks_err!("Failed to commit keyid query"))?;
Max Bires55620ff2022-02-11 13:34:15 -08002120 let key_id_guard = KEY_ID_LOCK.get(key_id);
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002121 let tx = self
2122 .conn
2123 .unchecked_transaction()
2124 .context(ks_err!("Failed to initialize transaction."))?;
Max Bires55620ff2022-02-11 13:34:15 -08002125 let mut stmt = tx.prepare(
2126 "SELECT subcomponent_type, blob
2127 FROM persistent.blobentry
2128 WHERE keyentryid = ?;",
2129 )?;
2130 let rows = stmt
2131 .query_map(params![key_id_guard.id()], |row| Ok((row.get(0)?, row.get(1)?)))?
2132 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
2133 .context("query failed.")?;
2134 if rows.is_empty() {
2135 return Ok(None);
2136 } else if rows.len() != 3 {
2137 return Err(KsError::sys()).context(format!(
2138 concat!(
2139 "Expected to get a single attestation",
2140 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2141 ),
2142 rows.len()
2143 ));
2144 }
2145 let mut km_blob: Vec<u8> = Vec::new();
2146 let mut cert_chain_blob: Vec<u8> = Vec::new();
2147 let mut batch_cert_blob: Vec<u8> = Vec::new();
2148 for row in rows {
2149 let sub_type: SubComponentType = row.0;
2150 match sub_type {
2151 SubComponentType::KEY_BLOB => {
2152 km_blob = row.1;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002153 }
Max Bires55620ff2022-02-11 13:34:15 -08002154 SubComponentType::CERT_CHAIN => {
2155 cert_chain_blob = row.1;
2156 }
2157 SubComponentType::CERT => {
2158 batch_cert_blob = row.1;
2159 }
2160 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002161 }
Max Bires55620ff2022-02-11 13:34:15 -08002162 }
2163 Ok(Some((
2164 key_id_guard,
2165 CertificateChain {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002166 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002167 batch_cert: batch_cert_blob,
2168 cert_chain: cert_chain_blob,
Max Bires55620ff2022-02-11 13:34:15 -08002169 },
2170 )))
Max Bires2b2e6562020-09-22 11:22:36 -07002171 }
2172
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002173 /// Updates the alias column of the given key id `newid` with the given alias,
2174 /// and atomically, removes the alias, domain, and namespace from another row
2175 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002176 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2177 /// collector.
2178 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002179 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002180 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002181 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002182 domain: &Domain,
2183 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002184 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002185 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002186 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002187 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002188 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002189 return Err(KsError::sys())
2190 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002191 }
2192 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002193 let updated = tx
2194 .execute(
2195 "UPDATE persistent.keyentry
2196 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002197 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2198 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002199 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002200 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002201 let result = tx
2202 .execute(
2203 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002204 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002205 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002206 params![
2207 alias,
2208 KeyLifeCycle::Live,
2209 newid.0,
2210 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002211 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002212 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002213 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002214 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002215 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002216 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002217 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002218 return Err(KsError::sys()).context(ks_err!(
2219 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002220 result
2221 ));
2222 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002223 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002224 }
2225
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002226 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2227 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2228 pub fn migrate_key_namespace(
2229 &mut self,
2230 key_id_guard: KeyIdGuard,
2231 destination: &KeyDescriptor,
2232 caller_uid: u32,
2233 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2234 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002235 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2236
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002237 let destination = match destination.domain {
2238 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2239 Domain::SELINUX => (*destination).clone(),
2240 domain => {
2241 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2242 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2243 }
2244 };
2245
2246 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002247 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002248
2249 let alias = destination
2250 .alias
2251 .as_ref()
2252 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002253 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002254
2255 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2256 // Query the destination location. If there is a key, the migration request fails.
2257 if tx
2258 .query_row(
2259 "SELECT id FROM persistent.keyentry
2260 WHERE alias = ? AND domain = ? AND namespace = ?;",
2261 params![alias, destination.domain.0, destination.nspace],
2262 |_| Ok(()),
2263 )
2264 .optional()
2265 .context("Failed to query destination.")?
2266 .is_some()
2267 {
2268 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2269 .context("Target already exists.");
2270 }
2271
2272 let updated = tx
2273 .execute(
2274 "UPDATE persistent.keyentry
2275 SET alias = ?, domain = ?, namespace = ?
2276 WHERE id = ?;",
2277 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2278 )
2279 .context("Failed to update key entry.")?;
2280
2281 if updated != 1 {
2282 return Err(KsError::sys())
2283 .context(format!("Update succeeded, but {} rows were updated.", updated));
2284 }
2285 Ok(()).no_gc()
2286 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002287 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002288 }
2289
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002290 /// Store a new key in a single transaction.
2291 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2292 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002293 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2294 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07002295 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002296 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002297 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002298 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002299 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002300 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002301 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08002302 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002303 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002304 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002305 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002306 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2307
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002308 let (alias, domain, namespace) = match key {
2309 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2310 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2311 (alias, key.domain, nspace)
2312 }
2313 _ => {
2314 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002315 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002316 }
2317 };
2318 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002319 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002320 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002321 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
2322
2323 // In some occasions the key blob is already upgraded during the import.
2324 // In order to make sure it gets properly deleted it is inserted into the
2325 // database here and then immediately replaced by the superseding blob.
2326 // The garbage collector will then subject the blob to deleteKey of the
2327 // KM back end to permanently invalidate the key.
2328 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
2329 Self::set_blob_internal(
2330 tx,
2331 key_id.id(),
2332 SubComponentType::KEY_BLOB,
2333 Some(blob),
2334 Some(blob_metadata),
2335 )
2336 .context("Trying to insert superseded key blob.")?;
2337 true
2338 } else {
2339 false
2340 };
2341
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002342 Self::set_blob_internal(
2343 tx,
2344 key_id.id(),
2345 SubComponentType::KEY_BLOB,
2346 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002347 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002348 )
2349 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002350 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002351 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002352 .context("Trying to insert the certificate.")?;
2353 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002354 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002355 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002356 tx,
2357 key_id.id(),
2358 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002359 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002360 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002361 )
2362 .context("Trying to insert the certificate chain.")?;
2363 }
2364 Self::insert_keyparameter_internal(tx, &key_id, params)
2365 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002366 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002367 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002368 .context("Trying to rebind alias.")?
2369 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002370 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002371 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002372 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002373 }
2374
Janis Danisevskis377d1002021-01-27 19:07:48 -08002375 /// Store a new certificate
2376 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2377 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002378 pub fn store_new_certificate(
2379 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002380 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002381 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002382 cert: &[u8],
2383 km_uuid: &Uuid,
2384 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002385 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2386
Janis Danisevskis377d1002021-01-27 19:07:48 -08002387 let (alias, domain, namespace) = match key {
2388 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2389 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2390 (alias, key.domain, nspace)
2391 }
2392 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002393 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2394 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08002395 }
2396 };
2397 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002398 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002399 .context("Trying to create new key entry.")?;
2400
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002401 Self::set_blob_internal(
2402 tx,
2403 key_id.id(),
2404 SubComponentType::CERT_CHAIN,
2405 Some(cert),
2406 None,
2407 )
2408 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002409
2410 let mut metadata = KeyMetaData::new();
2411 metadata.add(KeyMetaEntry::CreationDate(
2412 DateTime::now().context("Trying to make creation time.")?,
2413 ));
2414
2415 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2416
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002417 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002418 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002419 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002420 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002421 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08002422 }
2423
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002424 // Helper function loading the key_id given the key descriptor
2425 // tuple comprising domain, namespace, and alias.
2426 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002427 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002428 let alias = key
2429 .alias
2430 .as_ref()
2431 .map_or_else(|| Err(KsError::sys()), Ok)
2432 .context("In load_key_entry_id: Alias must be specified.")?;
2433 let mut stmt = tx
2434 .prepare(
2435 "SELECT id FROM persistent.keyentry
2436 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002437 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002438 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002439 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002440 AND alias = ?
2441 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002442 )
2443 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2444 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002445 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002446 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002447 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002448 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002449 .get(0)
2450 .context("Failed to unpack id.")
2451 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002452 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002453 }
2454
2455 /// This helper function completes the access tuple of a key, which is required
2456 /// to perform access control. The strategy depends on the `domain` field in the
2457 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002458 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002459 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002460 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002461 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002462 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002463 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002464 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002465 /// `namespace`.
2466 /// In each case the information returned is sufficient to perform the access
2467 /// check and the key id can be used to load further key artifacts.
2468 fn load_access_tuple(
2469 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002470 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002471 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002472 caller_uid: u32,
2473 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2474 match key.domain {
2475 // Domain App or SELinux. In this case we load the key_id from
2476 // the keyentry database for further loading of key components.
2477 // We already have the full access tuple to perform access control.
2478 // The only distinction is that we use the caller_uid instead
2479 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002480 // Domain::APP.
2481 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002482 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002483 if access_key.domain == Domain::APP {
2484 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002485 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002486 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002487 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002488
2489 Ok((key_id, access_key, None))
2490 }
2491
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002492 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002493 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002494 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002495 let mut stmt = tx
2496 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002497 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002498 WHERE grantee = ? AND id = ? AND
2499 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002500 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002501 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002502 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002503 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002504 .context("Domain:Grant: query failed.")?;
2505 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002506 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002507 let r =
2508 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002509 Ok((
2510 r.get(0).context("Failed to unpack key_id.")?,
2511 r.get(1).context("Failed to unpack access_vector.")?,
2512 ))
2513 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002514 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002515 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002516 }
2517
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002518 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002519 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002520 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002521 let (domain, namespace): (Domain, i64) = {
2522 let mut stmt = tx
2523 .prepare(
2524 "SELECT domain, namespace FROM persistent.keyentry
2525 WHERE
2526 id = ?
2527 AND state = ?;",
2528 )
2529 .context("Domain::KEY_ID: prepare statement failed")?;
2530 let mut rows = stmt
2531 .query(params![key.nspace, KeyLifeCycle::Live])
2532 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002533 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002534 let r =
2535 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002536 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002537 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002538 r.get(1).context("Failed to unpack namespace.")?,
2539 ))
2540 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002541 .context("Domain::KEY_ID.")?
2542 };
2543
2544 // We may use a key by id after loading it by grant.
2545 // In this case we have to check if the caller has a grant for this particular
2546 // key. We can skip this if we already know that the caller is the owner.
2547 // But we cannot know this if domain is anything but App. E.g. in the case
2548 // of Domain::SELINUX we have to speculatively check for grants because we have to
2549 // consult the SEPolicy before we know if the caller is the owner.
2550 let access_vector: Option<KeyPermSet> =
2551 if domain != Domain::APP || namespace != caller_uid as i64 {
2552 let access_vector: Option<i32> = tx
2553 .query_row(
2554 "SELECT access_vector FROM persistent.grant
2555 WHERE grantee = ? AND keyentryid = ?;",
2556 params![caller_uid as i64, key.nspace],
2557 |row| row.get(0),
2558 )
2559 .optional()
2560 .context("Domain::KEY_ID: query grant failed.")?;
2561 access_vector.map(|p| p.into())
2562 } else {
2563 None
2564 };
2565
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002566 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002567 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002568 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002569 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002570
Janis Danisevskis45760022021-01-19 16:34:10 -08002571 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002572 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002573 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002574 }
2575 }
2576
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002577 fn load_blob_components(
2578 key_id: i64,
2579 load_bits: KeyEntryLoadBits,
2580 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002581 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002582 let mut stmt = tx
2583 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002584 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002585 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2586 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002587 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002588
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002589 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002590
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002591 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002592 let mut cert_blob: Option<Vec<u8>> = None;
2593 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002594 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002595 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002596 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002597 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002598 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002599 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2600 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002601 key_blob = Some((
2602 row.get(0).context("Failed to extract key blob id.")?,
2603 row.get(2).context("Failed to extract key blob.")?,
2604 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002605 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002606 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002607 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002608 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002609 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002610 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002611 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002612 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002613 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002614 (SubComponentType::CERT, _, _)
2615 | (SubComponentType::CERT_CHAIN, _, _)
2616 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002617 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2618 }
2619 Ok(())
2620 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002621 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002622
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002623 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2624 Ok(Some((
2625 blob,
2626 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002627 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002628 )))
2629 })?;
2630
2631 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002632 }
2633
2634 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2635 let mut stmt = tx
2636 .prepare(
2637 "SELECT tag, data, security_level from persistent.keyparameter
2638 WHERE keyentryid = ?;",
2639 )
2640 .context("In load_key_parameters: prepare statement failed.")?;
2641
2642 let mut parameters: Vec<KeyParameter> = Vec::new();
2643
2644 let mut rows =
2645 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002646 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002647 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2648 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002649 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002650 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002651 .context("Failed to read KeyParameter.")?,
2652 );
2653 Ok(())
2654 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002655 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002656
2657 Ok(parameters)
2658 }
2659
Qi Wub9433b52020-12-01 14:52:46 +08002660 /// Decrements the usage count of a limited use key. This function first checks whether the
2661 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2662 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2663 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002664 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002665 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2666
Qi Wub9433b52020-12-01 14:52:46 +08002667 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2668 let limit: Option<i32> = tx
2669 .query_row(
2670 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2671 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2672 |row| row.get(0),
2673 )
2674 .optional()
2675 .context("Trying to load usage count")?;
2676
2677 let limit = limit
2678 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2679 .context("The Key no longer exists. Key is exhausted.")?;
2680
2681 tx.execute(
2682 "UPDATE persistent.keyparameter
2683 SET data = data - 1
2684 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2685 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2686 )
2687 .context("Failed to update key usage count.")?;
2688
2689 match limit {
2690 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002691 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002692 .context("Trying to mark limited use key for deletion."),
2693 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002694 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002695 }
2696 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002697 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002698 }
2699
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002700 /// Load a key entry by the given key descriptor.
2701 /// It uses the `check_permission` callback to verify if the access is allowed
2702 /// given the key access tuple read from the database using `load_access_tuple`.
2703 /// With `load_bits` the caller may specify which blobs shall be loaded from
2704 /// the blob database.
2705 pub fn load_key_entry(
2706 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002707 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002708 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002709 load_bits: KeyEntryLoadBits,
2710 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002711 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2712 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002713 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2714
Janis Danisevskis66784c42021-01-27 08:40:25 -08002715 loop {
2716 match self.load_key_entry_internal(
2717 key,
2718 key_type,
2719 load_bits,
2720 caller_uid,
2721 &check_permission,
2722 ) {
2723 Ok(result) => break Ok(result),
2724 Err(e) => {
2725 if Self::is_locked_error(&e) {
2726 std::thread::sleep(std::time::Duration::from_micros(500));
2727 continue;
2728 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002729 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002730 }
2731 }
2732 }
2733 }
2734 }
2735
2736 fn load_key_entry_internal(
2737 &mut self,
2738 key: &KeyDescriptor,
2739 key_type: KeyType,
2740 load_bits: KeyEntryLoadBits,
2741 caller_uid: u32,
2742 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002743 ) -> Result<(KeyIdGuard, KeyEntry)> {
2744 // KEY ID LOCK 1/2
2745 // If we got a key descriptor with a key id we can get the lock right away.
2746 // Otherwise we have to defer it until we know the key id.
2747 let key_id_guard = match key.domain {
2748 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2749 _ => None,
2750 };
2751
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002752 let tx = self
2753 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002754 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002755 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002756
2757 // Load the key_id and complete the access control tuple.
2758 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002759 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002760
2761 // Perform access control. It is vital that we return here if the permission is denied.
2762 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002763 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002764
Janis Danisevskisaec14592020-11-12 09:41:49 -08002765 // KEY ID LOCK 2/2
2766 // If we did not get a key id lock by now, it was because we got a key descriptor
2767 // without a key id. At this point we got the key id, so we can try and get a lock.
2768 // However, we cannot block here, because we are in the middle of the transaction.
2769 // So first we try to get the lock non blocking. If that fails, we roll back the
2770 // transaction and block until we get the lock. After we successfully got the lock,
2771 // we start a new transaction and load the access tuple again.
2772 //
2773 // We don't need to perform access control again, because we already established
2774 // that the caller had access to the given key. But we need to make sure that the
2775 // key id still exists. So we have to load the key entry by key id this time.
2776 let (key_id_guard, tx) = match key_id_guard {
2777 None => match KEY_ID_LOCK.try_get(key_id) {
2778 None => {
2779 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002780 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002781
Janis Danisevskisaec14592020-11-12 09:41:49 -08002782 // Block until we have a key id lock.
2783 let key_id_guard = KEY_ID_LOCK.get(key_id);
2784
2785 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002786 let tx = self
2787 .conn
2788 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002789 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002790
2791 Self::load_access_tuple(
2792 &tx,
2793 // This time we have to load the key by the retrieved key id, because the
2794 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002795 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002796 domain: Domain::KEY_ID,
2797 nspace: key_id,
2798 ..Default::default()
2799 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002800 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002801 caller_uid,
2802 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002803 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002804 (key_id_guard, tx)
2805 }
2806 Some(l) => (l, tx),
2807 },
2808 Some(key_id_guard) => (key_id_guard, tx),
2809 };
2810
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002811 let key_entry =
2812 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002813
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002814 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002815
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002816 Ok((key_id_guard, key_entry))
2817 }
2818
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002819 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002820 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002821 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2822 .context("Trying to delete keyentry.")?;
2823 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2824 .context("Trying to delete keymetadata.")?;
2825 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2826 .context("Trying to delete keyparameters.")?;
2827 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2828 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002829 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002830 }
2831
2832 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002833 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002834 pub fn unbind_key(
2835 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002836 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002837 key_type: KeyType,
2838 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002839 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002840 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002841 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2842
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002843 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2844 let (key_id, access_key_descriptor, access_vector) =
2845 Self::load_access_tuple(tx, key, key_type, caller_uid)
2846 .context("Trying to get access tuple.")?;
2847
2848 // Perform access control. It is vital that we return here if the permission is denied.
2849 // So do not touch that '?' at the end.
2850 check_permission(&access_key_descriptor, access_vector)
2851 .context("While checking permission.")?;
2852
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002853 Self::mark_unreferenced(tx, key_id)
2854 .map(|need_gc| (need_gc, ()))
2855 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002856 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002857 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002858 }
2859
Max Bires8e93d2b2021-01-14 13:17:59 -08002860 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2861 tx.query_row(
2862 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2863 params![key_id],
2864 |row| row.get(0),
2865 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002866 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002867 }
2868
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002869 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2870 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2871 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002872 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2873
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002874 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002875 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002876 }
2877 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2878 tx.execute(
2879 "DELETE FROM persistent.keymetadata
2880 WHERE keyentryid IN (
2881 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002882 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002883 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002884 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002885 )
2886 .context("Trying to delete keymetadata.")?;
2887 tx.execute(
2888 "DELETE FROM persistent.keyparameter
2889 WHERE keyentryid IN (
2890 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002891 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002892 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002893 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002894 )
2895 .context("Trying to delete keyparameters.")?;
2896 tx.execute(
2897 "DELETE FROM persistent.grant
2898 WHERE keyentryid IN (
2899 SELECT id FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002900 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?)
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002901 );",
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002902 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002903 )
2904 .context("Trying to delete grants.")?;
2905 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002906 "DELETE FROM persistent.keyentry
Vikram Gaur1a98f9c2022-05-24 16:40:43 +00002907 WHERE domain = ? AND namespace = ? AND (key_type = ? OR key_type = ?);",
2908 params![domain.0, namespace, KeyType::Client, KeyType::Attestation],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002909 )
2910 .context("Trying to delete keyentry.")?;
2911 Ok(()).need_gc()
2912 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002913 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002914 }
2915
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002916 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2917 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2918 {
2919 tx.execute(
2920 "DELETE FROM persistent.keymetadata
2921 WHERE keyentryid IN (
2922 SELECT id FROM persistent.keyentry
2923 WHERE state = ?
2924 );",
2925 params![KeyLifeCycle::Unreferenced],
2926 )
2927 .context("Trying to delete keymetadata.")?;
2928 tx.execute(
2929 "DELETE FROM persistent.keyparameter
2930 WHERE keyentryid IN (
2931 SELECT id FROM persistent.keyentry
2932 WHERE state = ?
2933 );",
2934 params![KeyLifeCycle::Unreferenced],
2935 )
2936 .context("Trying to delete keyparameters.")?;
2937 tx.execute(
2938 "DELETE FROM persistent.grant
2939 WHERE keyentryid IN (
2940 SELECT id FROM persistent.keyentry
2941 WHERE state = ?
2942 );",
2943 params![KeyLifeCycle::Unreferenced],
2944 )
2945 .context("Trying to delete grants.")?;
2946 tx.execute(
2947 "DELETE FROM persistent.keyentry
2948 WHERE state = ?;",
2949 params![KeyLifeCycle::Unreferenced],
2950 )
2951 .context("Trying to delete keyentry.")?;
2952 Result::<()>::Ok(())
2953 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002954 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002955 }
2956
Hasini Gunasingheda895552021-01-27 19:34:37 +00002957 /// Delete the keys created on behalf of the user, denoted by the user id.
2958 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2959 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2960 /// The caller of this function should notify the gc if the returned value is true.
2961 pub fn unbind_keys_for_user(
2962 &mut self,
2963 user_id: u32,
2964 keep_non_super_encrypted_keys: bool,
2965 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002966 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2967
Hasini Gunasingheda895552021-01-27 19:34:37 +00002968 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2969 let mut stmt = tx
2970 .prepare(&format!(
2971 "SELECT id from persistent.keyentry
2972 WHERE (
2973 key_type = ?
2974 AND domain = ?
2975 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2976 AND state = ?
2977 ) OR (
2978 key_type = ?
2979 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002980 AND state = ?
2981 );",
2982 aid_user_offset = AID_USER_OFFSET
2983 ))
2984 .context(concat!(
2985 "In unbind_keys_for_user. ",
2986 "Failed to prepare the query to find the keys created by apps."
2987 ))?;
2988
2989 let mut rows = stmt
2990 .query(params![
2991 // WHERE client key:
2992 KeyType::Client,
2993 Domain::APP.0 as u32,
2994 user_id,
2995 KeyLifeCycle::Live,
2996 // OR super key:
2997 KeyType::Super,
2998 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002999 KeyLifeCycle::Live
3000 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003001 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00003002
3003 let mut key_ids: Vec<i64> = Vec::new();
3004 db_utils::with_rows_extract_all(&mut rows, |row| {
3005 key_ids
3006 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
3007 Ok(())
3008 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003009 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00003010
3011 let mut notify_gc = false;
3012 for key_id in key_ids {
3013 if keep_non_super_encrypted_keys {
3014 // Load metadata and filter out non-super-encrypted keys.
3015 if let (_, Some((_, blob_metadata)), _, _) =
3016 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003017 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00003018 {
3019 if blob_metadata.encrypted_by().is_none() {
3020 continue;
3021 }
3022 }
3023 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003024 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00003025 .context("In unbind_keys_for_user.")?
3026 || notify_gc;
3027 }
3028 Ok(()).do_gc(notify_gc)
3029 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003030 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00003031 }
3032
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003033 fn load_key_components(
3034 tx: &Transaction,
3035 load_bits: KeyEntryLoadBits,
3036 key_id: i64,
3037 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003038 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003039
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003040 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003041 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003042
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003043 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08003044 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003045
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003046 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08003047 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003048
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003049 Ok(KeyEntry {
3050 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003051 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003052 cert: cert_blob,
3053 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003054 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003055 parameters,
3056 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003057 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003058 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003059 }
3060
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003061 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3062 /// The key descriptors will have the domain, nspace, and alias field set.
3063 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07003064 pub fn list(
3065 &mut self,
3066 domain: Domain,
3067 namespace: i64,
3068 key_type: KeyType,
3069 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003070 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3071
Janis Danisevskis66784c42021-01-27 08:40:25 -08003072 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3073 let mut stmt = tx
3074 .prepare(
3075 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07003076 WHERE domain = ?
3077 AND namespace = ?
3078 AND alias IS NOT NULL
3079 AND state = ?
3080 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003081 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003082 .context(ks_err!("Failed to prepare."))?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003083
Janis Danisevskis66784c42021-01-27 08:40:25 -08003084 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003085 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003086 .context(ks_err!("Failed to query."))?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003087
Janis Danisevskis66784c42021-01-27 08:40:25 -08003088 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3089 db_utils::with_rows_extract_all(&mut rows, |row| {
3090 descriptors.push(KeyDescriptor {
3091 domain,
3092 nspace: namespace,
3093 alias: Some(row.get(0).context("Trying to extract alias.")?),
3094 blob: None,
3095 });
3096 Ok(())
3097 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003098 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003099 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003100 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003101 }
3102
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003103 /// Adds a grant to the grant table.
3104 /// Like `load_key_entry` this function loads the access tuple before
3105 /// it uses the callback for a permission check. Upon success,
3106 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3107 /// grant table. The new row will have a randomized id, which is used as
3108 /// grant id in the namespace field of the resulting KeyDescriptor.
3109 pub fn grant(
3110 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003111 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003112 caller_uid: u32,
3113 grantee_uid: u32,
3114 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003115 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003116 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003117 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3118
Janis Danisevskis66784c42021-01-27 08:40:25 -08003119 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3120 // Load the key_id and complete the access control tuple.
3121 // We ignore the access vector here because grants cannot be granted.
3122 // The access vector returned here expresses the permissions the
3123 // grantee has if key.domain == Domain::GRANT. But this vector
3124 // cannot include the grant permission by design, so there is no way the
3125 // subsequent permission check can pass.
3126 // We could check key.domain == Domain::GRANT and fail early.
3127 // But even if we load the access tuple by grant here, the permission
3128 // check denies the attempt to create a grant by grant descriptor.
3129 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003130 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003131
Janis Danisevskis66784c42021-01-27 08:40:25 -08003132 // Perform access control. It is vital that we return here if the permission
3133 // was denied. So do not touch that '?' at the end of the line.
3134 // This permission check checks if the caller has the grant permission
3135 // for the given key and in addition to all of the permissions
3136 // expressed in `access_vector`.
3137 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003138 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003139
Janis Danisevskis66784c42021-01-27 08:40:25 -08003140 let grant_id = if let Some(grant_id) = tx
3141 .query_row(
3142 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003143 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003144 params![key_id, grantee_uid],
3145 |row| row.get(0),
3146 )
3147 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003148 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08003149 {
3150 tx.execute(
3151 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003152 SET access_vector = ?
3153 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003154 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003155 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003156 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003157 grant_id
3158 } else {
3159 Self::insert_with_retry(|id| {
3160 tx.execute(
3161 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3162 VALUES (?, ?, ?, ?);",
3163 params![id, grantee_uid, key_id, i32::from(access_vector)],
3164 )
3165 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003166 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08003167 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003168
Janis Danisevskis66784c42021-01-27 08:40:25 -08003169 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003170 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003171 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003172 }
3173
3174 /// This function checks permissions like `grant` and `load_key_entry`
3175 /// before removing a grant from the grant table.
3176 pub fn ungrant(
3177 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003178 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003179 caller_uid: u32,
3180 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003181 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003182 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003183 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3184
Janis Danisevskis66784c42021-01-27 08:40:25 -08003185 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3186 // Load the key_id and complete the access control tuple.
3187 // We ignore the access vector here because grants cannot be granted.
3188 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003189 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003190
Janis Danisevskis66784c42021-01-27 08:40:25 -08003191 // Perform access control. We must return here if the permission
3192 // was denied. So do not touch the '?' at the end of this line.
3193 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003194 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003195
Janis Danisevskis66784c42021-01-27 08:40:25 -08003196 tx.execute(
3197 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003198 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003199 params![key_id, grantee_uid],
3200 )
3201 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003202
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003203 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003204 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003205 }
3206
Joel Galenson845f74b2020-09-09 14:11:55 -07003207 // Generates a random id and passes it to the given function, which will
3208 // try to insert it into a database. If that insertion fails, retry;
3209 // otherwise return the id.
3210 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3211 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003212 let newid: i64 = match random() {
3213 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3214 i => i,
3215 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003216 match inserter(newid) {
3217 // If the id already existed, try again.
3218 Err(rusqlite::Error::SqliteFailure(
3219 libsqlite3_sys::Error {
3220 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3221 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3222 },
3223 _,
3224 )) => (),
3225 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003226 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07003227 }
3228 _ => return Ok(newid),
3229 }
3230 }
3231 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003232
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003233 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3234 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3235 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3236 auth_token.clone(),
3237 MonotonicRawTime::now(),
3238 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003239 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003240
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003241 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003242 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003243 where
3244 F: Fn(&AuthTokenEntry) -> bool,
3245 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003246 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003247 }
3248
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003249 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003250 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3251 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003252 }
3253
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003254 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003255 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3256 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003257 }
3258
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003259 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003260 fn get_last_off_body(&self) -> MonotonicRawTime {
3261 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003262 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003263
3264 /// Load descriptor of a key by key id
3265 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3266 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3267
3268 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3269 tx.query_row(
3270 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3271 params![key_id],
3272 |row| {
3273 Ok(KeyDescriptor {
3274 domain: Domain(row.get(0)?),
3275 nspace: row.get(1)?,
3276 alias: row.get(2)?,
3277 blob: None,
3278 })
3279 },
3280 )
3281 .optional()
3282 .context("Trying to load key descriptor")
3283 .no_gc()
3284 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003285 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01003286 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003287}
3288
3289#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08003290pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07003291
3292 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003293 use crate::key_parameter::{
3294 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3295 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3296 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003297 use crate::key_perm_set;
3298 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08003299 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003300 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003301 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3302 HardwareAuthToken::HardwareAuthToken,
3303 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003304 };
3305 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003306 Timestamp::Timestamp,
3307 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003308 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003309 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003310 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003311 use std::collections::BTreeMap;
3312 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003313 use std::sync::atomic::{AtomicU8, Ordering};
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003314 use std::sync::{Arc, RwLock};
Janis Danisevskisaec14592020-11-12 09:41:49 -08003315 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003316 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003317 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003318 #[cfg(disabled)]
3319 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003320
Seth Moore7ee79f92021-12-07 11:42:49 -08003321 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003322 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003323
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003324 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003325 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003326 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003327 })?;
3328 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003329 }
3330
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003331 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3332 where
3333 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3334 {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003335 let super_key: Arc<RwLock<SuperKeyManager>> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003336
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003337 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003338 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003339
Janis Danisevskis3395f862021-05-06 10:54:17 -07003340 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003341 }
3342
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003343 fn rebind_alias(
3344 db: &mut KeystoreDB,
3345 newid: &KeyIdGuard,
3346 alias: &str,
3347 domain: Domain,
3348 namespace: i64,
3349 ) -> Result<bool> {
3350 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003351 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003352 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00003353 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003354 }
3355
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003356 #[test]
3357 fn datetime() -> Result<()> {
3358 let conn = Connection::open_in_memory()?;
3359 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3360 let now = SystemTime::now();
3361 let duration = Duration::from_secs(1000);
3362 let then = now.checked_sub(duration).unwrap();
3363 let soon = now.checked_add(duration).unwrap();
3364 conn.execute(
3365 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3366 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3367 )?;
3368 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3369 let mut rows = stmt.query(NO_PARAMS)?;
3370 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3371 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3372 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3373 assert!(rows.next()?.is_none());
3374 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3375 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3376 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3377 Ok(())
3378 }
3379
Joel Galenson0891bc12020-07-20 10:37:03 -07003380 // Ensure that we're using the "injected" random function, not the real one.
3381 #[test]
3382 fn test_mocked_random() {
3383 let rand1 = random();
3384 let rand2 = random();
3385 let rand3 = random();
3386 if rand1 == rand2 {
3387 assert_eq!(rand2 + 1, rand3);
3388 } else {
3389 assert_eq!(rand1 + 1, rand2);
3390 assert_eq!(rand2, rand3);
3391 }
3392 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003393
Joel Galenson26f4d012020-07-17 14:57:21 -07003394 // Test that we have the correct tables.
3395 #[test]
3396 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003397 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003398 let tables = db
3399 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003400 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003401 .query_map(params![], |row| row.get(0))?
3402 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003403 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003404 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003405 assert_eq!(tables[1], "blobmetadata");
3406 assert_eq!(tables[2], "grant");
3407 assert_eq!(tables[3], "keyentry");
3408 assert_eq!(tables[4], "keymetadata");
3409 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003410 Ok(())
3411 }
3412
3413 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003414 fn test_auth_token_table_invariant() -> Result<()> {
3415 let mut db = new_test_db()?;
3416 let auth_token1 = HardwareAuthToken {
3417 challenge: i64::MAX,
3418 userId: 200,
3419 authenticatorId: 200,
3420 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3421 timestamp: Timestamp { milliSeconds: 500 },
3422 mac: String::from("mac").into_bytes(),
3423 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003424 db.insert_auth_token(&auth_token1);
3425 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003426 assert_eq!(auth_tokens_returned.len(), 1);
3427
3428 // insert another auth token with the same values for the columns in the UNIQUE constraint
3429 // of the auth token table and different value for timestamp
3430 let auth_token2 = HardwareAuthToken {
3431 challenge: i64::MAX,
3432 userId: 200,
3433 authenticatorId: 200,
3434 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3435 timestamp: Timestamp { milliSeconds: 600 },
3436 mac: String::from("mac").into_bytes(),
3437 };
3438
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003439 db.insert_auth_token(&auth_token2);
3440 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003441 assert_eq!(auth_tokens_returned.len(), 1);
3442
3443 if let Some(auth_token) = auth_tokens_returned.pop() {
3444 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3445 }
3446
3447 // insert another auth token with the different values for the columns in the UNIQUE
3448 // constraint of the auth token table
3449 let auth_token3 = HardwareAuthToken {
3450 challenge: i64::MAX,
3451 userId: 201,
3452 authenticatorId: 200,
3453 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3454 timestamp: Timestamp { milliSeconds: 600 },
3455 mac: String::from("mac").into_bytes(),
3456 };
3457
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003458 db.insert_auth_token(&auth_token3);
3459 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003460 assert_eq!(auth_tokens_returned.len(), 2);
3461
3462 Ok(())
3463 }
3464
3465 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003466 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3467 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003468 }
3469
3470 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003471 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003472 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003473 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003474
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003475 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003476 let entries = get_keyentry(&db)?;
3477 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003478
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003479 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003480
3481 let entries_new = get_keyentry(&db)?;
3482 assert_eq!(entries, entries_new);
3483 Ok(())
3484 }
3485
3486 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003487 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003488 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3489 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003490 }
3491
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003492 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003493
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003494 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3495 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003496
3497 let entries = get_keyentry(&db)?;
3498 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003499 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3500 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003501
3502 // Test that we must pass in a valid Domain.
3503 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003504 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003505 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003506 );
3507 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003508 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003509 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003510 );
3511 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003512 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003513 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003514 );
3515
3516 Ok(())
3517 }
3518
Joel Galenson33c04ad2020-08-03 11:04:38 -07003519 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003520 fn test_add_unsigned_key() -> Result<()> {
3521 let mut db = new_test_db()?;
3522 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3523 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3524 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3525 db.create_attestation_key_entry(
3526 &public_key,
3527 &raw_public_key,
3528 &private_key,
3529 &KEYSTORE_UUID,
3530 )?;
3531 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3532 assert_eq!(keys.len(), 1);
3533 assert_eq!(keys[0], public_key);
3534 Ok(())
3535 }
3536
3537 #[test]
3538 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3539 let mut db = new_test_db()?;
Max Birescd7f7412022-02-11 13:47:36 -08003540 let expiration_date: i64 =
3541 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3542 + EXPIRATION_BUFFER_MS
3543 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003544 let namespace: i64 = 30;
3545 let base_byte: u8 = 1;
3546 let loaded_values =
3547 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3548 let chain =
3549 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Chris Wailes3877f292021-07-26 19:24:18 -07003550 assert!(chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003551 let (_, cert_chain) = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003552 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003553 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3554 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003555 Ok(())
3556 }
3557
3558 #[test]
3559 fn test_get_attestation_pool_status() -> Result<()> {
3560 let mut db = new_test_db()?;
3561 let namespace: i64 = 30;
3562 load_attestation_key_pool(
3563 &mut db, 10, /* expiration */
3564 namespace, 0x01, /* base_byte */
3565 )?;
3566 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3567 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3568 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3569 assert_eq!(status.expiring, 0);
3570 assert_eq!(status.attested, 3);
3571 assert_eq!(status.unassigned, 0);
3572 assert_eq!(status.total, 3);
3573 assert_eq!(
3574 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3575 1
3576 );
3577 assert_eq!(
3578 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3579 2
3580 );
3581 assert_eq!(
3582 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3583 3
3584 );
3585 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3586 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3587 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3588 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003589 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003590 db.create_attestation_key_entry(
3591 &public_key,
3592 &raw_public_key,
3593 &private_key,
3594 &KEYSTORE_UUID,
3595 )?;
3596 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3597 assert_eq!(status.attested, 3);
3598 assert_eq!(status.unassigned, 0);
3599 assert_eq!(status.total, 4);
3600 db.store_signed_attestation_certificate_chain(
3601 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003602 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003603 &cert_chain,
3604 20,
3605 &KEYSTORE_UUID,
3606 )?;
3607 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3608 assert_eq!(status.attested, 4);
3609 assert_eq!(status.unassigned, 1);
3610 assert_eq!(status.total, 4);
3611 Ok(())
3612 }
3613
3614 #[test]
3615 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003616 let temp_dir =
3617 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3618 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003619 let expiration_date: i64 =
Max Birescd7f7412022-02-11 13:47:36 -08003620 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3621 + EXPIRATION_BUFFER_MS
3622 + 10000;
Max Bires2b2e6562020-09-22 11:22:36 -07003623 let namespace: i64 = 30;
3624 let namespace_del1: i64 = 45;
3625 let namespace_del2: i64 = 60;
3626 let entry_values = load_attestation_key_pool(
3627 &mut db,
3628 expiration_date,
3629 namespace,
3630 0x01, /* base_byte */
3631 )?;
3632 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
Max Birescd7f7412022-02-11 13:47:36 -08003633 load_attestation_key_pool(&mut db, expiration_date - 10001, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003634
3635 let blob_entry_row_count: u32 = db
3636 .conn
3637 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3638 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003639 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3640 // one key, one certificate chain, and one certificate.
3641 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003642
Max Bires2b2e6562020-09-22 11:22:36 -07003643 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3644
3645 let mut cert_chain =
3646 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003647 assert!(cert_chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003648 let (_, value) = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003649 assert_eq!(entry_values.batch_cert, value.batch_cert);
3650 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003651 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003652
3653 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3654 Domain::APP,
3655 namespace_del1,
3656 &KEYSTORE_UUID,
3657 )?;
Chariseea1e1c482022-02-26 01:26:35 +00003658 assert!(cert_chain.is_none());
Max Bires2b2e6562020-09-22 11:22:36 -07003659 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3660 Domain::APP,
3661 namespace_del2,
3662 &KEYSTORE_UUID,
3663 )?;
Chariseea1e1c482022-02-26 01:26:35 +00003664 assert!(cert_chain.is_none());
Max Bires2b2e6562020-09-22 11:22:36 -07003665
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003666 // Give the garbage collector half a second to catch up.
3667 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003668
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003669 let blob_entry_row_count: u32 = db
3670 .conn
3671 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3672 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003673 // There shound be 3 blob entries left, because we deleted two of the attestation
3674 // key entries with three blobs each.
3675 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003676
Max Bires2b2e6562020-09-22 11:22:36 -07003677 Ok(())
3678 }
3679
Max Birescd7f7412022-02-11 13:47:36 -08003680 fn compare_rem_prov_values(
3681 expected: &RemoteProvValues,
3682 actual: Option<(KeyIdGuard, CertificateChain)>,
3683 ) {
3684 assert!(actual.is_some());
3685 let (_, value) = actual.unwrap();
3686 assert_eq!(expected.batch_cert, value.batch_cert);
3687 assert_eq!(expected.cert_chain, value.cert_chain);
3688 assert_eq!(expected.priv_key, value.private_key.to_vec());
3689 }
3690
3691 #[test]
3692 fn test_dont_remove_valid_certs() -> Result<()> {
3693 let temp_dir =
3694 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3695 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
3696 let expiration_date: i64 =
3697 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64
3698 + EXPIRATION_BUFFER_MS
3699 + 10000;
3700 let namespace1: i64 = 30;
3701 let namespace2: i64 = 45;
3702 let namespace3: i64 = 60;
3703 let entry_values1 = load_attestation_key_pool(
3704 &mut db,
3705 expiration_date,
3706 namespace1,
3707 0x01, /* base_byte */
3708 )?;
3709 let entry_values2 =
3710 load_attestation_key_pool(&mut db, expiration_date + 40000, namespace2, 0x02)?;
3711 let entry_values3 =
3712 load_attestation_key_pool(&mut db, expiration_date - 9000, namespace3, 0x03)?;
3713
3714 let blob_entry_row_count: u32 = db
3715 .conn
3716 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3717 .expect("Failed to get blob entry row count.");
3718 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3719 // one key, one certificate chain, and one certificate.
3720 assert_eq!(blob_entry_row_count, 9);
3721
3722 let mut cert_chain =
3723 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace1, &KEYSTORE_UUID)?;
3724 compare_rem_prov_values(&entry_values1, cert_chain);
3725
3726 cert_chain =
3727 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace2, &KEYSTORE_UUID)?;
3728 compare_rem_prov_values(&entry_values2, cert_chain);
3729
3730 cert_chain =
3731 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace3, &KEYSTORE_UUID)?;
3732 compare_rem_prov_values(&entry_values3, cert_chain);
3733
3734 // Give the garbage collector half a second to catch up.
3735 std::thread::sleep(Duration::from_millis(500));
3736
3737 let blob_entry_row_count: u32 = db
3738 .conn
3739 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3740 .expect("Failed to get blob entry row count.");
3741 // There shound be 9 blob entries left, because all three keys are valid with
3742 // three blobs each.
3743 assert_eq!(blob_entry_row_count, 9);
3744
3745 Ok(())
3746 }
Max Bires2b2e6562020-09-22 11:22:36 -07003747 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003748 fn test_delete_all_attestation_keys() -> Result<()> {
3749 let mut db = new_test_db()?;
3750 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3751 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003752 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003753 let result = db.delete_all_attestation_keys()?;
3754
3755 // Give the garbage collector half a second to catch up.
3756 std::thread::sleep(Duration::from_millis(500));
3757
3758 // Attestation keys should be deleted, and the regular key should remain.
3759 assert_eq!(result, 2);
3760
3761 Ok(())
3762 }
3763
3764 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003765 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003766 fn extractor(
3767 ke: &KeyEntryRow,
3768 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3769 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003770 }
3771
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003772 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003773 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3774 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003775 let entries = get_keyentry(&db)?;
3776 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003777 assert_eq!(
3778 extractor(&entries[0]),
3779 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3780 );
3781 assert_eq!(
3782 extractor(&entries[1]),
3783 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3784 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003785
3786 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003787 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003788 let entries = get_keyentry(&db)?;
3789 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003790 assert_eq!(
3791 extractor(&entries[0]),
3792 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3793 );
3794 assert_eq!(
3795 extractor(&entries[1]),
3796 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3797 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003798
3799 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003800 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003801 let entries = get_keyentry(&db)?;
3802 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003803 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3804 assert_eq!(
3805 extractor(&entries[1]),
3806 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3807 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003808
3809 // Test that we must pass in a valid Domain.
3810 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003811 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003812 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003813 );
3814 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003815 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003816 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003817 );
3818 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003819 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003820 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003821 );
3822
3823 // Test that we correctly handle setting an alias for something that does not exist.
3824 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003825 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003826 "Expected to update a single entry but instead updated 0",
3827 );
3828 // Test that we correctly abort the transaction in this case.
3829 let entries = get_keyentry(&db)?;
3830 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003831 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3832 assert_eq!(
3833 extractor(&entries[1]),
3834 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3835 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003836
3837 Ok(())
3838 }
3839
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003840 #[test]
3841 fn test_grant_ungrant() -> Result<()> {
3842 const CALLER_UID: u32 = 15;
3843 const GRANTEE_UID: u32 = 12;
3844 const SELINUX_NAMESPACE: i64 = 7;
3845
3846 let mut db = new_test_db()?;
3847 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003848 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3849 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3850 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003851 )?;
3852 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003853 domain: super::Domain::APP,
3854 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003855 alias: Some("key".to_string()),
3856 blob: None,
3857 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003858 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3859 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003860
3861 // Reset totally predictable random number generator in case we
3862 // are not the first test running on this thread.
3863 reset_random();
3864 let next_random = 0i64;
3865
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003866 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003867 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003868 assert_eq!(*a, PVEC1);
3869 assert_eq!(
3870 *k,
3871 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003872 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003873 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003874 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003875 alias: Some("key".to_string()),
3876 blob: None,
3877 }
3878 );
3879 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003880 })
3881 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003882
3883 assert_eq!(
3884 app_granted_key,
3885 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003886 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003887 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003888 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003889 alias: None,
3890 blob: None,
3891 }
3892 );
3893
3894 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003895 domain: super::Domain::SELINUX,
3896 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003897 alias: Some("yek".to_string()),
3898 blob: None,
3899 };
3900
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003901 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003902 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003903 assert_eq!(*a, PVEC1);
3904 assert_eq!(
3905 *k,
3906 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003907 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003908 // namespace must be the supplied SELinux
3909 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003910 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003911 alias: Some("yek".to_string()),
3912 blob: None,
3913 }
3914 );
3915 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003916 })
3917 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003918
3919 assert_eq!(
3920 selinux_granted_key,
3921 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003922 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003923 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003924 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003925 alias: None,
3926 blob: None,
3927 }
3928 );
3929
3930 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003931 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003932 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003933 assert_eq!(*a, PVEC2);
3934 assert_eq!(
3935 *k,
3936 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003937 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003938 // namespace must be the supplied SELinux
3939 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003940 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003941 alias: Some("yek".to_string()),
3942 blob: None,
3943 }
3944 );
3945 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003946 })
3947 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003948
3949 assert_eq!(
3950 selinux_granted_key,
3951 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003952 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003953 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003954 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003955 alias: None,
3956 blob: None,
3957 }
3958 );
3959
3960 {
3961 // Limiting scope of stmt, because it borrows db.
3962 let mut stmt = db
3963 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003964 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003965 let mut rows =
3966 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3967 Ok((
3968 row.get(0)?,
3969 row.get(1)?,
3970 row.get(2)?,
3971 KeyPermSet::from(row.get::<_, i32>(3)?),
3972 ))
3973 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003974
3975 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003976 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003977 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003978 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003979 assert!(rows.next().is_none());
3980 }
3981
3982 debug_dump_keyentry_table(&mut db)?;
3983 println!("app_key {:?}", app_key);
3984 println!("selinux_key {:?}", selinux_key);
3985
Janis Danisevskis66784c42021-01-27 08:40:25 -08003986 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3987 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003988
3989 Ok(())
3990 }
3991
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003992 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003993 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3994 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3995
3996 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003997 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003998 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003999 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004000 let mut blob_metadata = BlobMetaData::new();
4001 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4002 db.set_blob(
4003 &key_id,
4004 SubComponentType::KEY_BLOB,
4005 Some(TEST_KEY_BLOB),
4006 Some(&blob_metadata),
4007 )?;
4008 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4009 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004010 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004011
4012 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004013 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004014 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004015 )?;
4016 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004017 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
4018 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004019 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004020 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004021 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004022 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004023 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004024 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004025 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004026
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004027 drop(rows);
4028 drop(stmt);
4029
4030 assert_eq!(
4031 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4032 BlobMetaData::load_from_db(id, tx).no_gc()
4033 })
4034 .expect("Should find blob metadata."),
4035 blob_metadata
4036 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004037 Ok(())
4038 }
4039
4040 static TEST_ALIAS: &str = "my super duper key";
4041
4042 #[test]
4043 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
4044 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004045 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004046 .context("test_insert_and_load_full_keyentry_domain_app")?
4047 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004048 let (_key_guard, key_entry) = db
4049 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004050 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004051 domain: Domain::APP,
4052 nspace: 0,
4053 alias: Some(TEST_ALIAS.to_string()),
4054 blob: None,
4055 },
4056 KeyType::Client,
4057 KeyEntryLoadBits::BOTH,
4058 1,
4059 |_k, _av| Ok(()),
4060 )
4061 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004062 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004063
4064 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004065 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004066 domain: Domain::APP,
4067 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004068 alias: Some(TEST_ALIAS.to_string()),
4069 blob: None,
4070 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004071 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004072 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004073 |_, _| Ok(()),
4074 )
4075 .unwrap();
4076
4077 assert_eq!(
4078 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4079 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004080 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004081 domain: Domain::APP,
4082 nspace: 0,
4083 alias: Some(TEST_ALIAS.to_string()),
4084 blob: None,
4085 },
4086 KeyType::Client,
4087 KeyEntryLoadBits::NONE,
4088 1,
4089 |_k, _av| Ok(()),
4090 )
4091 .unwrap_err()
4092 .root_cause()
4093 .downcast_ref::<KsError>()
4094 );
4095
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004096 Ok(())
4097 }
4098
4099 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004100 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4101 let mut db = new_test_db()?;
4102
4103 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004104 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004105 domain: Domain::APP,
4106 nspace: 1,
4107 alias: Some(TEST_ALIAS.to_string()),
4108 blob: None,
4109 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004110 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004111 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004112 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004113 )
4114 .expect("Trying to insert cert.");
4115
4116 let (_key_guard, mut key_entry) = db
4117 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004118 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004119 domain: Domain::APP,
4120 nspace: 1,
4121 alias: Some(TEST_ALIAS.to_string()),
4122 blob: None,
4123 },
4124 KeyType::Client,
4125 KeyEntryLoadBits::PUBLIC,
4126 1,
4127 |_k, _av| Ok(()),
4128 )
4129 .expect("Trying to read certificate entry.");
4130
4131 assert!(key_entry.pure_cert());
4132 assert!(key_entry.cert().is_none());
4133 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4134
4135 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004136 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004137 domain: Domain::APP,
4138 nspace: 1,
4139 alias: Some(TEST_ALIAS.to_string()),
4140 blob: None,
4141 },
4142 KeyType::Client,
4143 1,
4144 |_, _| Ok(()),
4145 )
4146 .unwrap();
4147
4148 assert_eq!(
4149 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4150 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004151 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004152 domain: Domain::APP,
4153 nspace: 1,
4154 alias: Some(TEST_ALIAS.to_string()),
4155 blob: None,
4156 },
4157 KeyType::Client,
4158 KeyEntryLoadBits::NONE,
4159 1,
4160 |_k, _av| Ok(()),
4161 )
4162 .unwrap_err()
4163 .root_cause()
4164 .downcast_ref::<KsError>()
4165 );
4166
4167 Ok(())
4168 }
4169
4170 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004171 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4172 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004173 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004174 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4175 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004176 let (_key_guard, key_entry) = db
4177 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004178 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004179 domain: Domain::SELINUX,
4180 nspace: 1,
4181 alias: Some(TEST_ALIAS.to_string()),
4182 blob: None,
4183 },
4184 KeyType::Client,
4185 KeyEntryLoadBits::BOTH,
4186 1,
4187 |_k, _av| Ok(()),
4188 )
4189 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004190 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004191
4192 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004193 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004194 domain: Domain::SELINUX,
4195 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004196 alias: Some(TEST_ALIAS.to_string()),
4197 blob: None,
4198 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004199 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004200 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004201 |_, _| Ok(()),
4202 )
4203 .unwrap();
4204
4205 assert_eq!(
4206 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4207 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004208 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004209 domain: Domain::SELINUX,
4210 nspace: 1,
4211 alias: Some(TEST_ALIAS.to_string()),
4212 blob: None,
4213 },
4214 KeyType::Client,
4215 KeyEntryLoadBits::NONE,
4216 1,
4217 |_k, _av| Ok(()),
4218 )
4219 .unwrap_err()
4220 .root_cause()
4221 .downcast_ref::<KsError>()
4222 );
4223
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004224 Ok(())
4225 }
4226
4227 #[test]
4228 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4229 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004230 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004231 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4232 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004233 let (_, key_entry) = db
4234 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004235 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004236 KeyType::Client,
4237 KeyEntryLoadBits::BOTH,
4238 1,
4239 |_k, _av| Ok(()),
4240 )
4241 .unwrap();
4242
Qi Wub9433b52020-12-01 14:52:46 +08004243 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004244
4245 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004246 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004247 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004248 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004249 |_, _| Ok(()),
4250 )
4251 .unwrap();
4252
4253 assert_eq!(
4254 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4255 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004256 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004257 KeyType::Client,
4258 KeyEntryLoadBits::NONE,
4259 1,
4260 |_k, _av| Ok(()),
4261 )
4262 .unwrap_err()
4263 .root_cause()
4264 .downcast_ref::<KsError>()
4265 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004266
4267 Ok(())
4268 }
4269
4270 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004271 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4272 let mut db = new_test_db()?;
4273 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4274 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4275 .0;
4276 // Update the usage count of the limited use key.
4277 db.check_and_update_key_usage_count(key_id)?;
4278
4279 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004280 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004281 KeyType::Client,
4282 KeyEntryLoadBits::BOTH,
4283 1,
4284 |_k, _av| Ok(()),
4285 )?;
4286
4287 // The usage count is decremented now.
4288 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4289
4290 Ok(())
4291 }
4292
4293 #[test]
4294 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4295 let mut db = new_test_db()?;
4296 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4297 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4298 .0;
4299 // Update the usage count of the limited use key.
4300 db.check_and_update_key_usage_count(key_id).expect(concat!(
4301 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4302 "This should succeed."
4303 ));
4304
4305 // Try to update the exhausted limited use key.
4306 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4307 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4308 "This should fail."
4309 ));
4310 assert_eq!(
4311 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4312 e.root_cause().downcast_ref::<KsError>().unwrap()
4313 );
4314
4315 Ok(())
4316 }
4317
4318 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004319 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4320 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004321 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004322 .context("test_insert_and_load_full_keyentry_from_grant")?
4323 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004324
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004325 let granted_key = db
4326 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004327 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004328 domain: Domain::APP,
4329 nspace: 0,
4330 alias: Some(TEST_ALIAS.to_string()),
4331 blob: None,
4332 },
4333 1,
4334 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004335 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004336 |_k, _av| Ok(()),
4337 )
4338 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004339
4340 debug_dump_grant_table(&mut db)?;
4341
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004342 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004343 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4344 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004345 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08004346 Ok(())
4347 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004348 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004349
Qi Wub9433b52020-12-01 14:52:46 +08004350 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004351
Janis Danisevskis66784c42021-01-27 08:40:25 -08004352 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004353
4354 assert_eq!(
4355 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4356 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004357 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004358 KeyType::Client,
4359 KeyEntryLoadBits::NONE,
4360 2,
4361 |_k, _av| Ok(()),
4362 )
4363 .unwrap_err()
4364 .root_cause()
4365 .downcast_ref::<KsError>()
4366 );
4367
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004368 Ok(())
4369 }
4370
Janis Danisevskis45760022021-01-19 16:34:10 -08004371 // This test attempts to load a key by key id while the caller is not the owner
4372 // but a grant exists for the given key and the caller.
4373 #[test]
4374 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4375 let mut db = new_test_db()?;
4376 const OWNER_UID: u32 = 1u32;
4377 const GRANTEE_UID: u32 = 2u32;
4378 const SOMEONE_ELSE_UID: u32 = 3u32;
4379 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4380 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4381 .0;
4382
4383 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004384 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004385 domain: Domain::APP,
4386 nspace: 0,
4387 alias: Some(TEST_ALIAS.to_string()),
4388 blob: None,
4389 },
4390 OWNER_UID,
4391 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004392 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08004393 |_k, _av| Ok(()),
4394 )
4395 .unwrap();
4396
4397 debug_dump_grant_table(&mut db)?;
4398
4399 let id_descriptor =
4400 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4401
4402 let (_, key_entry) = db
4403 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004404 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004405 KeyType::Client,
4406 KeyEntryLoadBits::BOTH,
4407 GRANTEE_UID,
4408 |k, av| {
4409 assert_eq!(Domain::APP, k.domain);
4410 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004411 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08004412 Ok(())
4413 },
4414 )
4415 .unwrap();
4416
4417 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4418
4419 let (_, key_entry) = db
4420 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004421 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004422 KeyType::Client,
4423 KeyEntryLoadBits::BOTH,
4424 SOMEONE_ELSE_UID,
4425 |k, av| {
4426 assert_eq!(Domain::APP, k.domain);
4427 assert_eq!(OWNER_UID as i64, k.nspace);
4428 assert!(av.is_none());
4429 Ok(())
4430 },
4431 )
4432 .unwrap();
4433
4434 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4435
Janis Danisevskis66784c42021-01-27 08:40:25 -08004436 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004437
4438 assert_eq!(
4439 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4440 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004441 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004442 KeyType::Client,
4443 KeyEntryLoadBits::NONE,
4444 GRANTEE_UID,
4445 |_k, _av| Ok(()),
4446 )
4447 .unwrap_err()
4448 .root_cause()
4449 .downcast_ref::<KsError>()
4450 );
4451
4452 Ok(())
4453 }
4454
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004455 // Creates a key migrates it to a different location and then tries to access it by the old
4456 // and new location.
4457 #[test]
4458 fn test_migrate_key_app_to_app() -> Result<()> {
4459 let mut db = new_test_db()?;
4460 const SOURCE_UID: u32 = 1u32;
4461 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004462 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4463 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004464 let key_id_guard =
4465 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4466 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4467
4468 let source_descriptor: KeyDescriptor = KeyDescriptor {
4469 domain: Domain::APP,
4470 nspace: -1,
4471 alias: Some(SOURCE_ALIAS.to_string()),
4472 blob: None,
4473 };
4474
4475 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4476 domain: Domain::APP,
4477 nspace: -1,
4478 alias: Some(DESTINATION_ALIAS.to_string()),
4479 blob: None,
4480 };
4481
4482 let key_id = key_id_guard.id();
4483
4484 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4485 Ok(())
4486 })
4487 .unwrap();
4488
4489 let (_, key_entry) = db
4490 .load_key_entry(
4491 &destination_descriptor,
4492 KeyType::Client,
4493 KeyEntryLoadBits::BOTH,
4494 DESTINATION_UID,
4495 |k, av| {
4496 assert_eq!(Domain::APP, k.domain);
4497 assert_eq!(DESTINATION_UID as i64, k.nspace);
4498 assert!(av.is_none());
4499 Ok(())
4500 },
4501 )
4502 .unwrap();
4503
4504 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4505
4506 assert_eq!(
4507 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4508 db.load_key_entry(
4509 &source_descriptor,
4510 KeyType::Client,
4511 KeyEntryLoadBits::NONE,
4512 SOURCE_UID,
4513 |_k, _av| Ok(()),
4514 )
4515 .unwrap_err()
4516 .root_cause()
4517 .downcast_ref::<KsError>()
4518 );
4519
4520 Ok(())
4521 }
4522
4523 // Creates a key migrates it to a different location and then tries to access it by the old
4524 // and new location.
4525 #[test]
4526 fn test_migrate_key_app_to_selinux() -> Result<()> {
4527 let mut db = new_test_db()?;
4528 const SOURCE_UID: u32 = 1u32;
4529 const DESTINATION_UID: u32 = 2u32;
4530 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004531 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4532 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004533 let key_id_guard =
4534 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4535 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4536
4537 let source_descriptor: KeyDescriptor = KeyDescriptor {
4538 domain: Domain::APP,
4539 nspace: -1,
4540 alias: Some(SOURCE_ALIAS.to_string()),
4541 blob: None,
4542 };
4543
4544 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4545 domain: Domain::SELINUX,
4546 nspace: DESTINATION_NAMESPACE,
4547 alias: Some(DESTINATION_ALIAS.to_string()),
4548 blob: None,
4549 };
4550
4551 let key_id = key_id_guard.id();
4552
4553 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4554 Ok(())
4555 })
4556 .unwrap();
4557
4558 let (_, key_entry) = db
4559 .load_key_entry(
4560 &destination_descriptor,
4561 KeyType::Client,
4562 KeyEntryLoadBits::BOTH,
4563 DESTINATION_UID,
4564 |k, av| {
4565 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00004566 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004567 assert!(av.is_none());
4568 Ok(())
4569 },
4570 )
4571 .unwrap();
4572
4573 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4574
4575 assert_eq!(
4576 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4577 db.load_key_entry(
4578 &source_descriptor,
4579 KeyType::Client,
4580 KeyEntryLoadBits::NONE,
4581 SOURCE_UID,
4582 |_k, _av| Ok(()),
4583 )
4584 .unwrap_err()
4585 .root_cause()
4586 .downcast_ref::<KsError>()
4587 );
4588
4589 Ok(())
4590 }
4591
4592 // Creates two keys and tries to migrate the first to the location of the second which
4593 // is expected to fail.
4594 #[test]
4595 fn test_migrate_key_destination_occupied() -> Result<()> {
4596 let mut db = new_test_db()?;
4597 const SOURCE_UID: u32 = 1u32;
4598 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004599 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4600 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004601 let key_id_guard =
4602 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4603 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4604 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4605 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4606
4607 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4608 domain: Domain::APP,
4609 nspace: -1,
4610 alias: Some(DESTINATION_ALIAS.to_string()),
4611 blob: None,
4612 };
4613
4614 assert_eq!(
4615 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4616 db.migrate_key_namespace(
4617 key_id_guard,
4618 &destination_descriptor,
4619 DESTINATION_UID,
4620 |_k| Ok(())
4621 )
4622 .unwrap_err()
4623 .root_cause()
4624 .downcast_ref::<KsError>()
4625 );
4626
4627 Ok(())
4628 }
4629
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004630 #[test]
4631 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004632 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4633 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4634 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004635 const UID: u32 = 33;
4636 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4637 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4638 let key_id_untouched1 =
4639 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4640 let key_id_untouched2 =
4641 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4642 let key_id_deleted =
4643 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4644
4645 let (_, key_entry) = db
4646 .load_key_entry(
4647 &KeyDescriptor {
4648 domain: Domain::APP,
4649 nspace: -1,
4650 alias: Some(ALIAS1.to_string()),
4651 blob: None,
4652 },
4653 KeyType::Client,
4654 KeyEntryLoadBits::BOTH,
4655 UID,
4656 |k, av| {
4657 assert_eq!(Domain::APP, k.domain);
4658 assert_eq!(UID as i64, k.nspace);
4659 assert!(av.is_none());
4660 Ok(())
4661 },
4662 )
4663 .unwrap();
4664 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4665 let (_, key_entry) = db
4666 .load_key_entry(
4667 &KeyDescriptor {
4668 domain: Domain::APP,
4669 nspace: -1,
4670 alias: Some(ALIAS2.to_string()),
4671 blob: None,
4672 },
4673 KeyType::Client,
4674 KeyEntryLoadBits::BOTH,
4675 UID,
4676 |k, av| {
4677 assert_eq!(Domain::APP, k.domain);
4678 assert_eq!(UID as i64, k.nspace);
4679 assert!(av.is_none());
4680 Ok(())
4681 },
4682 )
4683 .unwrap();
4684 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4685 let (_, key_entry) = db
4686 .load_key_entry(
4687 &KeyDescriptor {
4688 domain: Domain::APP,
4689 nspace: -1,
4690 alias: Some(ALIAS3.to_string()),
4691 blob: None,
4692 },
4693 KeyType::Client,
4694 KeyEntryLoadBits::BOTH,
4695 UID,
4696 |k, av| {
4697 assert_eq!(Domain::APP, k.domain);
4698 assert_eq!(UID as i64, k.nspace);
4699 assert!(av.is_none());
4700 Ok(())
4701 },
4702 )
4703 .unwrap();
4704 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4705
4706 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4707 KeystoreDB::from_0_to_1(tx).no_gc()
4708 })
4709 .unwrap();
4710
4711 let (_, key_entry) = db
4712 .load_key_entry(
4713 &KeyDescriptor {
4714 domain: Domain::APP,
4715 nspace: -1,
4716 alias: Some(ALIAS1.to_string()),
4717 blob: None,
4718 },
4719 KeyType::Client,
4720 KeyEntryLoadBits::BOTH,
4721 UID,
4722 |k, av| {
4723 assert_eq!(Domain::APP, k.domain);
4724 assert_eq!(UID as i64, k.nspace);
4725 assert!(av.is_none());
4726 Ok(())
4727 },
4728 )
4729 .unwrap();
4730 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4731 let (_, key_entry) = db
4732 .load_key_entry(
4733 &KeyDescriptor {
4734 domain: Domain::APP,
4735 nspace: -1,
4736 alias: Some(ALIAS2.to_string()),
4737 blob: None,
4738 },
4739 KeyType::Client,
4740 KeyEntryLoadBits::BOTH,
4741 UID,
4742 |k, av| {
4743 assert_eq!(Domain::APP, k.domain);
4744 assert_eq!(UID as i64, k.nspace);
4745 assert!(av.is_none());
4746 Ok(())
4747 },
4748 )
4749 .unwrap();
4750 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4751 assert_eq!(
4752 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4753 db.load_key_entry(
4754 &KeyDescriptor {
4755 domain: Domain::APP,
4756 nspace: -1,
4757 alias: Some(ALIAS3.to_string()),
4758 blob: None,
4759 },
4760 KeyType::Client,
4761 KeyEntryLoadBits::BOTH,
4762 UID,
4763 |k, av| {
4764 assert_eq!(Domain::APP, k.domain);
4765 assert_eq!(UID as i64, k.nspace);
4766 assert!(av.is_none());
4767 Ok(())
4768 },
4769 )
4770 .unwrap_err()
4771 .root_cause()
4772 .downcast_ref::<KsError>()
4773 );
4774 }
4775
Janis Danisevskisaec14592020-11-12 09:41:49 -08004776 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4777
Janis Danisevskisaec14592020-11-12 09:41:49 -08004778 #[test]
4779 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4780 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004781 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4782 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004783 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004784 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004785 .context("test_insert_and_load_full_keyentry_domain_app")?
4786 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004787 let (_key_guard, key_entry) = db
4788 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004789 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004790 domain: Domain::APP,
4791 nspace: 0,
4792 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4793 blob: None,
4794 },
4795 KeyType::Client,
4796 KeyEntryLoadBits::BOTH,
4797 33,
4798 |_k, _av| Ok(()),
4799 )
4800 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004801 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004802 let state = Arc::new(AtomicU8::new(1));
4803 let state2 = state.clone();
4804
4805 // Spawning a second thread that attempts to acquire the key id lock
4806 // for the same key as the primary thread. The primary thread then
4807 // waits, thereby forcing the secondary thread into the second stage
4808 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4809 // The test succeeds if the secondary thread observes the transition
4810 // of `state` from 1 to 2, despite having a whole second to overtake
4811 // the primary thread.
4812 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004813 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004814 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004815 assert!(db
4816 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004817 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004818 domain: Domain::APP,
4819 nspace: 0,
4820 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4821 blob: None,
4822 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004823 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004824 KeyEntryLoadBits::BOTH,
4825 33,
4826 |_k, _av| Ok(()),
4827 )
4828 .is_ok());
4829 // We should only see a 2 here because we can only return
4830 // from load_key_entry when the `_key_guard` expires,
4831 // which happens at the end of the scope.
4832 assert_eq!(2, state2.load(Ordering::Relaxed));
4833 });
4834
4835 thread::sleep(std::time::Duration::from_millis(1000));
4836
4837 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4838
4839 // Return the handle from this scope so we can join with the
4840 // secondary thread after the key id lock has expired.
4841 handle
4842 // This is where the `_key_guard` goes out of scope,
4843 // which is the reason for concurrent load_key_entry on the same key
4844 // to unblock.
4845 };
4846 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4847 // main test thread. We will not see failing asserts in secondary threads otherwise.
4848 handle.join().unwrap();
4849 Ok(())
4850 }
4851
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004852 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004853 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004854 let temp_dir =
4855 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4856
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004857 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4858 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004859
4860 let _tx1 = db1
4861 .conn
4862 .transaction_with_behavior(TransactionBehavior::Immediate)
4863 .expect("Failed to create first transaction.");
4864
4865 let error = db2
4866 .conn
4867 .transaction_with_behavior(TransactionBehavior::Immediate)
4868 .context("Transaction begin failed.")
4869 .expect_err("This should fail.");
4870 let root_cause = error.root_cause();
4871 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4872 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4873 {
4874 return;
4875 }
4876 panic!(
4877 "Unexpected error {:?} \n{:?} \n{:?}",
4878 error,
4879 root_cause,
4880 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4881 )
4882 }
4883
4884 #[cfg(disabled)]
4885 #[test]
4886 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4887 let temp_dir = Arc::new(
4888 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4889 .expect("Failed to create temp dir."),
4890 );
4891
4892 let test_begin = Instant::now();
4893
Janis Danisevskis66784c42021-01-27 08:40:25 -08004894 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004895 let mut db =
4896 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004897 const OPEN_DB_COUNT: u32 = 50u32;
4898
4899 let mut actual_key_count = KEY_COUNT;
4900 // First insert KEY_COUNT keys.
4901 for count in 0..KEY_COUNT {
4902 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4903 actual_key_count = count;
4904 break;
4905 }
4906 let alias = format!("test_alias_{}", count);
4907 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4908 .expect("Failed to make key entry.");
4909 }
4910
4911 // Insert more keys from a different thread and into a different namespace.
4912 let temp_dir1 = temp_dir.clone();
4913 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004914 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4915 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004916
4917 for count in 0..actual_key_count {
4918 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4919 return;
4920 }
4921 let alias = format!("test_alias_{}", count);
4922 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4923 .expect("Failed to make key entry.");
4924 }
4925
4926 // then unbind them again.
4927 for count in 0..actual_key_count {
4928 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4929 return;
4930 }
4931 let key = KeyDescriptor {
4932 domain: Domain::APP,
4933 nspace: -1,
4934 alias: Some(format!("test_alias_{}", count)),
4935 blob: None,
4936 };
4937 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4938 }
4939 });
4940
4941 // And start unbinding the first set of keys.
4942 let temp_dir2 = temp_dir.clone();
4943 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004944 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4945 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004946
4947 for count in 0..actual_key_count {
4948 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4949 return;
4950 }
4951 let key = KeyDescriptor {
4952 domain: Domain::APP,
4953 nspace: -1,
4954 alias: Some(format!("test_alias_{}", count)),
4955 blob: None,
4956 };
4957 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4958 }
4959 });
4960
Janis Danisevskis66784c42021-01-27 08:40:25 -08004961 // While a lot of inserting and deleting is going on we have to open database connections
4962 // successfully and use them.
4963 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4964 // out of scope.
4965 #[allow(clippy::redundant_clone)]
4966 let temp_dir4 = temp_dir.clone();
4967 let handle4 = thread::spawn(move || {
4968 for count in 0..OPEN_DB_COUNT {
4969 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4970 return;
4971 }
Seth Moore444b51a2021-06-11 09:49:49 -07004972 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4973 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004974
4975 let alias = format!("test_alias_{}", count);
4976 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4977 .expect("Failed to make key entry.");
4978 let key = KeyDescriptor {
4979 domain: Domain::APP,
4980 nspace: -1,
4981 alias: Some(alias),
4982 blob: None,
4983 };
4984 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4985 }
4986 });
4987
4988 handle1.join().expect("Thread 1 panicked.");
4989 handle2.join().expect("Thread 2 panicked.");
4990 handle4.join().expect("Thread 4 panicked.");
4991
Janis Danisevskis66784c42021-01-27 08:40:25 -08004992 Ok(())
4993 }
4994
4995 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004996 fn list() -> Result<()> {
4997 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004998 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004999 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
5000 (Domain::APP, 1, "test1"),
5001 (Domain::APP, 1, "test2"),
5002 (Domain::APP, 1, "test3"),
5003 (Domain::APP, 1, "test4"),
5004 (Domain::APP, 1, "test5"),
5005 (Domain::APP, 1, "test6"),
5006 (Domain::APP, 1, "test7"),
5007 (Domain::APP, 2, "test1"),
5008 (Domain::APP, 2, "test2"),
5009 (Domain::APP, 2, "test3"),
5010 (Domain::APP, 2, "test4"),
5011 (Domain::APP, 2, "test5"),
5012 (Domain::APP, 2, "test6"),
5013 (Domain::APP, 2, "test8"),
5014 (Domain::SELINUX, 100, "test1"),
5015 (Domain::SELINUX, 100, "test2"),
5016 (Domain::SELINUX, 100, "test3"),
5017 (Domain::SELINUX, 100, "test4"),
5018 (Domain::SELINUX, 100, "test5"),
5019 (Domain::SELINUX, 100, "test6"),
5020 (Domain::SELINUX, 100, "test9"),
5021 ];
5022
5023 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
5024 .iter()
5025 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08005026 let entry =
5027 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005028 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
5029 });
5030 (entry.id(), *ns)
5031 })
5032 .collect();
5033
5034 for (domain, namespace) in
5035 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
5036 {
5037 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
5038 .iter()
5039 .filter_map(|(domain, ns, alias)| match ns {
5040 ns if *ns == *namespace => Some(KeyDescriptor {
5041 domain: *domain,
5042 nspace: *ns,
5043 alias: Some(alias.to_string()),
5044 blob: None,
5045 }),
5046 _ => None,
5047 })
5048 .collect();
5049 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07005050 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005051 list_result.sort();
5052 assert_eq!(list_o_descriptors, list_result);
5053
5054 let mut list_o_ids: Vec<i64> = list_o_descriptors
5055 .into_iter()
5056 .map(|d| {
5057 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005058 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08005059 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005060 KeyType::Client,
5061 KeyEntryLoadBits::NONE,
5062 *namespace as u32,
5063 |_, _| Ok(()),
5064 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005065 .unwrap();
5066 entry.id()
5067 })
5068 .collect();
5069 list_o_ids.sort_unstable();
5070 let mut loaded_entries: Vec<i64> = list_o_keys
5071 .iter()
5072 .filter_map(|(id, ns)| match ns {
5073 ns if *ns == *namespace => Some(*id),
5074 _ => None,
5075 })
5076 .collect();
5077 loaded_entries.sort_unstable();
5078 assert_eq!(list_o_ids, loaded_entries);
5079 }
Janis Danisevskis18313832021-05-17 13:30:32 -07005080 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005081
5082 Ok(())
5083 }
5084
Joel Galenson0891bc12020-07-20 10:37:03 -07005085 // Helpers
5086
5087 // Checks that the given result is an error containing the given string.
5088 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
5089 let error_str = format!(
5090 "{:#?}",
5091 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
5092 );
5093 assert!(
5094 error_str.contains(target),
5095 "The string \"{}\" should contain \"{}\"",
5096 error_str,
5097 target
5098 );
5099 }
5100
Joel Galenson2aab4432020-07-22 15:27:57 -07005101 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07005102 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005103 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005104 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005105 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005106 namespace: Option<i64>,
5107 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005108 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08005109 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005110 }
5111
5112 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
5113 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07005114 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07005115 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07005116 Ok(KeyEntryRow {
5117 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005118 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07005119 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07005120 namespace: row.get(3)?,
5121 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005122 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08005123 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07005124 })
5125 })?
5126 .map(|r| r.context("Could not read keyentry row."))
5127 .collect::<Result<Vec<_>>>()
5128 }
5129
Max Biresb2e1d032021-02-08 21:35:05 -08005130 struct RemoteProvValues {
5131 cert_chain: Vec<u8>,
5132 priv_key: Vec<u8>,
5133 batch_cert: Vec<u8>,
5134 }
5135
Max Bires2b2e6562020-09-22 11:22:36 -07005136 fn load_attestation_key_pool(
5137 db: &mut KeystoreDB,
5138 expiration_date: i64,
5139 namespace: i64,
5140 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08005141 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07005142 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
5143 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
5144 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5145 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005146 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005147 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5148 db.store_signed_attestation_certificate_chain(
5149 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005150 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005151 &cert_chain,
5152 expiration_date,
5153 &KEYSTORE_UUID,
5154 )?;
5155 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005156 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005157 }
5158
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005159 // Note: The parameters and SecurityLevel associations are nonsensical. This
5160 // collection is only used to check if the parameters are preserved as expected by the
5161 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005162 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5163 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005164 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5165 KeyParameter::new(
5166 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5167 SecurityLevel::TRUSTED_ENVIRONMENT,
5168 ),
5169 KeyParameter::new(
5170 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5171 SecurityLevel::TRUSTED_ENVIRONMENT,
5172 ),
5173 KeyParameter::new(
5174 KeyParameterValue::Algorithm(Algorithm::RSA),
5175 SecurityLevel::TRUSTED_ENVIRONMENT,
5176 ),
5177 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5178 KeyParameter::new(
5179 KeyParameterValue::BlockMode(BlockMode::ECB),
5180 SecurityLevel::TRUSTED_ENVIRONMENT,
5181 ),
5182 KeyParameter::new(
5183 KeyParameterValue::BlockMode(BlockMode::GCM),
5184 SecurityLevel::TRUSTED_ENVIRONMENT,
5185 ),
5186 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5187 KeyParameter::new(
5188 KeyParameterValue::Digest(Digest::MD5),
5189 SecurityLevel::TRUSTED_ENVIRONMENT,
5190 ),
5191 KeyParameter::new(
5192 KeyParameterValue::Digest(Digest::SHA_2_224),
5193 SecurityLevel::TRUSTED_ENVIRONMENT,
5194 ),
5195 KeyParameter::new(
5196 KeyParameterValue::Digest(Digest::SHA_2_256),
5197 SecurityLevel::STRONGBOX,
5198 ),
5199 KeyParameter::new(
5200 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5201 SecurityLevel::TRUSTED_ENVIRONMENT,
5202 ),
5203 KeyParameter::new(
5204 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5205 SecurityLevel::TRUSTED_ENVIRONMENT,
5206 ),
5207 KeyParameter::new(
5208 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5209 SecurityLevel::STRONGBOX,
5210 ),
5211 KeyParameter::new(
5212 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5213 SecurityLevel::TRUSTED_ENVIRONMENT,
5214 ),
5215 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5216 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5217 KeyParameter::new(
5218 KeyParameterValue::EcCurve(EcCurve::P_224),
5219 SecurityLevel::TRUSTED_ENVIRONMENT,
5220 ),
5221 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5222 KeyParameter::new(
5223 KeyParameterValue::EcCurve(EcCurve::P_384),
5224 SecurityLevel::TRUSTED_ENVIRONMENT,
5225 ),
5226 KeyParameter::new(
5227 KeyParameterValue::EcCurve(EcCurve::P_521),
5228 SecurityLevel::TRUSTED_ENVIRONMENT,
5229 ),
5230 KeyParameter::new(
5231 KeyParameterValue::RSAPublicExponent(3),
5232 SecurityLevel::TRUSTED_ENVIRONMENT,
5233 ),
5234 KeyParameter::new(
5235 KeyParameterValue::IncludeUniqueID,
5236 SecurityLevel::TRUSTED_ENVIRONMENT,
5237 ),
5238 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5239 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5240 KeyParameter::new(
5241 KeyParameterValue::ActiveDateTime(1234567890),
5242 SecurityLevel::STRONGBOX,
5243 ),
5244 KeyParameter::new(
5245 KeyParameterValue::OriginationExpireDateTime(1234567890),
5246 SecurityLevel::TRUSTED_ENVIRONMENT,
5247 ),
5248 KeyParameter::new(
5249 KeyParameterValue::UsageExpireDateTime(1234567890),
5250 SecurityLevel::TRUSTED_ENVIRONMENT,
5251 ),
5252 KeyParameter::new(
5253 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5254 SecurityLevel::TRUSTED_ENVIRONMENT,
5255 ),
5256 KeyParameter::new(
5257 KeyParameterValue::MaxUsesPerBoot(1234567890),
5258 SecurityLevel::TRUSTED_ENVIRONMENT,
5259 ),
5260 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5261 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5262 KeyParameter::new(
5263 KeyParameterValue::NoAuthRequired,
5264 SecurityLevel::TRUSTED_ENVIRONMENT,
5265 ),
5266 KeyParameter::new(
5267 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5268 SecurityLevel::TRUSTED_ENVIRONMENT,
5269 ),
5270 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5271 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5272 KeyParameter::new(
5273 KeyParameterValue::TrustedUserPresenceRequired,
5274 SecurityLevel::TRUSTED_ENVIRONMENT,
5275 ),
5276 KeyParameter::new(
5277 KeyParameterValue::TrustedConfirmationRequired,
5278 SecurityLevel::TRUSTED_ENVIRONMENT,
5279 ),
5280 KeyParameter::new(
5281 KeyParameterValue::UnlockedDeviceRequired,
5282 SecurityLevel::TRUSTED_ENVIRONMENT,
5283 ),
5284 KeyParameter::new(
5285 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5286 SecurityLevel::SOFTWARE,
5287 ),
5288 KeyParameter::new(
5289 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5290 SecurityLevel::SOFTWARE,
5291 ),
5292 KeyParameter::new(
5293 KeyParameterValue::CreationDateTime(12345677890),
5294 SecurityLevel::SOFTWARE,
5295 ),
5296 KeyParameter::new(
5297 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5298 SecurityLevel::TRUSTED_ENVIRONMENT,
5299 ),
5300 KeyParameter::new(
5301 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5302 SecurityLevel::TRUSTED_ENVIRONMENT,
5303 ),
5304 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5305 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5306 KeyParameter::new(
5307 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5308 SecurityLevel::SOFTWARE,
5309 ),
5310 KeyParameter::new(
5311 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5312 SecurityLevel::TRUSTED_ENVIRONMENT,
5313 ),
5314 KeyParameter::new(
5315 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5316 SecurityLevel::TRUSTED_ENVIRONMENT,
5317 ),
5318 KeyParameter::new(
5319 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5320 SecurityLevel::TRUSTED_ENVIRONMENT,
5321 ),
5322 KeyParameter::new(
5323 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5324 SecurityLevel::TRUSTED_ENVIRONMENT,
5325 ),
5326 KeyParameter::new(
5327 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5328 SecurityLevel::TRUSTED_ENVIRONMENT,
5329 ),
5330 KeyParameter::new(
5331 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5332 SecurityLevel::TRUSTED_ENVIRONMENT,
5333 ),
5334 KeyParameter::new(
5335 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5336 SecurityLevel::TRUSTED_ENVIRONMENT,
5337 ),
5338 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00005339 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5340 SecurityLevel::TRUSTED_ENVIRONMENT,
5341 ),
5342 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005343 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5344 SecurityLevel::TRUSTED_ENVIRONMENT,
5345 ),
5346 KeyParameter::new(
5347 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5348 SecurityLevel::TRUSTED_ENVIRONMENT,
5349 ),
5350 KeyParameter::new(
5351 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5352 SecurityLevel::TRUSTED_ENVIRONMENT,
5353 ),
5354 KeyParameter::new(
5355 KeyParameterValue::VendorPatchLevel(3),
5356 SecurityLevel::TRUSTED_ENVIRONMENT,
5357 ),
5358 KeyParameter::new(
5359 KeyParameterValue::BootPatchLevel(4),
5360 SecurityLevel::TRUSTED_ENVIRONMENT,
5361 ),
5362 KeyParameter::new(
5363 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5364 SecurityLevel::TRUSTED_ENVIRONMENT,
5365 ),
5366 KeyParameter::new(
5367 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5368 SecurityLevel::TRUSTED_ENVIRONMENT,
5369 ),
5370 KeyParameter::new(
5371 KeyParameterValue::MacLength(256),
5372 SecurityLevel::TRUSTED_ENVIRONMENT,
5373 ),
5374 KeyParameter::new(
5375 KeyParameterValue::ResetSinceIdRotation,
5376 SecurityLevel::TRUSTED_ENVIRONMENT,
5377 ),
5378 KeyParameter::new(
5379 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5380 SecurityLevel::TRUSTED_ENVIRONMENT,
5381 ),
Qi Wub9433b52020-12-01 14:52:46 +08005382 ];
5383 if let Some(value) = max_usage_count {
5384 params.push(KeyParameter::new(
5385 KeyParameterValue::UsageCountLimit(value),
5386 SecurityLevel::SOFTWARE,
5387 ));
5388 }
5389 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005390 }
5391
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005392 fn make_test_key_entry(
5393 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005394 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005395 namespace: i64,
5396 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005397 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005398 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005399 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005400 let mut blob_metadata = BlobMetaData::new();
5401 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5402 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5403 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5404 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5405 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5406
5407 db.set_blob(
5408 &key_id,
5409 SubComponentType::KEY_BLOB,
5410 Some(TEST_KEY_BLOB),
5411 Some(&blob_metadata),
5412 )?;
5413 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5414 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005415
5416 let params = make_test_params(max_usage_count);
5417 db.insert_keyparameter(&key_id, &params)?;
5418
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005419 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005420 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005421 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005422 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005423 Ok(key_id)
5424 }
5425
Qi Wub9433b52020-12-01 14:52:46 +08005426 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5427 let params = make_test_params(max_usage_count);
5428
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005429 let mut blob_metadata = BlobMetaData::new();
5430 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5431 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5432 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5433 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5434 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5435
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005436 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005437 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005438
5439 KeyEntry {
5440 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005441 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005442 cert: Some(TEST_CERT_BLOB.to_vec()),
5443 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005444 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005445 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005446 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005447 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005448 }
5449 }
5450
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005451 fn make_bootlevel_key_entry(
5452 db: &mut KeystoreDB,
5453 domain: Domain,
5454 namespace: i64,
5455 alias: &str,
5456 logical_only: bool,
5457 ) -> Result<KeyIdGuard> {
5458 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5459 let mut blob_metadata = BlobMetaData::new();
5460 if !logical_only {
5461 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5462 }
5463 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5464
5465 db.set_blob(
5466 &key_id,
5467 SubComponentType::KEY_BLOB,
5468 Some(TEST_KEY_BLOB),
5469 Some(&blob_metadata),
5470 )?;
5471 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5472 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5473
5474 let mut params = make_test_params(None);
5475 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5476
5477 db.insert_keyparameter(&key_id, &params)?;
5478
5479 let mut metadata = KeyMetaData::new();
5480 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5481 db.insert_key_metadata(&key_id, &metadata)?;
5482 rebind_alias(db, &key_id, alias, domain, namespace)?;
5483 Ok(key_id)
5484 }
5485
5486 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5487 let mut params = make_test_params(None);
5488 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5489
5490 let mut blob_metadata = BlobMetaData::new();
5491 if !logical_only {
5492 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5493 }
5494 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5495
5496 let mut metadata = KeyMetaData::new();
5497 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5498
5499 KeyEntry {
5500 id: key_id,
5501 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5502 cert: Some(TEST_CERT_BLOB.to_vec()),
5503 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5504 km_uuid: KEYSTORE_UUID,
5505 parameters: params,
5506 metadata,
5507 pure_cert: false,
5508 }
5509 }
5510
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005511 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005512 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005513 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005514 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005515 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005516 NO_PARAMS,
5517 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005518 Ok((
5519 row.get(0)?,
5520 row.get(1)?,
5521 row.get(2)?,
5522 row.get(3)?,
5523 row.get(4)?,
5524 row.get(5)?,
5525 row.get(6)?,
5526 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005527 },
5528 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005529
5530 println!("Key entry table rows:");
5531 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005532 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005533 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005534 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5535 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005536 );
5537 }
5538 Ok(())
5539 }
5540
5541 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005542 let mut stmt = db
5543 .conn
5544 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005545 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5546 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5547 })?;
5548
5549 println!("Grant table rows:");
5550 for r in rows {
5551 let (id, gt, ki, av) = r.unwrap();
5552 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5553 }
5554 Ok(())
5555 }
5556
Joel Galenson0891bc12020-07-20 10:37:03 -07005557 // Use a custom random number generator that repeats each number once.
5558 // This allows us to test repeated elements.
5559
5560 thread_local! {
5561 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5562 }
5563
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005564 fn reset_random() {
5565 RANDOM_COUNTER.with(|counter| {
5566 *counter.borrow_mut() = 0;
5567 })
5568 }
5569
Joel Galenson0891bc12020-07-20 10:37:03 -07005570 pub fn random() -> i64 {
5571 RANDOM_COUNTER.with(|counter| {
5572 let result = *counter.borrow() / 2;
5573 *counter.borrow_mut() += 1;
5574 result
5575 })
5576 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005577
5578 #[test]
5579 fn test_last_off_body() -> Result<()> {
5580 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005581 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005582 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005583 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005584 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005585 let one_second = Duration::from_secs(1);
5586 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005587 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005588 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005589 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005590 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005591 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005592 Ok(())
5593 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005594
5595 #[test]
5596 fn test_unbind_keys_for_user() -> Result<()> {
5597 let mut db = new_test_db()?;
5598 db.unbind_keys_for_user(1, false)?;
5599
5600 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5601 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5602 db.unbind_keys_for_user(2, false)?;
5603
Janis Danisevskis18313832021-05-17 13:30:32 -07005604 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5605 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005606
5607 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005608 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005609
5610 Ok(())
5611 }
5612
5613 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005614 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5615 let mut db = new_test_db()?;
5616 let super_key = keystore2_crypto::generate_aes256_key()?;
5617 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5618 let (encrypted_super_key, metadata) =
5619 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5620
5621 let key_name_enc = SuperKeyType {
5622 alias: "test_super_key_1",
5623 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5624 };
5625
5626 let key_name_nonenc = SuperKeyType {
5627 alias: "test_super_key_2",
5628 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5629 };
5630
5631 // Install two super keys.
5632 db.store_super_key(
5633 1,
5634 &key_name_nonenc,
5635 &super_key,
5636 &BlobMetaData::new(),
5637 &KeyMetaData::new(),
5638 )?;
5639 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5640
5641 // Check that both can be found in the database.
5642 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5643 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5644
5645 // Install the same keys for a different user.
5646 db.store_super_key(
5647 2,
5648 &key_name_nonenc,
5649 &super_key,
5650 &BlobMetaData::new(),
5651 &KeyMetaData::new(),
5652 )?;
5653 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5654
5655 // Check that the second pair of keys can be found in the database.
5656 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5657 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5658
5659 // Delete only encrypted keys.
5660 db.unbind_keys_for_user(1, true)?;
5661
5662 // The encrypted superkey should be gone now.
5663 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5664 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5665
5666 // Reinsert the encrypted key.
5667 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5668
5669 // Check that both can be found in the database, again..
5670 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5671 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5672
5673 // Delete all even unencrypted keys.
5674 db.unbind_keys_for_user(1, false)?;
5675
5676 // Both should be gone now.
5677 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5678 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5679
5680 // Check that the second pair of keys was untouched.
5681 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5682 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5683
5684 Ok(())
5685 }
5686
5687 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005688 fn test_store_super_key() -> Result<()> {
5689 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005690 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005691 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005692 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005693 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005694 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005695
5696 let (encrypted_super_key, metadata) =
5697 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005698 db.store_super_key(
5699 1,
5700 &USER_SUPER_KEY,
5701 &encrypted_super_key,
5702 &metadata,
5703 &KeyMetaData::new(),
5704 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005705
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005706 // Check if super key exists.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005707 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005708
Paul Crowley7a658392021-03-18 17:08:20 -07005709 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005710 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5711 USER_SUPER_KEY.algorithm,
5712 key_entry,
5713 &pw,
5714 None,
5715 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005716
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005717 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005718 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005719
Hasini Gunasingheda895552021-01-27 19:34:37 +00005720 Ok(())
5721 }
Seth Moore78c091f2021-04-09 21:38:30 +00005722
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005723 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005724 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005725 MetricsStorage::KEY_ENTRY,
5726 MetricsStorage::KEY_ENTRY_ID_INDEX,
5727 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5728 MetricsStorage::BLOB_ENTRY,
5729 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5730 MetricsStorage::KEY_PARAMETER,
5731 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5732 MetricsStorage::KEY_METADATA,
5733 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5734 MetricsStorage::GRANT,
5735 MetricsStorage::AUTH_TOKEN,
5736 MetricsStorage::BLOB_METADATA,
5737 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005738 ]
5739 }
5740
5741 /// Perform a simple check to ensure that we can query all the storage types
5742 /// that are supported by the DB. Check for reasonable values.
5743 #[test]
5744 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005745 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005746
5747 let mut db = new_test_db()?;
5748
5749 for t in get_valid_statsd_storage_types() {
5750 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005751 // AuthToken can be less than a page since it's in a btree, not sqlite
5752 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005753 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005754 } else {
5755 assert!(stat.size >= PAGE_SIZE);
5756 }
Seth Moore78c091f2021-04-09 21:38:30 +00005757 assert!(stat.size >= stat.unused_size);
5758 }
5759
5760 Ok(())
5761 }
5762
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005763 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005764 get_valid_statsd_storage_types()
5765 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005766 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005767 .collect()
5768 }
5769
5770 fn assert_storage_increased(
5771 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005772 increased_storage_types: Vec<MetricsStorage>,
5773 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005774 ) {
5775 for storage in increased_storage_types {
5776 // Verify the expected storage increased.
5777 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005778 let storage = storage;
5779 let old = &baseline[&storage.0];
5780 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005781 assert!(
5782 new.unused_size <= old.unused_size,
5783 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005784 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005785 new.unused_size,
5786 old.unused_size
5787 );
5788
5789 // Update the baseline with the new value so that it succeeds in the
5790 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005791 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005792 }
5793
5794 // Get an updated map of the storage and verify there were no unexpected changes.
5795 let updated_stats = get_storage_stats_map(db);
5796 assert_eq!(updated_stats.len(), baseline.len());
5797
5798 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005799 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005800 let mut s = String::new();
5801 for &k in map.keys() {
5802 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5803 .expect("string concat failed");
5804 }
5805 s
5806 };
5807
5808 assert!(
5809 updated_stats[&k].size == baseline[&k].size
5810 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5811 "updated_stats:\n{}\nbaseline:\n{}",
5812 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005813 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005814 );
5815 }
5816 }
5817
5818 #[test]
5819 fn test_verify_key_table_size_reporting() -> Result<()> {
5820 let mut db = new_test_db()?;
5821 let mut working_stats = get_storage_stats_map(&mut db);
5822
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005823 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005824 assert_storage_increased(
5825 &mut db,
5826 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005827 MetricsStorage::KEY_ENTRY,
5828 MetricsStorage::KEY_ENTRY_ID_INDEX,
5829 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005830 ],
5831 &mut working_stats,
5832 );
5833
5834 let mut blob_metadata = BlobMetaData::new();
5835 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5836 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5837 assert_storage_increased(
5838 &mut db,
5839 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005840 MetricsStorage::BLOB_ENTRY,
5841 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5842 MetricsStorage::BLOB_METADATA,
5843 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005844 ],
5845 &mut working_stats,
5846 );
5847
5848 let params = make_test_params(None);
5849 db.insert_keyparameter(&key_id, &params)?;
5850 assert_storage_increased(
5851 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005852 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005853 &mut working_stats,
5854 );
5855
5856 let mut metadata = KeyMetaData::new();
5857 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5858 db.insert_key_metadata(&key_id, &metadata)?;
5859 assert_storage_increased(
5860 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005861 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005862 &mut working_stats,
5863 );
5864
5865 let mut sum = 0;
5866 for stat in working_stats.values() {
5867 sum += stat.size;
5868 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005869 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005870 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5871
5872 Ok(())
5873 }
5874
5875 #[test]
5876 fn test_verify_auth_table_size_reporting() -> Result<()> {
5877 let mut db = new_test_db()?;
5878 let mut working_stats = get_storage_stats_map(&mut db);
5879 db.insert_auth_token(&HardwareAuthToken {
5880 challenge: 123,
5881 userId: 456,
5882 authenticatorId: 789,
5883 authenticatorType: kmhw_authenticator_type::ANY,
5884 timestamp: Timestamp { milliSeconds: 10 },
5885 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005886 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005887 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005888 Ok(())
5889 }
5890
5891 #[test]
5892 fn test_verify_grant_table_size_reporting() -> Result<()> {
5893 const OWNER: i64 = 1;
5894 let mut db = new_test_db()?;
5895 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5896
5897 let mut working_stats = get_storage_stats_map(&mut db);
5898 db.grant(
5899 &KeyDescriptor {
5900 domain: Domain::APP,
5901 nspace: 0,
5902 alias: Some(TEST_ALIAS.to_string()),
5903 blob: None,
5904 },
5905 OWNER as u32,
5906 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005907 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005908 |_, _| Ok(()),
5909 )?;
5910
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005911 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005912
5913 Ok(())
5914 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005915
5916 #[test]
5917 fn find_auth_token_entry_returns_latest() -> Result<()> {
5918 let mut db = new_test_db()?;
5919 db.insert_auth_token(&HardwareAuthToken {
5920 challenge: 123,
5921 userId: 456,
5922 authenticatorId: 789,
5923 authenticatorType: kmhw_authenticator_type::ANY,
5924 timestamp: Timestamp { milliSeconds: 10 },
5925 mac: b"mac0".to_vec(),
5926 });
5927 std::thread::sleep(std::time::Duration::from_millis(1));
5928 db.insert_auth_token(&HardwareAuthToken {
5929 challenge: 123,
5930 userId: 457,
5931 authenticatorId: 789,
5932 authenticatorType: kmhw_authenticator_type::ANY,
5933 timestamp: Timestamp { milliSeconds: 12 },
5934 mac: b"mac1".to_vec(),
5935 });
5936 std::thread::sleep(std::time::Duration::from_millis(1));
5937 db.insert_auth_token(&HardwareAuthToken {
5938 challenge: 123,
5939 userId: 458,
5940 authenticatorId: 789,
5941 authenticatorType: kmhw_authenticator_type::ANY,
5942 timestamp: Timestamp { milliSeconds: 3 },
5943 mac: b"mac2".to_vec(),
5944 });
5945 // All three entries are in the database
5946 assert_eq!(db.perboot.auth_tokens_len(), 3);
5947 // It selected the most recent timestamp
5948 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5949 Ok(())
5950 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005951
5952 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005953 fn test_load_key_descriptor() -> Result<()> {
5954 let mut db = new_test_db()?;
5955 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5956
5957 let key = db.load_key_descriptor(key_id)?.unwrap();
5958
5959 assert_eq!(key.domain, Domain::APP);
5960 assert_eq!(key.nspace, 1);
5961 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5962
5963 // No such id
5964 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5965 Ok(())
5966 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005967}