blob: 825a4b075deb2fb16f15df87c0d14fecd599ee5b [file] [log] [blame]
Joel Galenson26f4d012020-07-17 14:57:21 -07001// Copyright 2020, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070015//! This is the Keystore 2.0 database module.
16//! The database module provides a connection to the backing SQLite store.
17//! We have two databases one for persistent key blob storage and one for
18//! items that have a per boot life cycle.
19//!
20//! ## Persistent database
21//! The persistent database has tables for key blobs. They are organized
22//! as follows:
23//! The `keyentry` table is the primary table for key entries. It is
24//! accompanied by two tables for blobs and parameters.
25//! Each key entry occupies exactly one row in the `keyentry` table and
26//! zero or more rows in the tables `blobentry` and `keyparameter`.
27//!
28//! ## Per boot database
29//! The per boot database stores items with a per boot lifecycle.
30//! Currently, there is only the `grant` table in this database.
31//! Grants are references to a key that can be used to access a key by
32//! clients that don't own that key. Grants can only be created by the
33//! owner of a key. And only certain components can create grants.
34//! This is governed by SEPolicy.
35//!
36//! ## Access control
37//! Some database functions that load keys or create grants perform
38//! access control. This is because in some cases access control
39//! can only be performed after some information about the designated
40//! key was loaded from the database. To decouple the permission checks
41//! from the database module these functions take permission check
42//! callbacks.
Joel Galenson26f4d012020-07-17 14:57:21 -070043
Matthew Maurerd7815ca2021-05-06 21:58:45 -070044mod perboot;
Janis Danisevskis030ba022021-05-26 11:15:30 -070045pub(crate) mod utils;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -070046mod versioning;
Matthew Maurerd7815ca2021-05-06 21:58:45 -070047
Janis Danisevskis11bd2592022-01-04 19:59:26 -080048use crate::gc::Gc;
Janis Danisevskisb42fc182020-12-15 08:41:27 -080049use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080050use crate::key_parameter::{KeyParameter, Tag};
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +000051use crate::ks_err;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070052use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000053use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080054use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070055 error::{Error as KsError, ErrorCode, ResponseCode},
56 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080057};
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000058use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Tri Voa1634bb2022-12-01 15:54:19 -080059 HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
60 SecurityLevel::SecurityLevel,
61};
62use android_security_metrics::aidl::android::security::metrics::{
Tri Vo0346bbe2023-05-12 14:16:31 -040063 Storage::Storage as MetricsStorage, StorageStats::StorageStats,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080064};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070065use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070066 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070067};
Shaquille Johnson7f5a8152023-09-27 18:46:27 +010068use anyhow::{anyhow, Context, Result};
69use keystore2_flags;
70use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
71use utils as db_utils;
72use utils::SqlField;
Max Bires2b2e6562020-09-22 11:22:36 -070073
74use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080075use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000076use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070077#[cfg(not(test))]
78use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070079use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070080 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080081 types::FromSql,
82 types::FromSqlResult,
83 types::ToSqlOutput,
84 types::{FromSqlError, Value, ValueRef},
Andrew Walbran78abb1e2023-05-30 16:20:56 +000085 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070086};
Max Bires2b2e6562020-09-22 11:22:36 -070087
Janis Danisevskisaec14592020-11-12 09:41:49 -080088use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080089 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080090 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070091 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080092 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080093};
Max Bires2b2e6562020-09-22 11:22:36 -070094
Joel Galenson0891bc12020-07-20 10:37:03 -070095#[cfg(test)]
96use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070097
Janis Danisevskisb42fc182020-12-15 08:41:27 -080098impl_metadata!(
99 /// A set of metadata for key entries.
100 #[derive(Debug, Default, Eq, PartialEq)]
101 pub struct KeyMetaData;
102 /// A metadata entry for key entries.
103 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
104 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800105 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800106 CreationDate(DateTime) with accessor creation_date,
107 /// Expiration date for attestation keys.
108 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700109 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
110 /// provisioning
111 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
112 /// Vector representing the raw public key so results from the server can be matched
113 /// to the right entry
114 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700115 /// SEC1 public key for ECDH encryption
116 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800117 // --- ADD NEW META DATA FIELDS HERE ---
118 // For backwards compatibility add new entries only to
119 // end of this list and above this comment.
120 };
121);
122
123impl KeyMetaData {
124 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
125 let mut stmt = tx
126 .prepare(
127 "SELECT tag, data from persistent.keymetadata
128 WHERE keyentryid = ?;",
129 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000130 .context(ks_err!("KeyMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800131
132 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
133
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000134 let mut rows = stmt
135 .query(params![key_id])
136 .context(ks_err!("KeyMetaData::load_from_db: query failed."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800137 db_utils::with_rows_extract_all(&mut rows, |row| {
138 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
139 metadata.insert(
140 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700141 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800142 .context("Failed to read KeyMetaEntry.")?,
143 );
144 Ok(())
145 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000146 .context(ks_err!("KeyMetaData::load_from_db."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800147
148 Ok(Self { data: metadata })
149 }
150
151 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
152 let mut stmt = tx
153 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000154 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800155 VALUES (?, ?, ?);",
156 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000157 .context(ks_err!("KeyMetaData::store_in_db: Failed to prepare statement."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800158
159 let iter = self.data.iter();
160 for (tag, entry) in iter {
161 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000162 ks_err!("KeyMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800163 })?;
164 }
165 Ok(())
166 }
167}
168
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800169impl_metadata!(
170 /// A set of metadata for key blobs.
171 #[derive(Debug, Default, Eq, PartialEq)]
172 pub struct BlobMetaData;
173 /// A metadata entry for key blobs.
174 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
175 pub enum BlobMetaEntry {
176 /// If present, indicates that the blob is encrypted with another key or a key derived
177 /// from a password.
178 EncryptedBy(EncryptedBy) with accessor encrypted_by,
179 /// If the blob is password encrypted this field is set to the
180 /// salt used for the key derivation.
181 Salt(Vec<u8>) with accessor salt,
182 /// If the blob is encrypted, this field is set to the initialization vector.
183 Iv(Vec<u8>) with accessor iv,
184 /// If the blob is encrypted, this field holds the AEAD TAG.
185 AeadTag(Vec<u8>) with accessor aead_tag,
186 /// The uuid of the owning KeyMint instance.
187 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700188 /// If the key is ECDH encrypted, this is the ephemeral public key
189 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000190 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
191 /// of that key
192 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800193 // --- ADD NEW META DATA FIELDS HERE ---
194 // For backwards compatibility add new entries only to
195 // end of this list and above this comment.
196 };
197);
198
199impl BlobMetaData {
200 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
201 let mut stmt = tx
202 .prepare(
203 "SELECT tag, data from persistent.blobmetadata
204 WHERE blobentryid = ?;",
205 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000206 .context(ks_err!("BlobMetaData::load_from_db: prepare statement failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800207
208 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
209
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000210 let mut rows = stmt.query(params![blob_id]).context(ks_err!("query failed."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800211 db_utils::with_rows_extract_all(&mut rows, |row| {
212 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
213 metadata.insert(
214 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700215 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800216 .context("Failed to read BlobMetaEntry.")?,
217 );
218 Ok(())
219 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000220 .context(ks_err!("BlobMetaData::load_from_db"))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221
222 Ok(Self { data: metadata })
223 }
224
225 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
226 let mut stmt = tx
227 .prepare(
228 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
229 VALUES (?, ?, ?);",
230 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000231 .context(ks_err!("BlobMetaData::store_in_db: Failed to prepare statement.",))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800232
233 let iter = self.data.iter();
234 for (tag, entry) in iter {
235 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000236 ks_err!("BlobMetaData::store_in_db: Failed to insert {:?}", entry)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800237 })?;
238 }
239 Ok(())
240 }
241}
242
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800243/// Indicates the type of the keyentry.
244#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
245pub enum KeyType {
246 /// This is a client key type. These keys are created or imported through the Keystore 2.0
247 /// AIDL interface android.system.keystore2.
248 Client,
249 /// This is a super key type. These keys are created by keystore itself and used to encrypt
250 /// other key blobs to provide LSKF binding.
251 Super,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800252}
253
254impl ToSql for KeyType {
255 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
256 Ok(ToSqlOutput::Owned(Value::Integer(match self {
257 KeyType::Client => 0,
258 KeyType::Super => 1,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800259 })))
260 }
261}
262
263impl FromSql for KeyType {
264 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
265 match i64::column_result(value)? {
266 0 => Ok(KeyType::Client),
267 1 => Ok(KeyType::Super),
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800268 v => Err(FromSqlError::OutOfRange(v)),
269 }
270 }
271}
272
Max Bires8e93d2b2021-01-14 13:17:59 -0800273/// Uuid representation that can be stored in the database.
274/// Right now it can only be initialized from SecurityLevel.
275/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
276#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
277pub struct Uuid([u8; 16]);
278
279impl Deref for Uuid {
280 type Target = [u8; 16];
281
282 fn deref(&self) -> &Self::Target {
283 &self.0
284 }
285}
286
287impl From<SecurityLevel> for Uuid {
288 fn from(sec_level: SecurityLevel) -> Self {
289 Self((sec_level.0 as u128).to_be_bytes())
290 }
291}
292
293impl ToSql for Uuid {
294 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
295 self.0.to_sql()
296 }
297}
298
299impl FromSql for Uuid {
300 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
301 let blob = Vec::<u8>::column_result(value)?;
302 if blob.len() != 16 {
303 return Err(FromSqlError::OutOfRange(blob.len() as i64));
304 }
305 let mut arr = [0u8; 16];
306 arr.copy_from_slice(&blob);
307 Ok(Self(arr))
308 }
309}
310
311/// Key entries that are not associated with any KeyMint instance, such as pure certificate
312/// entries are associated with this UUID.
313pub static KEYSTORE_UUID: Uuid = Uuid([
314 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
315]);
316
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800317/// Indicates how the sensitive part of this key blob is encrypted.
318#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
319pub enum EncryptedBy {
320 /// The keyblob is encrypted by a user password.
321 /// In the database this variant is represented as NULL.
322 Password,
323 /// The keyblob is encrypted by another key with wrapped key id.
324 /// In the database this variant is represented as non NULL value
325 /// that is convertible to i64, typically NUMERIC.
326 KeyId(i64),
327}
328
329impl ToSql for EncryptedBy {
330 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
331 match self {
332 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
333 Self::KeyId(id) => id.to_sql(),
334 }
335 }
336}
337
338impl FromSql for EncryptedBy {
339 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
340 match value {
341 ValueRef::Null => Ok(Self::Password),
342 _ => Ok(Self::KeyId(i64::column_result(value)?)),
343 }
344 }
345}
346
347/// A database representation of wall clock time. DateTime stores unix epoch time as
348/// i64 in milliseconds.
349#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
350pub struct DateTime(i64);
351
352/// Error type returned when creating DateTime or converting it from and to
353/// SystemTime.
354#[derive(thiserror::Error, Debug)]
355pub enum DateTimeError {
356 /// This is returned when SystemTime and Duration computations fail.
357 #[error(transparent)]
358 SystemTimeError(#[from] SystemTimeError),
359
360 /// This is returned when type conversions fail.
361 #[error(transparent)]
362 TypeConversion(#[from] std::num::TryFromIntError),
363
364 /// This is returned when checked time arithmetic failed.
365 #[error("Time arithmetic failed.")]
366 TimeArithmetic,
367}
368
369impl DateTime {
370 /// Constructs a new DateTime object denoting the current time. This may fail during
371 /// conversion to unix epoch time and during conversion to the internal i64 representation.
372 pub fn now() -> Result<Self, DateTimeError> {
373 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
374 }
375
376 /// Constructs a new DateTime object from milliseconds.
377 pub fn from_millis_epoch(millis: i64) -> Self {
378 Self(millis)
379 }
380
381 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700382 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800383 self.0
384 }
385
386 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700387 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800388 self.0 / 1000
389 }
390}
391
392impl ToSql for DateTime {
393 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
394 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
395 }
396}
397
398impl FromSql for DateTime {
399 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
400 Ok(Self(i64::column_result(value)?))
401 }
402}
403
404impl TryInto<SystemTime> for DateTime {
405 type Error = DateTimeError;
406
407 fn try_into(self) -> Result<SystemTime, Self::Error> {
408 // We want to construct a SystemTime representation equivalent to self, denoting
409 // a point in time THEN, but we cannot set the time directly. We can only construct
410 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
411 // and between EPOCH and THEN. With this common reference we can construct the
412 // duration between NOW and THEN which we can add to our SystemTime representation
413 // of NOW to get a SystemTime representation of THEN.
414 // Durations can only be positive, thus the if statement below.
415 let now = SystemTime::now();
416 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
417 let then_epoch = Duration::from_millis(self.0.try_into()?);
418 Ok(if now_epoch > then_epoch {
419 // then = now - (now_epoch - then_epoch)
420 now_epoch
421 .checked_sub(then_epoch)
422 .and_then(|d| now.checked_sub(d))
423 .ok_or(DateTimeError::TimeArithmetic)?
424 } else {
425 // then = now + (then_epoch - now_epoch)
426 then_epoch
427 .checked_sub(now_epoch)
428 .and_then(|d| now.checked_add(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 })
431 }
432}
433
434impl TryFrom<SystemTime> for DateTime {
435 type Error = DateTimeError;
436
437 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
438 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
439 }
440}
441
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800442#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
443enum KeyLifeCycle {
444 /// Existing keys have a key ID but are not fully populated yet.
445 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
446 /// them to Unreferenced for garbage collection.
447 Existing,
448 /// A live key is fully populated and usable by clients.
449 Live,
450 /// An unreferenced key is scheduled for garbage collection.
451 Unreferenced,
452}
453
454impl ToSql for KeyLifeCycle {
455 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
456 match self {
457 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
458 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
459 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
460 }
461 }
462}
463
464impl FromSql for KeyLifeCycle {
465 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
466 match i64::column_result(value)? {
467 0 => Ok(KeyLifeCycle::Existing),
468 1 => Ok(KeyLifeCycle::Live),
469 2 => Ok(KeyLifeCycle::Unreferenced),
470 v => Err(FromSqlError::OutOfRange(v)),
471 }
472 }
473}
474
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700475/// Keys have a KeyMint blob component and optional public certificate and
476/// certificate chain components.
477/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
478/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800479#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700480pub struct KeyEntryLoadBits(u32);
481
482impl KeyEntryLoadBits {
483 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
484 pub const NONE: KeyEntryLoadBits = Self(0);
485 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
486 pub const KM: KeyEntryLoadBits = Self(1);
487 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
488 pub const PUBLIC: KeyEntryLoadBits = Self(2);
489 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
490 pub const BOTH: KeyEntryLoadBits = Self(3);
491
492 /// Returns true if this object indicates that the public components shall be loaded.
493 pub const fn load_public(&self) -> bool {
494 self.0 & Self::PUBLIC.0 != 0
495 }
496
497 /// Returns true if the object indicates that the KeyMint component shall be loaded.
498 pub const fn load_km(&self) -> bool {
499 self.0 & Self::KM.0 != 0
500 }
501}
502
Janis Danisevskisaec14592020-11-12 09:41:49 -0800503lazy_static! {
504 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
505}
506
507struct KeyIdLockDb {
508 locked_keys: Mutex<HashSet<i64>>,
509 cond_var: Condvar,
510}
511
512/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
513/// from the database a second time. Most functions manipulating the key blob database
514/// require a KeyIdGuard.
515#[derive(Debug)]
516pub struct KeyIdGuard(i64);
517
518impl KeyIdLockDb {
519 fn new() -> Self {
520 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
521 }
522
523 /// This function blocks until an exclusive lock for the given key entry id can
524 /// be acquired. It returns a guard object, that represents the lifecycle of the
525 /// acquired lock.
526 pub fn get(&self, key_id: i64) -> KeyIdGuard {
527 let mut locked_keys = self.locked_keys.lock().unwrap();
528 while locked_keys.contains(&key_id) {
529 locked_keys = self.cond_var.wait(locked_keys).unwrap();
530 }
531 locked_keys.insert(key_id);
532 KeyIdGuard(key_id)
533 }
534
535 /// This function attempts to acquire an exclusive lock on a given key id. If the
536 /// given key id is already taken the function returns None immediately. If a lock
537 /// can be acquired this function returns a guard object, that represents the
538 /// lifecycle of the acquired lock.
539 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
540 let mut locked_keys = self.locked_keys.lock().unwrap();
541 if locked_keys.insert(key_id) {
542 Some(KeyIdGuard(key_id))
543 } else {
544 None
545 }
546 }
547}
548
549impl KeyIdGuard {
550 /// Get the numeric key id of the locked key.
551 pub fn id(&self) -> i64 {
552 self.0
553 }
554}
555
556impl Drop for KeyIdGuard {
557 fn drop(&mut self) {
558 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
559 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800560 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800561 KEY_ID_LOCK.cond_var.notify_all();
562 }
563}
564
Max Bires8e93d2b2021-01-14 13:17:59 -0800565/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700566#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800567pub struct CertificateInfo {
568 cert: Option<Vec<u8>>,
569 cert_chain: Option<Vec<u8>>,
570}
571
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800572/// This type represents a Blob with its metadata and an optional superseded blob.
573#[derive(Debug)]
574pub struct BlobInfo<'a> {
575 blob: &'a [u8],
576 metadata: &'a BlobMetaData,
577 /// Superseded blobs are an artifact of legacy import. In some rare occasions
578 /// the key blob needs to be upgraded during import. In that case two
579 /// blob are imported, the superseded one will have to be imported first,
580 /// so that the garbage collector can reap it.
581 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
582}
583
584impl<'a> BlobInfo<'a> {
585 /// Create a new instance of blob info with blob and corresponding metadata
586 /// and no superseded blob info.
587 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
588 Self { blob, metadata, superseded_blob: None }
589 }
590
591 /// Create a new instance of blob info with blob and corresponding metadata
592 /// as well as superseded blob info.
593 pub fn new_with_superseded(
594 blob: &'a [u8],
595 metadata: &'a BlobMetaData,
596 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
597 ) -> Self {
598 Self { blob, metadata, superseded_blob }
599 }
600}
601
Max Bires8e93d2b2021-01-14 13:17:59 -0800602impl CertificateInfo {
603 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
604 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
605 Self { cert, cert_chain }
606 }
607
608 /// Take the cert
609 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
610 self.cert.take()
611 }
612
613 /// Take the cert chain
614 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
615 self.cert_chain.take()
616 }
617}
618
Max Bires2b2e6562020-09-22 11:22:36 -0700619/// This type represents a certificate chain with a private key corresponding to the leaf
620/// 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 -0700621pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800622 /// A KM key blob
623 pub private_key: ZVec,
624 /// A batch cert for private_key
625 pub batch_cert: Vec<u8>,
626 /// A full certificate chain from root signing authority to private_key, including batch_cert
627 /// for convenience.
628 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700629}
630
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631/// This type represents a Keystore 2.0 key entry.
632/// An entry has a unique `id` by which it can be found in the database.
633/// It has a security level field, key parameters, and three optional fields
634/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800635#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700636pub struct KeyEntry {
637 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800638 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700639 cert: Option<Vec<u8>>,
640 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800641 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700642 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800643 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800644 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700645}
646
647impl KeyEntry {
648 /// Returns the unique id of the Key entry.
649 pub fn id(&self) -> i64 {
650 self.id
651 }
652 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800653 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
654 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800656 /// Extracts the Optional KeyMint blob including its metadata.
657 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
658 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700659 }
660 /// Exposes the optional public certificate.
661 pub fn cert(&self) -> &Option<Vec<u8>> {
662 &self.cert
663 }
664 /// Extracts the optional public certificate.
665 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
666 self.cert.take()
667 }
668 /// Exposes the optional public certificate chain.
669 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
670 &self.cert_chain
671 }
672 /// Extracts the optional public certificate_chain.
673 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
674 self.cert_chain.take()
675 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800676 /// Returns the uuid of the owning KeyMint instance.
677 pub fn km_uuid(&self) -> &Uuid {
678 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700679 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700680 /// Exposes the key parameters of this key entry.
681 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
682 &self.parameters
683 }
684 /// Consumes this key entry and extracts the keyparameters from it.
685 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
686 self.parameters
687 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800688 /// Exposes the key metadata of this key entry.
689 pub fn metadata(&self) -> &KeyMetaData {
690 &self.metadata
691 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800692 /// This returns true if the entry is a pure certificate entry with no
693 /// private key component.
694 pub fn pure_cert(&self) -> bool {
695 self.pure_cert
696 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000697 /// Consumes this key entry and extracts the keyparameters and metadata from it.
698 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
699 (self.parameters, self.metadata)
700 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700701}
702
703/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800704#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700705pub struct SubComponentType(u32);
706impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800707 /// Persistent identifier for a key blob.
708 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700709 /// Persistent identifier for a certificate blob.
710 pub const CERT: SubComponentType = Self(1);
711 /// Persistent identifier for a certificate chain blob.
712 pub const CERT_CHAIN: SubComponentType = Self(2);
713}
714
715impl ToSql for SubComponentType {
716 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
717 self.0.to_sql()
718 }
719}
720
721impl FromSql for SubComponentType {
722 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
723 Ok(Self(u32::column_result(value)?))
724 }
725}
726
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800727/// This trait is private to the database module. It is used to convey whether or not the garbage
728/// collector shall be invoked after a database access. All closures passed to
729/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
730/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
731/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
732/// `.need_gc()`.
733trait DoGc<T> {
734 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
735
736 fn no_gc(self) -> Result<(bool, T)>;
737
738 fn need_gc(self) -> Result<(bool, T)>;
739}
740
741impl<T> DoGc<T> for Result<T> {
742 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
743 self.map(|r| (need_gc, r))
744 }
745
746 fn no_gc(self) -> Result<(bool, T)> {
747 self.do_gc(false)
748 }
749
750 fn need_gc(self) -> Result<(bool, T)> {
751 self.do_gc(true)
752 }
753}
754
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700755/// KeystoreDB wraps a connection to an SQLite database and tracks its
756/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700757pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700758 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700759 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700760 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700761}
762
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000763/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000764/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000765#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
766pub struct MonotonicRawTime(i64);
767
768impl MonotonicRawTime {
769 /// Constructs a new MonotonicRawTime
770 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000771 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000772 }
773
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000774 /// Returns the value of MonotonicRawTime in milliseconds as i64
775 pub fn milliseconds(&self) -> i64 {
776 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000777 }
778
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000779 /// Returns the integer value of MonotonicRawTime as i64
780 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000781 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000782 }
783
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800784 /// Like i64::checked_sub.
785 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
786 self.0.checked_sub(other.0).map(Self)
787 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788}
789
790impl ToSql for MonotonicRawTime {
791 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
792 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
793 }
794}
795
796impl FromSql for MonotonicRawTime {
797 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
798 Ok(Self(i64::column_result(value)?))
799 }
800}
801
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000802/// This struct encapsulates the information to be stored in the database about the auth tokens
803/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700804#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000805pub struct AuthTokenEntry {
806 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000807 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000808 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000809}
810
811impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000812 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000813 AuthTokenEntry { auth_token, time_received }
814 }
815
816 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800817 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800819 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
Charisee03e00842023-01-25 01:41:23 +0000820 && ((auth_type.0 & self.auth_token.authenticatorType.0) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000821 })
822 }
823
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000824 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800825 pub fn auth_token(&self) -> &HardwareAuthToken {
826 &self.auth_token
827 }
828
829 /// Returns the auth token wrapped by the AuthTokenEntry
830 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000831 self.auth_token
832 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800833
834 /// Returns the time that this auth token was received.
835 pub fn time_received(&self) -> MonotonicRawTime {
836 self.time_received
837 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000838
839 /// Returns the challenge value of the auth token.
840 pub fn challenge(&self) -> i64 {
841 self.auth_token.challenge
842 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000843}
844
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800845/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
846/// This object does not allow access to the database connection. But it keeps a database
847/// connection alive in order to keep the in memory per boot database alive.
848pub struct PerBootDbKeepAlive(Connection);
849
Joel Galenson26f4d012020-07-17 14:57:21 -0700850impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800851 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700852 const CURRENT_DB_VERSION: u32 = 1;
853 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854
Seth Moore78c091f2021-04-09 21:38:30 +0000855 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700856 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000857
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700858 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800859 /// files persistent.sqlite and perboot.sqlite in the given directory.
860 /// It also attempts to initialize all of the tables.
861 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700862 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700863 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700864 let _wp = wd::watch_millis("KeystoreDB::new", 500);
865
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700866 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700867 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800868
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700869 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800870 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700871 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000872 .context(ks_err!("KeystoreDB::new: trying to upgrade database."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800873 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800874 })?;
875 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700876 }
877
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700878 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
879 // cryptographic binding to the boot level keys was implemented.
880 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
881 tx.execute(
882 "UPDATE persistent.keyentry SET state = ?
883 WHERE
884 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
885 AND
886 id NOT IN (
887 SELECT keyentryid FROM persistent.blobentry
888 WHERE id IN (
889 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
890 )
891 );",
892 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
893 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +0000894 .context(ks_err!("Failed to delete logical boot level keys."))?;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700895 Ok(1)
896 }
897
Janis Danisevskis66784c42021-01-27 08:40:25 -0800898 fn init_tables(tx: &Transaction) -> Result<()> {
899 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700900 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700901 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800902 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700903 domain INTEGER,
904 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800905 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800906 state INTEGER,
907 km_uuid BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000908 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 )
910 .context("Failed to initialize \"keyentry\" table.")?;
911
Janis Danisevskis66784c42021-01-27 08:40:25 -0800912 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800913 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
914 ON keyentry(id);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000915 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800916 )
917 .context("Failed to create index keyentry_id_index.")?;
918
919 tx.execute(
920 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
921 ON keyentry(domain, namespace, alias);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000922 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800923 )
924 .context("Failed to create index keyentry_domain_namespace_index.")?;
925
926 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700927 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
928 id INTEGER PRIMARY KEY,
929 subcomponent_type INTEGER,
930 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800931 blob BLOB);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000932 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700933 )
934 .context("Failed to initialize \"blobentry\" table.")?;
935
Janis Danisevskis66784c42021-01-27 08:40:25 -0800936 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800937 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
938 ON blobentry(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000939 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800940 )
941 .context("Failed to create index blobentry_keyentryid_index.")?;
942
943 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800944 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
945 id INTEGER PRIMARY KEY,
946 blobentryid INTEGER,
947 tag INTEGER,
948 data ANY,
949 UNIQUE (blobentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000950 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800951 )
952 .context("Failed to initialize \"blobmetadata\" table.")?;
953
954 tx.execute(
955 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
956 ON blobmetadata(blobentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000957 [],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800958 )
959 .context("Failed to create index blobmetadata_blobentryid_index.")?;
960
961 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700962 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000963 keyentryid INTEGER,
964 tag INTEGER,
965 data ANY,
966 security_level INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000967 [],
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700968 )
969 .context("Failed to initialize \"keyparameter\" table.")?;
970
Janis Danisevskis66784c42021-01-27 08:40:25 -0800971 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800972 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
973 ON keyparameter(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000974 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800975 )
976 .context("Failed to create index keyparameter_keyentryid_index.")?;
977
978 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800979 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
980 keyentryid INTEGER,
981 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000982 data ANY,
983 UNIQUE (keyentryid, tag));",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000984 [],
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800985 )
986 .context("Failed to initialize \"keymetadata\" table.")?;
987
Janis Danisevskis66784c42021-01-27 08:40:25 -0800988 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800989 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
990 ON keymetadata(keyentryid);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +0000991 [],
Janis Danisevskisa5438182021-02-02 14:22:59 -0800992 )
993 .context("Failed to create index keymetadata_keyentryid_index.")?;
994
995 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800996 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700997 id INTEGER UNIQUE,
998 grantee INTEGER,
999 keyentryid INTEGER,
1000 access_vector INTEGER);",
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001001 [],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001002 )
1003 .context("Failed to initialize \"grant\" table.")?;
1004
Joel Galenson0891bc12020-07-20 10:37:03 -07001005 Ok(())
1006 }
1007
Seth Moore472fcbb2021-05-12 10:07:51 -07001008 fn make_persistent_path(db_root: &Path) -> Result<String> {
1009 // Build the path to the sqlite file.
1010 let mut persistent_path = db_root.to_path_buf();
1011 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1012
1013 // Now convert them to strings prefixed with "file:"
1014 let mut persistent_path_str = "file:".to_owned();
1015 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1016
1017 Ok(persistent_path_str)
1018 }
1019
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001020 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001021 let conn =
1022 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1023
Janis Danisevskis66784c42021-01-27 08:40:25 -08001024 loop {
1025 if let Err(e) = conn
1026 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1027 .context("Failed to attach database persistent.")
1028 {
1029 if Self::is_locked_error(&e) {
1030 std::thread::sleep(std::time::Duration::from_micros(500));
1031 continue;
1032 } else {
1033 return Err(e);
1034 }
1035 }
1036 break;
1037 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001038
Shaquille Johnson7f5a8152023-09-27 18:46:27 +01001039 if keystore2_flags::wal_db_journalmode() {
1040 // Update journal mode to WAL
1041 conn.pragma_update(None, "journal_mode", "WAL")
1042 .context("Failed to connect in WAL mode for persistent db")?;
1043 }
Matthew Maurer4fb19112021-05-06 15:40:44 -07001044 // Drop the cache size from default (2M) to 0.5M
1045 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1046 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001047
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001048 Ok(conn)
1049 }
1050
Seth Moore78c091f2021-04-09 21:38:30 +00001051 fn do_table_size_query(
1052 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001053 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001054 query: &str,
1055 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001056 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001057 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001058 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001059 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001060 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001061 })
1062 .no_gc()
1063 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001064 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001065 }
1066
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001067 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001068 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001069 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001070 "SELECT page_count * page_size, freelist_count * page_size
1071 FROM pragma_page_count('persistent'),
1072 pragma_page_size('persistent'),
1073 persistent.pragma_freelist_count();",
1074 &[],
1075 )
1076 }
1077
1078 fn get_table_size(
1079 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001080 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001081 schema: &str,
1082 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001083 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001084 self.do_table_size_query(
1085 storage_type,
1086 "SELECT pgsize,unused FROM dbstat(?1)
1087 WHERE name=?2 AND aggregate=TRUE;",
1088 &[schema, table],
1089 )
1090 }
1091
1092 /// Fetches a storage statisitics atom for a given storage type. For storage
1093 /// types that map to a table, information about the table's storage is
1094 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001095 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001096 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1097
Seth Moore78c091f2021-04-09 21:38:30 +00001098 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001099 MetricsStorage::DATABASE => self.get_total_size(),
1100 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001101 self.get_table_size(storage_type, "persistent", "keyentry")
1102 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001103 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001104 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1105 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001106 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001107 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1108 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001109 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001110 self.get_table_size(storage_type, "persistent", "blobentry")
1111 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001112 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001113 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1114 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001115 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001116 self.get_table_size(storage_type, "persistent", "keyparameter")
1117 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001118 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001119 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1120 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001121 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001122 self.get_table_size(storage_type, "persistent", "keymetadata")
1123 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001124 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001125 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1126 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001127 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1128 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001129 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1130 // reportable
1131 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001132 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001133 storage_type,
1134 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001135 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001136 unused_size: 0,
1137 })
Seth Moore78c091f2021-04-09 21:38:30 +00001138 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001140 self.get_table_size(storage_type, "persistent", "blobmetadata")
1141 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001142 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001143 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1144 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001145 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001146 }
1147 }
1148
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001149 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001150 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1151 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001152 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1153 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001155 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001156 blob_ids_to_delete: &[i64],
1157 max_blobs: usize,
1158 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001159 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001160 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001161 // Delete the given blobs.
1162 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001163 tx.execute(
1164 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001166 )
1167 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001168 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1169 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001170 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001171
1172 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1173
Janis Danisevskis3395f862021-05-06 10:54:17 -07001174 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1175 let result: Vec<(i64, Vec<u8>)> = {
1176 let mut stmt = tx
1177 .prepare(
1178 "SELECT id, blob FROM persistent.blobentry
1179 WHERE subcomponent_type = ?
1180 AND (
1181 id NOT IN (
1182 SELECT MAX(id) FROM persistent.blobentry
1183 WHERE subcomponent_type = ?
1184 GROUP BY keyentryid, subcomponent_type
1185 )
1186 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1187 ) LIMIT ?;",
1188 )
1189 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001190
Janis Danisevskis3395f862021-05-06 10:54:17 -07001191 let rows = stmt
1192 .query_map(
1193 params![
1194 SubComponentType::KEY_BLOB,
1195 SubComponentType::KEY_BLOB,
1196 max_blobs as i64,
1197 ],
1198 |row| Ok((row.get(0)?, row.get(1)?)),
1199 )
1200 .context("Trying to query superseded blob.")?;
1201
1202 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1203 .context("Trying to extract superseded blobs.")?
1204 };
1205
1206 let result = result
1207 .into_iter()
1208 .map(|(blob_id, blob)| {
1209 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1210 })
1211 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1212 .context("Trying to load blob metadata.")?;
1213 if !result.is_empty() {
1214 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001215 }
1216
1217 // We did not find any superseded key blob, so let's remove other superseded blob in
1218 // one transaction.
1219 tx.execute(
1220 "DELETE FROM persistent.blobentry
1221 WHERE NOT subcomponent_type = ?
1222 AND (
1223 id NOT IN (
1224 SELECT MAX(id) FROM persistent.blobentry
1225 WHERE NOT subcomponent_type = ?
1226 GROUP BY keyentryid, subcomponent_type
1227 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1228 );",
1229 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1230 )
1231 .context("Trying to purge superseded blobs.")?;
1232
Janis Danisevskis3395f862021-05-06 10:54:17 -07001233 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001234 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001235 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001236 }
1237
1238 /// This maintenance function should be called only once before the database is used for the
1239 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1240 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1241 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1242 /// Keystore crashed at some point during key generation. Callers may want to log such
1243 /// occurrences.
1244 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1245 /// it to `KeyLifeCycle::Live` may have grants.
1246 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001247 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1248
Janis Danisevskis66784c42021-01-27 08:40:25 -08001249 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1250 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001251 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1252 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1253 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001254 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001255 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001256 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001257 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001258 }
1259
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001260 /// Checks if a key exists with given key type and key descriptor properties.
1261 pub fn key_exists(
1262 &mut self,
1263 domain: Domain,
1264 nspace: i64,
1265 alias: &str,
1266 key_type: KeyType,
1267 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001268 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1269
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001270 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1271 let key_descriptor =
1272 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001273 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001274 match result {
1275 Ok(_) => Ok(true),
1276 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1277 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001278 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001279 },
1280 }
1281 .no_gc()
1282 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001283 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001284 }
1285
Hasini Gunasingheda895552021-01-27 19:34:37 +00001286 /// Stores a super key in the database.
1287 pub fn store_super_key(
1288 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001289 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001290 key_type: &SuperKeyType,
1291 blob: &[u8],
1292 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001293 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001294 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001295 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1296
Hasini Gunasingheda895552021-01-27 19:34:37 +00001297 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1298 let key_id = Self::insert_with_retry(|id| {
1299 tx.execute(
1300 "INSERT into persistent.keyentry
1301 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001302 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001303 params![
1304 id,
1305 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001306 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001307 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001308 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001309 KeyLifeCycle::Live,
1310 &KEYSTORE_UUID,
1311 ],
1312 )
1313 })
1314 .context("Failed to insert into keyentry table.")?;
1315
Paul Crowley8d5b2532021-03-19 10:53:07 -07001316 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1317
Hasini Gunasingheda895552021-01-27 19:34:37 +00001318 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001319 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001320 key_id,
1321 SubComponentType::KEY_BLOB,
1322 Some(blob),
1323 Some(blob_metadata),
1324 )
1325 .context("Failed to store key blob.")?;
1326
1327 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1328 .context("Trying to load key components.")
1329 .no_gc()
1330 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001331 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001332 }
1333
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001334 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001335 pub fn load_super_key(
1336 &mut self,
1337 key_type: &SuperKeyType,
1338 user_id: u32,
1339 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001340 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1341
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001342 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1343 let key_descriptor = KeyDescriptor {
1344 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001345 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001346 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001347 blob: None,
1348 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001349 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001350 match id {
1351 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001352 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001353 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001354 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1355 }
1356 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1357 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001358 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001359 },
1360 }
1361 .no_gc()
1362 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001363 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001364 }
1365
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001366 /// Atomically loads a key entry and associated metadata or creates it using the
1367 /// callback create_new_key callback. The callback is called during a database
1368 /// transaction. This means that implementers should be mindful about using
1369 /// blocking operations such as IPC or grabbing mutexes.
1370 pub fn get_or_create_key_with<F>(
1371 &mut self,
1372 domain: Domain,
1373 namespace: i64,
1374 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001375 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001376 create_new_key: F,
1377 ) -> Result<(KeyIdGuard, KeyEntry)>
1378 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001379 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001380 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001381 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1382
Janis Danisevskis66784c42021-01-27 08:40:25 -08001383 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1384 let id = {
1385 let mut stmt = tx
1386 .prepare(
1387 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001388 WHERE
1389 key_type = ?
1390 AND domain = ?
1391 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001392 AND alias = ?
1393 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001394 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001395 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001396 let mut rows = stmt
1397 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001398 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001399
Janis Danisevskis66784c42021-01-27 08:40:25 -08001400 db_utils::with_rows_extract_one(&mut rows, |row| {
1401 Ok(match row {
1402 Some(r) => r.get(0).context("Failed to unpack id.")?,
1403 None => None,
1404 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001405 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001406 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001407 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001408
Janis Danisevskis66784c42021-01-27 08:40:25 -08001409 let (id, entry) = match id {
1410 Some(id) => (
1411 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001412 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001414
Janis Danisevskis66784c42021-01-27 08:40:25 -08001415 None => {
1416 let id = Self::insert_with_retry(|id| {
1417 tx.execute(
1418 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001419 (id, key_type, domain, namespace, alias, state, km_uuid)
1420 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001421 params![
1422 id,
1423 KeyType::Super,
1424 domain.0,
1425 namespace,
1426 alias,
1427 KeyLifeCycle::Live,
1428 km_uuid,
1429 ],
1430 )
1431 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001432 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001433
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001434 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001435 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001436 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001437 id,
1438 SubComponentType::KEY_BLOB,
1439 Some(&blob),
1440 Some(&metadata),
1441 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001442 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001443 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001444 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001445 KeyEntry {
1446 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001447 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001448 pure_cert: false,
1449 ..Default::default()
1450 },
1451 )
1452 }
1453 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001454 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001455 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001456 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001457 }
1458
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001459 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001460 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1461 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001462 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1463 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001464 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001465 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001466 loop {
1467 match self
1468 .conn
1469 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001470 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001471 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1472 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001473 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001474 Ok(result)
1475 }) {
1476 Ok(result) => break Ok(result),
1477 Err(e) => {
1478 if Self::is_locked_error(&e) {
1479 std::thread::sleep(std::time::Duration::from_micros(500));
1480 continue;
1481 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001482 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001483 }
1484 }
1485 }
1486 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001487 .map(|(need_gc, result)| {
1488 if need_gc {
1489 if let Some(ref gc) = self.gc {
1490 gc.notify_gc();
1491 }
1492 }
1493 result
1494 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001495 }
1496
1497 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001498 matches!(
1499 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1500 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1501 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1502 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001503 }
1504
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001505 /// Creates a new key entry and allocates a new randomized id for the new key.
1506 /// The key id gets associated with a domain and namespace but not with an alias.
1507 /// To complete key generation `rebind_alias` should be called after all of the
1508 /// key artifacts, i.e., blobs and parameters have been associated with the new
1509 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1510 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001511 pub fn create_key_entry(
1512 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001513 domain: &Domain,
1514 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001515 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001516 km_uuid: &Uuid,
1517 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001518 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1519
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001520 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001521 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001522 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001523 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001524 }
1525
1526 fn create_key_entry_internal(
1527 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001528 domain: &Domain,
1529 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001530 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001531 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001532 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001533 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001534 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001535 _ => {
1536 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001537 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001538 }
1539 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001540 Ok(KEY_ID_LOCK.get(
1541 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001542 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001543 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001544 (id, key_type, domain, namespace, alias, state, km_uuid)
1545 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001546 params![
1547 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001548 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001549 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001550 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001551 KeyLifeCycle::Existing,
1552 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001553 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001554 )
1555 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001556 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001557 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001558 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001559
Janis Danisevskis377d1002021-01-27 19:07:48 -08001560 /// Set a new blob and associates it with the given key id. Each blob
1561 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001562 /// Each key can have one of each sub component type associated. If more
1563 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001564 /// will get garbage collected.
1565 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1566 /// removed by setting blob to None.
1567 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001568 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001569 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001570 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001571 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001572 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001573 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001574 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1575
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001576 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001577 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001578 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001579 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001580 }
1581
Janis Danisevskiseed69842021-02-18 20:04:10 -08001582 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1583 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1584 /// We use this to insert key blobs into the database which can then be garbage collected
1585 /// lazily by the key garbage collector.
1586 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001587 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1588
Janis Danisevskiseed69842021-02-18 20:04:10 -08001589 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1590 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001591 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001592 Self::UNASSIGNED_KEY_ID,
1593 SubComponentType::KEY_BLOB,
1594 Some(blob),
1595 Some(blob_metadata),
1596 )
1597 .need_gc()
1598 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001599 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001600 }
1601
Janis Danisevskis377d1002021-01-27 19:07:48 -08001602 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001603 tx: &Transaction,
1604 key_id: i64,
1605 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001606 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001607 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001608 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001609 match (blob, sc_type) {
1610 (Some(blob), _) => {
1611 tx.execute(
1612 "INSERT INTO persistent.blobentry
1613 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1614 params![sc_type, key_id, blob],
1615 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001616 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001617 if let Some(blob_metadata) = blob_metadata {
1618 let blob_id = tx
Andrew Walbran78abb1e2023-05-30 16:20:56 +00001619 .query_row("SELECT MAX(id) FROM persistent.blobentry;", [], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001620 row.get(0)
1621 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001622 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001623 blob_metadata
1624 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001625 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001626 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001627 }
1628 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1629 tx.execute(
1630 "DELETE FROM persistent.blobentry
1631 WHERE subcomponent_type = ? AND keyentryid = ?;",
1632 params![sc_type, key_id],
1633 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001634 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001635 }
1636 (None, _) => {
1637 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001638 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001639 }
1640 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001641 Ok(())
1642 }
1643
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001644 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1645 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001646 #[cfg(test)]
1647 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001648 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001649 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001650 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001651 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001652 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001653
Janis Danisevskis66784c42021-01-27 08:40:25 -08001654 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001655 tx: &Transaction,
1656 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001657 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001658 ) -> Result<()> {
1659 let mut stmt = tx
1660 .prepare(
1661 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1662 VALUES (?, ?, ?, ?);",
1663 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001664 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001665
Janis Danisevskis66784c42021-01-27 08:40:25 -08001666 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001667 stmt.insert(params![
1668 key_id.0,
1669 p.get_tag().0,
1670 p.key_parameter_value(),
1671 p.security_level().0
1672 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001673 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001674 }
1675 Ok(())
1676 }
1677
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001678 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001679 #[cfg(test)]
1680 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001681 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001682 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001683 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001684 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001685 }
1686
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001687 /// Updates the alias column of the given key id `newid` with the given alias,
1688 /// and atomically, removes the alias, domain, and namespace from another row
1689 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001690 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1691 /// collector.
1692 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001693 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001694 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001695 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001696 domain: &Domain,
1697 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001698 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001699 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001700 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001701 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001702 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001703 return Err(KsError::sys())
1704 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001705 }
1706 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001707 let updated = tx
1708 .execute(
1709 "UPDATE persistent.keyentry
1710 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001711 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1712 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001713 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001714 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001715 let result = tx
1716 .execute(
1717 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001718 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001719 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001720 params![
1721 alias,
1722 KeyLifeCycle::Live,
1723 newid.0,
1724 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001725 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001726 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001727 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001728 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001729 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001730 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001731 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001732 return Err(KsError::sys()).context(ks_err!(
1733 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001734 result
1735 ));
1736 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001737 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001738 }
1739
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001740 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1741 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1742 pub fn migrate_key_namespace(
1743 &mut self,
1744 key_id_guard: KeyIdGuard,
1745 destination: &KeyDescriptor,
1746 caller_uid: u32,
1747 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1748 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001749 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1750
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001751 let destination = match destination.domain {
1752 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1753 Domain::SELINUX => (*destination).clone(),
1754 domain => {
1755 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1756 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1757 }
1758 };
1759
1760 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001761 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001762
1763 let alias = destination
1764 .alias
1765 .as_ref()
1766 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001767 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001768
1769 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1770 // Query the destination location. If there is a key, the migration request fails.
1771 if tx
1772 .query_row(
1773 "SELECT id FROM persistent.keyentry
1774 WHERE alias = ? AND domain = ? AND namespace = ?;",
1775 params![alias, destination.domain.0, destination.nspace],
1776 |_| Ok(()),
1777 )
1778 .optional()
1779 .context("Failed to query destination.")?
1780 .is_some()
1781 {
1782 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1783 .context("Target already exists.");
1784 }
1785
1786 let updated = tx
1787 .execute(
1788 "UPDATE persistent.keyentry
1789 SET alias = ?, domain = ?, namespace = ?
1790 WHERE id = ?;",
1791 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1792 )
1793 .context("Failed to update key entry.")?;
1794
1795 if updated != 1 {
1796 return Err(KsError::sys())
1797 .context(format!("Update succeeded, but {} rows were updated.", updated));
1798 }
1799 Ok(()).no_gc()
1800 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001801 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001802 }
1803
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001804 /// Store a new key in a single transaction.
1805 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1806 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001807 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1808 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001809 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001810 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001811 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001812 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001813 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001814 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001815 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001816 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001817 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001818 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001819 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001820 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1821
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001822 let (alias, domain, namespace) = match key {
1823 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1824 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1825 (alias, key.domain, nspace)
1826 }
1827 _ => {
1828 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001829 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001830 }
1831 };
1832 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001833 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001834 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001835 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1836
1837 // In some occasions the key blob is already upgraded during the import.
1838 // In order to make sure it gets properly deleted it is inserted into the
1839 // database here and then immediately replaced by the superseding blob.
1840 // The garbage collector will then subject the blob to deleteKey of the
1841 // KM back end to permanently invalidate the key.
1842 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1843 Self::set_blob_internal(
1844 tx,
1845 key_id.id(),
1846 SubComponentType::KEY_BLOB,
1847 Some(blob),
1848 Some(blob_metadata),
1849 )
1850 .context("Trying to insert superseded key blob.")?;
1851 true
1852 } else {
1853 false
1854 };
1855
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001856 Self::set_blob_internal(
1857 tx,
1858 key_id.id(),
1859 SubComponentType::KEY_BLOB,
1860 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001861 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001862 )
1863 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001864 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001865 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001866 .context("Trying to insert the certificate.")?;
1867 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001868 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001869 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001870 tx,
1871 key_id.id(),
1872 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001873 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001874 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001875 )
1876 .context("Trying to insert the certificate chain.")?;
1877 }
1878 Self::insert_keyparameter_internal(tx, &key_id, params)
1879 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001880 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001881 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001882 .context("Trying to rebind alias.")?
1883 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001884 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001885 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001886 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001887 }
1888
Janis Danisevskis377d1002021-01-27 19:07:48 -08001889 /// Store a new certificate
1890 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1891 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001892 pub fn store_new_certificate(
1893 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001894 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001895 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001896 cert: &[u8],
1897 km_uuid: &Uuid,
1898 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001899 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1900
Janis Danisevskis377d1002021-01-27 19:07:48 -08001901 let (alias, domain, namespace) = match key {
1902 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1903 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1904 (alias, key.domain, nspace)
1905 }
1906 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001907 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1908 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001909 }
1910 };
1911 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001912 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001913 .context("Trying to create new key entry.")?;
1914
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001915 Self::set_blob_internal(
1916 tx,
1917 key_id.id(),
1918 SubComponentType::CERT_CHAIN,
1919 Some(cert),
1920 None,
1921 )
1922 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001923
1924 let mut metadata = KeyMetaData::new();
1925 metadata.add(KeyMetaEntry::CreationDate(
1926 DateTime::now().context("Trying to make creation time.")?,
1927 ));
1928
1929 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1930
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001931 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001932 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001933 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001934 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001935 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001936 }
1937
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001938 // Helper function loading the key_id given the key descriptor
1939 // tuple comprising domain, namespace, and alias.
1940 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001941 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001942 let alias = key
1943 .alias
1944 .as_ref()
1945 .map_or_else(|| Err(KsError::sys()), Ok)
1946 .context("In load_key_entry_id: Alias must be specified.")?;
1947 let mut stmt = tx
1948 .prepare(
1949 "SELECT id FROM persistent.keyentry
1950 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001951 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001952 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001953 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001954 AND alias = ?
1955 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001956 )
1957 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1958 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001959 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001960 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001961 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001962 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001963 .get(0)
1964 .context("Failed to unpack id.")
1965 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001966 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001967 }
1968
1969 /// This helper function completes the access tuple of a key, which is required
1970 /// to perform access control. The strategy depends on the `domain` field in the
1971 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001972 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001973 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001974 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001975 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001976 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001977 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001978 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001979 /// `namespace`.
1980 /// In each case the information returned is sufficient to perform the access
1981 /// check and the key id can be used to load further key artifacts.
1982 fn load_access_tuple(
1983 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001984 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001985 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001986 caller_uid: u32,
1987 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1988 match key.domain {
1989 // Domain App or SELinux. In this case we load the key_id from
1990 // the keyentry database for further loading of key components.
1991 // We already have the full access tuple to perform access control.
1992 // The only distinction is that we use the caller_uid instead
1993 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001994 // Domain::APP.
1995 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001996 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001997 if access_key.domain == Domain::APP {
1998 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001999 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002000 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002001 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002002
2003 Ok((key_id, access_key, None))
2004 }
2005
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002006 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002007 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002008 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002009 let mut stmt = tx
2010 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002011 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002012 WHERE grantee = ? AND id = ? AND
2013 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002014 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002015 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002016 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002017 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002018 .context("Domain:Grant: query failed.")?;
2019 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002020 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002021 let r =
2022 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002023 Ok((
2024 r.get(0).context("Failed to unpack key_id.")?,
2025 r.get(1).context("Failed to unpack access_vector.")?,
2026 ))
2027 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002028 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002029 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002030 }
2031
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002032 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002033 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002034 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002035 let (domain, namespace): (Domain, i64) = {
2036 let mut stmt = tx
2037 .prepare(
2038 "SELECT domain, namespace FROM persistent.keyentry
2039 WHERE
2040 id = ?
2041 AND state = ?;",
2042 )
2043 .context("Domain::KEY_ID: prepare statement failed")?;
2044 let mut rows = stmt
2045 .query(params![key.nspace, KeyLifeCycle::Live])
2046 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002047 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002048 let r =
2049 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002050 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002051 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002052 r.get(1).context("Failed to unpack namespace.")?,
2053 ))
2054 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002055 .context("Domain::KEY_ID.")?
2056 };
2057
2058 // We may use a key by id after loading it by grant.
2059 // In this case we have to check if the caller has a grant for this particular
2060 // key. We can skip this if we already know that the caller is the owner.
2061 // But we cannot know this if domain is anything but App. E.g. in the case
2062 // of Domain::SELINUX we have to speculatively check for grants because we have to
2063 // consult the SEPolicy before we know if the caller is the owner.
2064 let access_vector: Option<KeyPermSet> =
2065 if domain != Domain::APP || namespace != caller_uid as i64 {
2066 let access_vector: Option<i32> = tx
2067 .query_row(
2068 "SELECT access_vector FROM persistent.grant
2069 WHERE grantee = ? AND keyentryid = ?;",
2070 params![caller_uid as i64, key.nspace],
2071 |row| row.get(0),
2072 )
2073 .optional()
2074 .context("Domain::KEY_ID: query grant failed.")?;
2075 access_vector.map(|p| p.into())
2076 } else {
2077 None
2078 };
2079
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002080 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002081 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002082 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002083 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002084
Janis Danisevskis45760022021-01-19 16:34:10 -08002085 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002086 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002087 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002088 }
2089 }
2090
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002091 fn load_blob_components(
2092 key_id: i64,
2093 load_bits: KeyEntryLoadBits,
2094 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002095 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002096 let mut stmt = tx
2097 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002098 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002099 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2100 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002101 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002102
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002103 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002104
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002105 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002106 let mut cert_blob: Option<Vec<u8>> = None;
2107 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002108 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002109 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002110 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002111 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002112 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002113 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2114 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002115 key_blob = Some((
2116 row.get(0).context("Failed to extract key blob id.")?,
2117 row.get(2).context("Failed to extract key blob.")?,
2118 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002119 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002120 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002121 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002122 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002123 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002124 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002125 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002126 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002127 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002128 (SubComponentType::CERT, _, _)
2129 | (SubComponentType::CERT_CHAIN, _, _)
2130 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002131 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2132 }
2133 Ok(())
2134 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002135 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002136
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002137 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2138 Ok(Some((
2139 blob,
2140 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002141 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002142 )))
2143 })?;
2144
2145 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002146 }
2147
2148 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2149 let mut stmt = tx
2150 .prepare(
2151 "SELECT tag, data, security_level from persistent.keyparameter
2152 WHERE keyentryid = ?;",
2153 )
2154 .context("In load_key_parameters: prepare statement failed.")?;
2155
2156 let mut parameters: Vec<KeyParameter> = Vec::new();
2157
2158 let mut rows =
2159 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002160 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002161 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2162 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002163 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002164 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002165 .context("Failed to read KeyParameter.")?,
2166 );
2167 Ok(())
2168 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002169 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002170
2171 Ok(parameters)
2172 }
2173
Qi Wub9433b52020-12-01 14:52:46 +08002174 /// Decrements the usage count of a limited use key. This function first checks whether the
2175 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2176 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2177 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002178 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002179 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2180
Qi Wub9433b52020-12-01 14:52:46 +08002181 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2182 let limit: Option<i32> = tx
2183 .query_row(
2184 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2185 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2186 |row| row.get(0),
2187 )
2188 .optional()
2189 .context("Trying to load usage count")?;
2190
2191 let limit = limit
2192 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2193 .context("The Key no longer exists. Key is exhausted.")?;
2194
2195 tx.execute(
2196 "UPDATE persistent.keyparameter
2197 SET data = data - 1
2198 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2199 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2200 )
2201 .context("Failed to update key usage count.")?;
2202
2203 match limit {
2204 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002205 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002206 .context("Trying to mark limited use key for deletion."),
2207 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002208 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002209 }
2210 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002211 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002212 }
2213
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002214 /// Load a key entry by the given key descriptor.
2215 /// It uses the `check_permission` callback to verify if the access is allowed
2216 /// given the key access tuple read from the database using `load_access_tuple`.
2217 /// With `load_bits` the caller may specify which blobs shall be loaded from
2218 /// the blob database.
2219 pub fn load_key_entry(
2220 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002221 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002222 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002223 load_bits: KeyEntryLoadBits,
2224 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002225 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2226 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002227 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2228
Janis Danisevskis66784c42021-01-27 08:40:25 -08002229 loop {
2230 match self.load_key_entry_internal(
2231 key,
2232 key_type,
2233 load_bits,
2234 caller_uid,
2235 &check_permission,
2236 ) {
2237 Ok(result) => break Ok(result),
2238 Err(e) => {
2239 if Self::is_locked_error(&e) {
2240 std::thread::sleep(std::time::Duration::from_micros(500));
2241 continue;
2242 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002243 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002244 }
2245 }
2246 }
2247 }
2248 }
2249
2250 fn load_key_entry_internal(
2251 &mut self,
2252 key: &KeyDescriptor,
2253 key_type: KeyType,
2254 load_bits: KeyEntryLoadBits,
2255 caller_uid: u32,
2256 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002257 ) -> Result<(KeyIdGuard, KeyEntry)> {
2258 // KEY ID LOCK 1/2
2259 // If we got a key descriptor with a key id we can get the lock right away.
2260 // Otherwise we have to defer it until we know the key id.
2261 let key_id_guard = match key.domain {
2262 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2263 _ => None,
2264 };
2265
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002266 let tx = self
2267 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002268 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002269 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002270
2271 // Load the key_id and complete the access control tuple.
2272 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002273 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002274
2275 // Perform access control. It is vital that we return here if the permission is denied.
2276 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002277 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002278
Janis Danisevskisaec14592020-11-12 09:41:49 -08002279 // KEY ID LOCK 2/2
2280 // If we did not get a key id lock by now, it was because we got a key descriptor
2281 // without a key id. At this point we got the key id, so we can try and get a lock.
2282 // However, we cannot block here, because we are in the middle of the transaction.
2283 // So first we try to get the lock non blocking. If that fails, we roll back the
2284 // transaction and block until we get the lock. After we successfully got the lock,
2285 // we start a new transaction and load the access tuple again.
2286 //
2287 // We don't need to perform access control again, because we already established
2288 // that the caller had access to the given key. But we need to make sure that the
2289 // key id still exists. So we have to load the key entry by key id this time.
2290 let (key_id_guard, tx) = match key_id_guard {
2291 None => match KEY_ID_LOCK.try_get(key_id) {
2292 None => {
2293 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002294 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002295
Janis Danisevskisaec14592020-11-12 09:41:49 -08002296 // Block until we have a key id lock.
2297 let key_id_guard = KEY_ID_LOCK.get(key_id);
2298
2299 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002300 let tx = self
2301 .conn
2302 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002303 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002304
2305 Self::load_access_tuple(
2306 &tx,
2307 // This time we have to load the key by the retrieved key id, because the
2308 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002309 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002310 domain: Domain::KEY_ID,
2311 nspace: key_id,
2312 ..Default::default()
2313 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002314 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002315 caller_uid,
2316 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002317 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002318 (key_id_guard, tx)
2319 }
2320 Some(l) => (l, tx),
2321 },
2322 Some(key_id_guard) => (key_id_guard, tx),
2323 };
2324
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002325 let key_entry =
2326 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002327
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002328 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002329
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002330 Ok((key_id_guard, key_entry))
2331 }
2332
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002333 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002334 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002335 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2336 .context("Trying to delete keyentry.")?;
2337 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2338 .context("Trying to delete keymetadata.")?;
2339 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2340 .context("Trying to delete keyparameters.")?;
2341 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2342 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002343 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002344 }
2345
2346 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002347 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002348 pub fn unbind_key(
2349 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002350 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002351 key_type: KeyType,
2352 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002353 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002354 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002355 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2356
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002357 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2358 let (key_id, access_key_descriptor, access_vector) =
2359 Self::load_access_tuple(tx, key, key_type, caller_uid)
2360 .context("Trying to get access tuple.")?;
2361
2362 // Perform access control. It is vital that we return here if the permission is denied.
2363 // So do not touch that '?' at the end.
2364 check_permission(&access_key_descriptor, access_vector)
2365 .context("While checking permission.")?;
2366
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002367 Self::mark_unreferenced(tx, key_id)
2368 .map(|need_gc| (need_gc, ()))
2369 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002370 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002371 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002372 }
2373
Max Bires8e93d2b2021-01-14 13:17:59 -08002374 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2375 tx.query_row(
2376 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2377 params![key_id],
2378 |row| row.get(0),
2379 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002380 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002381 }
2382
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002383 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2384 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2385 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002386 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2387
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002388 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002389 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002390 }
2391 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2392 tx.execute(
2393 "DELETE FROM persistent.keymetadata
2394 WHERE keyentryid IN (
2395 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002396 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002397 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002398 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002399 )
2400 .context("Trying to delete keymetadata.")?;
2401 tx.execute(
2402 "DELETE FROM persistent.keyparameter
2403 WHERE keyentryid IN (
2404 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002405 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002406 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002407 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002408 )
2409 .context("Trying to delete keyparameters.")?;
2410 tx.execute(
2411 "DELETE FROM persistent.grant
2412 WHERE keyentryid IN (
2413 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002414 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002415 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002416 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002417 )
2418 .context("Trying to delete grants.")?;
2419 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002420 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002421 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2422 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002423 )
2424 .context("Trying to delete keyentry.")?;
2425 Ok(()).need_gc()
2426 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002427 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002428 }
2429
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002430 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2431 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2432 {
2433 tx.execute(
2434 "DELETE FROM persistent.keymetadata
2435 WHERE keyentryid IN (
2436 SELECT id FROM persistent.keyentry
2437 WHERE state = ?
2438 );",
2439 params![KeyLifeCycle::Unreferenced],
2440 )
2441 .context("Trying to delete keymetadata.")?;
2442 tx.execute(
2443 "DELETE FROM persistent.keyparameter
2444 WHERE keyentryid IN (
2445 SELECT id FROM persistent.keyentry
2446 WHERE state = ?
2447 );",
2448 params![KeyLifeCycle::Unreferenced],
2449 )
2450 .context("Trying to delete keyparameters.")?;
2451 tx.execute(
2452 "DELETE FROM persistent.grant
2453 WHERE keyentryid IN (
2454 SELECT id FROM persistent.keyentry
2455 WHERE state = ?
2456 );",
2457 params![KeyLifeCycle::Unreferenced],
2458 )
2459 .context("Trying to delete grants.")?;
2460 tx.execute(
2461 "DELETE FROM persistent.keyentry
2462 WHERE state = ?;",
2463 params![KeyLifeCycle::Unreferenced],
2464 )
2465 .context("Trying to delete keyentry.")?;
2466 Result::<()>::Ok(())
2467 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002468 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002469 }
2470
Hasini Gunasingheda895552021-01-27 19:34:37 +00002471 /// Delete the keys created on behalf of the user, denoted by the user id.
2472 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2473 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2474 /// The caller of this function should notify the gc if the returned value is true.
2475 pub fn unbind_keys_for_user(
2476 &mut self,
2477 user_id: u32,
2478 keep_non_super_encrypted_keys: bool,
2479 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002480 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2481
Hasini Gunasingheda895552021-01-27 19:34:37 +00002482 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2483 let mut stmt = tx
2484 .prepare(&format!(
2485 "SELECT id from persistent.keyentry
2486 WHERE (
2487 key_type = ?
2488 AND domain = ?
2489 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2490 AND state = ?
2491 ) OR (
2492 key_type = ?
2493 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002494 AND state = ?
2495 );",
2496 aid_user_offset = AID_USER_OFFSET
2497 ))
2498 .context(concat!(
2499 "In unbind_keys_for_user. ",
2500 "Failed to prepare the query to find the keys created by apps."
2501 ))?;
2502
2503 let mut rows = stmt
2504 .query(params![
2505 // WHERE client key:
2506 KeyType::Client,
2507 Domain::APP.0 as u32,
2508 user_id,
2509 KeyLifeCycle::Live,
2510 // OR super key:
2511 KeyType::Super,
2512 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002513 KeyLifeCycle::Live
2514 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002515 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002516
2517 let mut key_ids: Vec<i64> = Vec::new();
2518 db_utils::with_rows_extract_all(&mut rows, |row| {
2519 key_ids
2520 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2521 Ok(())
2522 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002523 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002524
2525 let mut notify_gc = false;
2526 for key_id in key_ids {
2527 if keep_non_super_encrypted_keys {
2528 // Load metadata and filter out non-super-encrypted keys.
2529 if let (_, Some((_, blob_metadata)), _, _) =
2530 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002531 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002532 {
2533 if blob_metadata.encrypted_by().is_none() {
2534 continue;
2535 }
2536 }
2537 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002538 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002539 .context("In unbind_keys_for_user.")?
2540 || notify_gc;
2541 }
2542 Ok(()).do_gc(notify_gc)
2543 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002544 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002545 }
2546
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002547 fn load_key_components(
2548 tx: &Transaction,
2549 load_bits: KeyEntryLoadBits,
2550 key_id: i64,
2551 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002552 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002553
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002554 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002555 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002556
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002557 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002558 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002559
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002560 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002561 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002562
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002563 Ok(KeyEntry {
2564 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002565 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002566 cert: cert_blob,
2567 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002568 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002569 parameters,
2570 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002571 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002572 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002573 }
2574
Eran Messeri24f31972023-01-25 17:00:33 +00002575 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2576 /// aliases are greater than the specified 'start_past_alias'. If no value
2577 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002578 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002579 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002580 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002581 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002582 &mut self,
2583 domain: Domain,
2584 namespace: i64,
2585 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002586 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002587 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002588 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002589
Eran Messeri24f31972023-01-25 17:00:33 +00002590 let query = format!(
2591 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002592 WHERE domain = ?
2593 AND namespace = ?
2594 AND alias IS NOT NULL
2595 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002596 AND key_type = ?
2597 {}
2598 ORDER BY alias ASC;",
2599 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2600 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002601
Eran Messeri24f31972023-01-25 17:00:33 +00002602 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2603 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2604
2605 let mut rows = match start_past_alias {
2606 Some(past_alias) => stmt
2607 .query(params![
2608 domain.0 as u32,
2609 namespace,
2610 KeyLifeCycle::Live,
2611 key_type,
2612 past_alias
2613 ])
2614 .context(ks_err!("Failed to query."))?,
2615 None => stmt
2616 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2617 .context(ks_err!("Failed to query."))?,
2618 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002619
Janis Danisevskis66784c42021-01-27 08:40:25 -08002620 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2621 db_utils::with_rows_extract_all(&mut rows, |row| {
2622 descriptors.push(KeyDescriptor {
2623 domain,
2624 nspace: namespace,
2625 alias: Some(row.get(0).context("Trying to extract alias.")?),
2626 blob: None,
2627 });
2628 Ok(())
2629 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002630 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002631 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002632 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002633 }
2634
Eran Messeri24f31972023-01-25 17:00:33 +00002635 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2636 /// Domain must be APP or SELINUX, the caller must make sure of that.
2637 pub fn count_keys(
2638 &mut self,
2639 domain: Domain,
2640 namespace: i64,
2641 key_type: KeyType,
2642 ) -> Result<usize> {
2643 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2644
2645 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2646 tx.query_row(
2647 "SELECT COUNT(alias) FROM persistent.keyentry
2648 WHERE domain = ?
2649 AND namespace = ?
2650 AND alias IS NOT NULL
2651 AND state = ?
2652 AND key_type = ?;",
2653 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2654 |row| row.get(0),
2655 )
2656 .context(ks_err!("Failed to count number of keys."))
2657 .no_gc()
2658 })?;
2659 Ok(num_keys)
2660 }
2661
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002662 /// Adds a grant to the grant table.
2663 /// Like `load_key_entry` this function loads the access tuple before
2664 /// it uses the callback for a permission check. Upon success,
2665 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2666 /// grant table. The new row will have a randomized id, which is used as
2667 /// grant id in the namespace field of the resulting KeyDescriptor.
2668 pub fn grant(
2669 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002670 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002671 caller_uid: u32,
2672 grantee_uid: u32,
2673 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002674 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002675 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002676 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2677
Janis Danisevskis66784c42021-01-27 08:40:25 -08002678 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2679 // Load the key_id and complete the access control tuple.
2680 // We ignore the access vector here because grants cannot be granted.
2681 // The access vector returned here expresses the permissions the
2682 // grantee has if key.domain == Domain::GRANT. But this vector
2683 // cannot include the grant permission by design, so there is no way the
2684 // subsequent permission check can pass.
2685 // We could check key.domain == Domain::GRANT and fail early.
2686 // But even if we load the access tuple by grant here, the permission
2687 // check denies the attempt to create a grant by grant descriptor.
2688 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002689 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002690
Janis Danisevskis66784c42021-01-27 08:40:25 -08002691 // Perform access control. It is vital that we return here if the permission
2692 // was denied. So do not touch that '?' at the end of the line.
2693 // This permission check checks if the caller has the grant permission
2694 // for the given key and in addition to all of the permissions
2695 // expressed in `access_vector`.
2696 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002697 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002698
Janis Danisevskis66784c42021-01-27 08:40:25 -08002699 let grant_id = if let Some(grant_id) = tx
2700 .query_row(
2701 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002702 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002703 params![key_id, grantee_uid],
2704 |row| row.get(0),
2705 )
2706 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002707 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002708 {
2709 tx.execute(
2710 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002711 SET access_vector = ?
2712 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002713 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002714 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002715 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002716 grant_id
2717 } else {
2718 Self::insert_with_retry(|id| {
2719 tx.execute(
2720 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2721 VALUES (?, ?, ?, ?);",
2722 params![id, grantee_uid, key_id, i32::from(access_vector)],
2723 )
2724 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002725 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002726 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002727
Janis Danisevskis66784c42021-01-27 08:40:25 -08002728 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002729 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002730 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002731 }
2732
2733 /// This function checks permissions like `grant` and `load_key_entry`
2734 /// before removing a grant from the grant table.
2735 pub fn ungrant(
2736 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002737 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002738 caller_uid: u32,
2739 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002740 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002741 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002742 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2743
Janis Danisevskis66784c42021-01-27 08:40:25 -08002744 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2745 // Load the key_id and complete the access control tuple.
2746 // We ignore the access vector here because grants cannot be granted.
2747 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002748 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002749
Janis Danisevskis66784c42021-01-27 08:40:25 -08002750 // Perform access control. We must return here if the permission
2751 // was denied. So do not touch the '?' at the end of this line.
2752 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002753 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002754
Janis Danisevskis66784c42021-01-27 08:40:25 -08002755 tx.execute(
2756 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002757 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002758 params![key_id, grantee_uid],
2759 )
2760 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002761
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002762 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002763 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002764 }
2765
Joel Galenson845f74b2020-09-09 14:11:55 -07002766 // Generates a random id and passes it to the given function, which will
2767 // try to insert it into a database. If that insertion fails, retry;
2768 // otherwise return the id.
2769 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2770 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002771 let newid: i64 = match random() {
2772 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2773 i => i,
2774 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002775 match inserter(newid) {
2776 // If the id already existed, try again.
2777 Err(rusqlite::Error::SqliteFailure(
2778 libsqlite3_sys::Error {
2779 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2780 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2781 },
2782 _,
2783 )) => (),
2784 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002785 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002786 }
2787 _ => return Ok(newid),
2788 }
2789 }
2790 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002791
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002792 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2793 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
2794 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
2795 auth_token.clone(),
2796 MonotonicRawTime::now(),
2797 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002798 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002799
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002800 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002801 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002802 where
2803 F: Fn(&AuthTokenEntry) -> bool,
2804 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002805 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002806 }
2807
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002808 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002809 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
2810 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002811 }
2812
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002813 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002814 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
2815 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002816 }
2817
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002818 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002819 fn get_last_off_body(&self) -> MonotonicRawTime {
2820 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002821 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002822
2823 /// Load descriptor of a key by key id
2824 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2825 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2826
2827 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2828 tx.query_row(
2829 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2830 params![key_id],
2831 |row| {
2832 Ok(KeyDescriptor {
2833 domain: Domain(row.get(0)?),
2834 nspace: row.get(1)?,
2835 alias: row.get(2)?,
2836 blob: None,
2837 })
2838 },
2839 )
2840 .optional()
2841 .context("Trying to load key descriptor")
2842 .no_gc()
2843 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002844 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002845 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002846}
2847
2848#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002849pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002850
2851 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002852 use crate::key_parameter::{
2853 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2854 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2855 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002856 use crate::key_perm_set;
2857 use crate::permission::{KeyPerm, KeyPermSet};
Eric Biggers673d34a2023-10-18 01:54:18 +00002858 use crate::super_key::{SuperKeyManager, USER_AFTER_FIRST_UNLOCK_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002859 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002860 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2861 HardwareAuthToken::HardwareAuthToken,
2862 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002863 };
2864 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002865 Timestamp::Timestamp,
2866 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002867 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07002868 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002869 use std::collections::BTreeMap;
2870 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002871 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002872 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002873 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002874 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002875 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002876 #[cfg(disabled)]
2877 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002878
Seth Moore7ee79f92021-12-07 11:42:49 -08002879 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002880 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002881
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002882 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002883 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002884 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002885 })?;
2886 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002887 }
2888
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002889 fn rebind_alias(
2890 db: &mut KeystoreDB,
2891 newid: &KeyIdGuard,
2892 alias: &str,
2893 domain: Domain,
2894 namespace: i64,
2895 ) -> Result<bool> {
2896 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002897 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002898 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002899 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002900 }
2901
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002902 #[test]
2903 fn datetime() -> Result<()> {
2904 let conn = Connection::open_in_memory()?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002905 conn.execute("CREATE TABLE test (ts DATETIME);", [])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002906 let now = SystemTime::now();
2907 let duration = Duration::from_secs(1000);
2908 let then = now.checked_sub(duration).unwrap();
2909 let soon = now.checked_add(duration).unwrap();
2910 conn.execute(
2911 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2912 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2913 )?;
2914 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00002915 let mut rows = stmt.query([])?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002916 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2917 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2918 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2919 assert!(rows.next()?.is_none());
2920 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2921 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2922 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2923 Ok(())
2924 }
2925
Joel Galenson0891bc12020-07-20 10:37:03 -07002926 // Ensure that we're using the "injected" random function, not the real one.
2927 #[test]
2928 fn test_mocked_random() {
2929 let rand1 = random();
2930 let rand2 = random();
2931 let rand3 = random();
2932 if rand1 == rand2 {
2933 assert_eq!(rand2 + 1, rand3);
2934 } else {
2935 assert_eq!(rand1 + 1, rand2);
2936 assert_eq!(rand2, rand3);
2937 }
2938 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002939
Joel Galenson26f4d012020-07-17 14:57:21 -07002940 // Test that we have the correct tables.
2941 #[test]
2942 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002943 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002944 let tables = db
2945 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002946 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002947 .query_map(params![], |row| row.get(0))?
2948 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002949 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002950 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002951 assert_eq!(tables[1], "blobmetadata");
2952 assert_eq!(tables[2], "grant");
2953 assert_eq!(tables[3], "keyentry");
2954 assert_eq!(tables[4], "keymetadata");
2955 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07002956 Ok(())
2957 }
2958
2959 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002960 fn test_auth_token_table_invariant() -> Result<()> {
2961 let mut db = new_test_db()?;
2962 let auth_token1 = HardwareAuthToken {
2963 challenge: i64::MAX,
2964 userId: 200,
2965 authenticatorId: 200,
2966 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2967 timestamp: Timestamp { milliSeconds: 500 },
2968 mac: String::from("mac").into_bytes(),
2969 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002970 db.insert_auth_token(&auth_token1);
2971 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002972 assert_eq!(auth_tokens_returned.len(), 1);
2973
2974 // insert another auth token with the same values for the columns in the UNIQUE constraint
2975 // of the auth token table and different value for timestamp
2976 let auth_token2 = HardwareAuthToken {
2977 challenge: i64::MAX,
2978 userId: 200,
2979 authenticatorId: 200,
2980 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2981 timestamp: Timestamp { milliSeconds: 600 },
2982 mac: String::from("mac").into_bytes(),
2983 };
2984
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002985 db.insert_auth_token(&auth_token2);
2986 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002987 assert_eq!(auth_tokens_returned.len(), 1);
2988
2989 if let Some(auth_token) = auth_tokens_returned.pop() {
2990 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
2991 }
2992
2993 // insert another auth token with the different values for the columns in the UNIQUE
2994 // constraint of the auth token table
2995 let auth_token3 = HardwareAuthToken {
2996 challenge: i64::MAX,
2997 userId: 201,
2998 authenticatorId: 200,
2999 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3000 timestamp: Timestamp { milliSeconds: 600 },
3001 mac: String::from("mac").into_bytes(),
3002 };
3003
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003004 db.insert_auth_token(&auth_token3);
3005 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003006 assert_eq!(auth_tokens_returned.len(), 2);
3007
3008 Ok(())
3009 }
3010
3011 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003012 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3013 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003014 }
3015
3016 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003017 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003018 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003019 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003020
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003021 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003022 let entries = get_keyentry(&db)?;
3023 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003024
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003025 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003026
3027 let entries_new = get_keyentry(&db)?;
3028 assert_eq!(entries, entries_new);
3029 Ok(())
3030 }
3031
3032 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003033 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003034 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3035 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003036 }
3037
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003038 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003039
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003040 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3041 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003042
3043 let entries = get_keyentry(&db)?;
3044 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003045 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3046 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003047
3048 // Test that we must pass in a valid Domain.
3049 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003050 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003051 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003052 );
3053 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003054 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003055 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson0891bc12020-07-20 10:37:03 -07003056 );
3057 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003058 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003059 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003060 );
3061
3062 Ok(())
3063 }
3064
Joel Galenson33c04ad2020-08-03 11:04:38 -07003065 #[test]
3066 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003067 fn extractor(
3068 ke: &KeyEntryRow,
3069 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3070 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003071 }
3072
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003073 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003074 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3075 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003076 let entries = get_keyentry(&db)?;
3077 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003078 assert_eq!(
3079 extractor(&entries[0]),
3080 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3081 );
3082 assert_eq!(
3083 extractor(&entries[1]),
3084 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3085 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003086
3087 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003088 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003089 let entries = get_keyentry(&db)?;
3090 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003091 assert_eq!(
3092 extractor(&entries[0]),
3093 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3094 );
3095 assert_eq!(
3096 extractor(&entries[1]),
3097 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3098 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003099
3100 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003101 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003102 let entries = get_keyentry(&db)?;
3103 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003104 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3105 assert_eq!(
3106 extractor(&entries[1]),
3107 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3108 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003109
3110 // Test that we must pass in a valid Domain.
3111 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003112 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003113 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003114 );
3115 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003116 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003117 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003118 );
3119 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003120 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003121 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003122 );
3123
3124 // Test that we correctly handle setting an alias for something that does not exist.
3125 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003126 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003127 "Expected to update a single entry but instead updated 0",
3128 );
3129 // Test that we correctly abort the transaction in this case.
3130 let entries = get_keyentry(&db)?;
3131 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003132 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3133 assert_eq!(
3134 extractor(&entries[1]),
3135 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3136 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003137
3138 Ok(())
3139 }
3140
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003141 #[test]
3142 fn test_grant_ungrant() -> Result<()> {
3143 const CALLER_UID: u32 = 15;
3144 const GRANTEE_UID: u32 = 12;
3145 const SELINUX_NAMESPACE: i64 = 7;
3146
3147 let mut db = new_test_db()?;
3148 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003149 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3150 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3151 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003152 )?;
3153 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003154 domain: super::Domain::APP,
3155 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003156 alias: Some("key".to_string()),
3157 blob: None,
3158 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003159 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3160 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003161
3162 // Reset totally predictable random number generator in case we
3163 // are not the first test running on this thread.
3164 reset_random();
3165 let next_random = 0i64;
3166
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003167 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003168 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003169 assert_eq!(*a, PVEC1);
3170 assert_eq!(
3171 *k,
3172 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003173 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003174 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003175 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003176 alias: Some("key".to_string()),
3177 blob: None,
3178 }
3179 );
3180 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003181 })
3182 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003183
3184 assert_eq!(
3185 app_granted_key,
3186 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003187 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003188 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003189 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003190 alias: None,
3191 blob: None,
3192 }
3193 );
3194
3195 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003196 domain: super::Domain::SELINUX,
3197 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003198 alias: Some("yek".to_string()),
3199 blob: None,
3200 };
3201
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003202 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003203 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003204 assert_eq!(*a, PVEC1);
3205 assert_eq!(
3206 *k,
3207 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003208 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003209 // namespace must be the supplied SELinux
3210 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003211 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003212 alias: Some("yek".to_string()),
3213 blob: None,
3214 }
3215 );
3216 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003217 })
3218 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003219
3220 assert_eq!(
3221 selinux_granted_key,
3222 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003223 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003224 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003225 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003226 alias: None,
3227 blob: None,
3228 }
3229 );
3230
3231 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003232 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003233 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003234 assert_eq!(*a, PVEC2);
3235 assert_eq!(
3236 *k,
3237 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003238 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003239 // namespace must be the supplied SELinux
3240 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003241 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003242 alias: Some("yek".to_string()),
3243 blob: None,
3244 }
3245 );
3246 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003247 })
3248 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003249
3250 assert_eq!(
3251 selinux_granted_key,
3252 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003253 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003254 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003255 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003256 alias: None,
3257 blob: None,
3258 }
3259 );
3260
3261 {
3262 // Limiting scope of stmt, because it borrows db.
3263 let mut stmt = db
3264 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003265 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003266 let mut rows = stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>([], |row| {
3267 Ok((row.get(0)?, row.get(1)?, row.get(2)?, KeyPermSet::from(row.get::<_, i32>(3)?)))
3268 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003269
3270 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003271 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003272 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003273 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003274 assert!(rows.next().is_none());
3275 }
3276
3277 debug_dump_keyentry_table(&mut db)?;
3278 println!("app_key {:?}", app_key);
3279 println!("selinux_key {:?}", selinux_key);
3280
Janis Danisevskis66784c42021-01-27 08:40:25 -08003281 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3282 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003283
3284 Ok(())
3285 }
3286
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003287 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003288 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3289 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3290
3291 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003292 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003293 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003294 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003295 let mut blob_metadata = BlobMetaData::new();
3296 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3297 db.set_blob(
3298 &key_id,
3299 SubComponentType::KEY_BLOB,
3300 Some(TEST_KEY_BLOB),
3301 Some(&blob_metadata),
3302 )?;
3303 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3304 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003305 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003306
3307 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003308 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003309 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003310 )?;
3311 let mut rows = stmt
Andrew Walbran78abb1e2023-05-30 16:20:56 +00003312 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>([], |row| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003313 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003314 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003315 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003316 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003317 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003318 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003319 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003320 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003321
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003322 drop(rows);
3323 drop(stmt);
3324
3325 assert_eq!(
3326 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3327 BlobMetaData::load_from_db(id, tx).no_gc()
3328 })
3329 .expect("Should find blob metadata."),
3330 blob_metadata
3331 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003332 Ok(())
3333 }
3334
3335 static TEST_ALIAS: &str = "my super duper key";
3336
3337 #[test]
3338 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3339 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003340 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003341 .context("test_insert_and_load_full_keyentry_domain_app")?
3342 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003343 let (_key_guard, key_entry) = db
3344 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003345 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003346 domain: Domain::APP,
3347 nspace: 0,
3348 alias: Some(TEST_ALIAS.to_string()),
3349 blob: None,
3350 },
3351 KeyType::Client,
3352 KeyEntryLoadBits::BOTH,
3353 1,
3354 |_k, _av| Ok(()),
3355 )
3356 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003357 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003358
3359 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003360 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003361 domain: Domain::APP,
3362 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003363 alias: Some(TEST_ALIAS.to_string()),
3364 blob: None,
3365 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003366 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003367 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003368 |_, _| Ok(()),
3369 )
3370 .unwrap();
3371
3372 assert_eq!(
3373 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3374 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003375 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003376 domain: Domain::APP,
3377 nspace: 0,
3378 alias: Some(TEST_ALIAS.to_string()),
3379 blob: None,
3380 },
3381 KeyType::Client,
3382 KeyEntryLoadBits::NONE,
3383 1,
3384 |_k, _av| Ok(()),
3385 )
3386 .unwrap_err()
3387 .root_cause()
3388 .downcast_ref::<KsError>()
3389 );
3390
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003391 Ok(())
3392 }
3393
3394 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003395 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3396 let mut db = new_test_db()?;
3397
3398 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003399 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003400 domain: Domain::APP,
3401 nspace: 1,
3402 alias: Some(TEST_ALIAS.to_string()),
3403 blob: None,
3404 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003405 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003406 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003407 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003408 )
3409 .expect("Trying to insert cert.");
3410
3411 let (_key_guard, mut key_entry) = db
3412 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003413 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003414 domain: Domain::APP,
3415 nspace: 1,
3416 alias: Some(TEST_ALIAS.to_string()),
3417 blob: None,
3418 },
3419 KeyType::Client,
3420 KeyEntryLoadBits::PUBLIC,
3421 1,
3422 |_k, _av| Ok(()),
3423 )
3424 .expect("Trying to read certificate entry.");
3425
3426 assert!(key_entry.pure_cert());
3427 assert!(key_entry.cert().is_none());
3428 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3429
3430 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003431 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003432 domain: Domain::APP,
3433 nspace: 1,
3434 alias: Some(TEST_ALIAS.to_string()),
3435 blob: None,
3436 },
3437 KeyType::Client,
3438 1,
3439 |_, _| Ok(()),
3440 )
3441 .unwrap();
3442
3443 assert_eq!(
3444 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3445 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003446 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003447 domain: Domain::APP,
3448 nspace: 1,
3449 alias: Some(TEST_ALIAS.to_string()),
3450 blob: None,
3451 },
3452 KeyType::Client,
3453 KeyEntryLoadBits::NONE,
3454 1,
3455 |_k, _av| Ok(()),
3456 )
3457 .unwrap_err()
3458 .root_cause()
3459 .downcast_ref::<KsError>()
3460 );
3461
3462 Ok(())
3463 }
3464
3465 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003466 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3467 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003468 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003469 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3470 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003471 let (_key_guard, key_entry) = db
3472 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003473 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003474 domain: Domain::SELINUX,
3475 nspace: 1,
3476 alias: Some(TEST_ALIAS.to_string()),
3477 blob: None,
3478 },
3479 KeyType::Client,
3480 KeyEntryLoadBits::BOTH,
3481 1,
3482 |_k, _av| Ok(()),
3483 )
3484 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003485 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003486
3487 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003488 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003489 domain: Domain::SELINUX,
3490 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003491 alias: Some(TEST_ALIAS.to_string()),
3492 blob: None,
3493 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003494 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003495 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003496 |_, _| Ok(()),
3497 )
3498 .unwrap();
3499
3500 assert_eq!(
3501 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3502 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003503 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003504 domain: Domain::SELINUX,
3505 nspace: 1,
3506 alias: Some(TEST_ALIAS.to_string()),
3507 blob: None,
3508 },
3509 KeyType::Client,
3510 KeyEntryLoadBits::NONE,
3511 1,
3512 |_k, _av| Ok(()),
3513 )
3514 .unwrap_err()
3515 .root_cause()
3516 .downcast_ref::<KsError>()
3517 );
3518
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003519 Ok(())
3520 }
3521
3522 #[test]
3523 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3524 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003525 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003526 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3527 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003528 let (_, key_entry) = db
3529 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003530 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003531 KeyType::Client,
3532 KeyEntryLoadBits::BOTH,
3533 1,
3534 |_k, _av| Ok(()),
3535 )
3536 .unwrap();
3537
Qi Wub9433b52020-12-01 14:52:46 +08003538 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003539
3540 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003541 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003542 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003543 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003544 |_, _| Ok(()),
3545 )
3546 .unwrap();
3547
3548 assert_eq!(
3549 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3550 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003551 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003552 KeyType::Client,
3553 KeyEntryLoadBits::NONE,
3554 1,
3555 |_k, _av| Ok(()),
3556 )
3557 .unwrap_err()
3558 .root_cause()
3559 .downcast_ref::<KsError>()
3560 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003561
3562 Ok(())
3563 }
3564
3565 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003566 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3567 let mut db = new_test_db()?;
3568 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3569 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3570 .0;
3571 // Update the usage count of the limited use key.
3572 db.check_and_update_key_usage_count(key_id)?;
3573
3574 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003575 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003576 KeyType::Client,
3577 KeyEntryLoadBits::BOTH,
3578 1,
3579 |_k, _av| Ok(()),
3580 )?;
3581
3582 // The usage count is decremented now.
3583 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3584
3585 Ok(())
3586 }
3587
3588 #[test]
3589 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3590 let mut db = new_test_db()?;
3591 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3592 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3593 .0;
3594 // Update the usage count of the limited use key.
3595 db.check_and_update_key_usage_count(key_id).expect(concat!(
3596 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3597 "This should succeed."
3598 ));
3599
3600 // Try to update the exhausted limited use key.
3601 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3602 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3603 "This should fail."
3604 ));
3605 assert_eq!(
3606 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3607 e.root_cause().downcast_ref::<KsError>().unwrap()
3608 );
3609
3610 Ok(())
3611 }
3612
3613 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003614 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3615 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003616 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003617 .context("test_insert_and_load_full_keyentry_from_grant")?
3618 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003619
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003620 let granted_key = db
3621 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003622 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003623 domain: Domain::APP,
3624 nspace: 0,
3625 alias: Some(TEST_ALIAS.to_string()),
3626 blob: None,
3627 },
3628 1,
3629 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003630 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003631 |_k, _av| Ok(()),
3632 )
3633 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003634
3635 debug_dump_grant_table(&mut db)?;
3636
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003637 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003638 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3639 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003640 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003641 Ok(())
3642 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003643 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003644
Qi Wub9433b52020-12-01 14:52:46 +08003645 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003646
Janis Danisevskis66784c42021-01-27 08:40:25 -08003647 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003648
3649 assert_eq!(
3650 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3651 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003652 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003653 KeyType::Client,
3654 KeyEntryLoadBits::NONE,
3655 2,
3656 |_k, _av| Ok(()),
3657 )
3658 .unwrap_err()
3659 .root_cause()
3660 .downcast_ref::<KsError>()
3661 );
3662
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003663 Ok(())
3664 }
3665
Janis Danisevskis45760022021-01-19 16:34:10 -08003666 // This test attempts to load a key by key id while the caller is not the owner
3667 // but a grant exists for the given key and the caller.
3668 #[test]
3669 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3670 let mut db = new_test_db()?;
3671 const OWNER_UID: u32 = 1u32;
3672 const GRANTEE_UID: u32 = 2u32;
3673 const SOMEONE_ELSE_UID: u32 = 3u32;
3674 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3675 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3676 .0;
3677
3678 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003679 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003680 domain: Domain::APP,
3681 nspace: 0,
3682 alias: Some(TEST_ALIAS.to_string()),
3683 blob: None,
3684 },
3685 OWNER_UID,
3686 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003687 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003688 |_k, _av| Ok(()),
3689 )
3690 .unwrap();
3691
3692 debug_dump_grant_table(&mut db)?;
3693
3694 let id_descriptor =
3695 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3696
3697 let (_, key_entry) = db
3698 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003699 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003700 KeyType::Client,
3701 KeyEntryLoadBits::BOTH,
3702 GRANTEE_UID,
3703 |k, av| {
3704 assert_eq!(Domain::APP, k.domain);
3705 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003706 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003707 Ok(())
3708 },
3709 )
3710 .unwrap();
3711
3712 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3713
3714 let (_, key_entry) = db
3715 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003716 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003717 KeyType::Client,
3718 KeyEntryLoadBits::BOTH,
3719 SOMEONE_ELSE_UID,
3720 |k, av| {
3721 assert_eq!(Domain::APP, k.domain);
3722 assert_eq!(OWNER_UID as i64, k.nspace);
3723 assert!(av.is_none());
3724 Ok(())
3725 },
3726 )
3727 .unwrap();
3728
3729 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3730
Janis Danisevskis66784c42021-01-27 08:40:25 -08003731 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003732
3733 assert_eq!(
3734 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3735 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003736 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003737 KeyType::Client,
3738 KeyEntryLoadBits::NONE,
3739 GRANTEE_UID,
3740 |_k, _av| Ok(()),
3741 )
3742 .unwrap_err()
3743 .root_cause()
3744 .downcast_ref::<KsError>()
3745 );
3746
3747 Ok(())
3748 }
3749
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003750 // Creates a key migrates it to a different location and then tries to access it by the old
3751 // and new location.
3752 #[test]
3753 fn test_migrate_key_app_to_app() -> Result<()> {
3754 let mut db = new_test_db()?;
3755 const SOURCE_UID: u32 = 1u32;
3756 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003757 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3758 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003759 let key_id_guard =
3760 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3761 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3762
3763 let source_descriptor: KeyDescriptor = KeyDescriptor {
3764 domain: Domain::APP,
3765 nspace: -1,
3766 alias: Some(SOURCE_ALIAS.to_string()),
3767 blob: None,
3768 };
3769
3770 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3771 domain: Domain::APP,
3772 nspace: -1,
3773 alias: Some(DESTINATION_ALIAS.to_string()),
3774 blob: None,
3775 };
3776
3777 let key_id = key_id_guard.id();
3778
3779 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3780 Ok(())
3781 })
3782 .unwrap();
3783
3784 let (_, key_entry) = db
3785 .load_key_entry(
3786 &destination_descriptor,
3787 KeyType::Client,
3788 KeyEntryLoadBits::BOTH,
3789 DESTINATION_UID,
3790 |k, av| {
3791 assert_eq!(Domain::APP, k.domain);
3792 assert_eq!(DESTINATION_UID as i64, k.nspace);
3793 assert!(av.is_none());
3794 Ok(())
3795 },
3796 )
3797 .unwrap();
3798
3799 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3800
3801 assert_eq!(
3802 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3803 db.load_key_entry(
3804 &source_descriptor,
3805 KeyType::Client,
3806 KeyEntryLoadBits::NONE,
3807 SOURCE_UID,
3808 |_k, _av| Ok(()),
3809 )
3810 .unwrap_err()
3811 .root_cause()
3812 .downcast_ref::<KsError>()
3813 );
3814
3815 Ok(())
3816 }
3817
3818 // Creates a key migrates it to a different location and then tries to access it by the old
3819 // and new location.
3820 #[test]
3821 fn test_migrate_key_app_to_selinux() -> Result<()> {
3822 let mut db = new_test_db()?;
3823 const SOURCE_UID: u32 = 1u32;
3824 const DESTINATION_UID: u32 = 2u32;
3825 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003826 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3827 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003828 let key_id_guard =
3829 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3830 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3831
3832 let source_descriptor: KeyDescriptor = KeyDescriptor {
3833 domain: Domain::APP,
3834 nspace: -1,
3835 alias: Some(SOURCE_ALIAS.to_string()),
3836 blob: None,
3837 };
3838
3839 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3840 domain: Domain::SELINUX,
3841 nspace: DESTINATION_NAMESPACE,
3842 alias: Some(DESTINATION_ALIAS.to_string()),
3843 blob: None,
3844 };
3845
3846 let key_id = key_id_guard.id();
3847
3848 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3849 Ok(())
3850 })
3851 .unwrap();
3852
3853 let (_, key_entry) = db
3854 .load_key_entry(
3855 &destination_descriptor,
3856 KeyType::Client,
3857 KeyEntryLoadBits::BOTH,
3858 DESTINATION_UID,
3859 |k, av| {
3860 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003861 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003862 assert!(av.is_none());
3863 Ok(())
3864 },
3865 )
3866 .unwrap();
3867
3868 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3869
3870 assert_eq!(
3871 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3872 db.load_key_entry(
3873 &source_descriptor,
3874 KeyType::Client,
3875 KeyEntryLoadBits::NONE,
3876 SOURCE_UID,
3877 |_k, _av| Ok(()),
3878 )
3879 .unwrap_err()
3880 .root_cause()
3881 .downcast_ref::<KsError>()
3882 );
3883
3884 Ok(())
3885 }
3886
3887 // Creates two keys and tries to migrate the first to the location of the second which
3888 // is expected to fail.
3889 #[test]
3890 fn test_migrate_key_destination_occupied() -> Result<()> {
3891 let mut db = new_test_db()?;
3892 const SOURCE_UID: u32 = 1u32;
3893 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003894 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3895 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003896 let key_id_guard =
3897 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3898 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3899 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
3900 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3901
3902 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3903 domain: Domain::APP,
3904 nspace: -1,
3905 alias: Some(DESTINATION_ALIAS.to_string()),
3906 blob: None,
3907 };
3908
3909 assert_eq!(
3910 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
3911 db.migrate_key_namespace(
3912 key_id_guard,
3913 &destination_descriptor,
3914 DESTINATION_UID,
3915 |_k| Ok(())
3916 )
3917 .unwrap_err()
3918 .root_cause()
3919 .downcast_ref::<KsError>()
3920 );
3921
3922 Ok(())
3923 }
3924
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003925 #[test]
3926 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003927 const ALIAS1: &str = "test_upgrade_0_to_1_1";
3928 const ALIAS2: &str = "test_upgrade_0_to_1_2";
3929 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003930 const UID: u32 = 33;
3931 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
3932 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
3933 let key_id_untouched1 =
3934 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
3935 let key_id_untouched2 =
3936 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
3937 let key_id_deleted =
3938 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
3939
3940 let (_, key_entry) = db
3941 .load_key_entry(
3942 &KeyDescriptor {
3943 domain: Domain::APP,
3944 nspace: -1,
3945 alias: Some(ALIAS1.to_string()),
3946 blob: None,
3947 },
3948 KeyType::Client,
3949 KeyEntryLoadBits::BOTH,
3950 UID,
3951 |k, av| {
3952 assert_eq!(Domain::APP, k.domain);
3953 assert_eq!(UID as i64, k.nspace);
3954 assert!(av.is_none());
3955 Ok(())
3956 },
3957 )
3958 .unwrap();
3959 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
3960 let (_, key_entry) = db
3961 .load_key_entry(
3962 &KeyDescriptor {
3963 domain: Domain::APP,
3964 nspace: -1,
3965 alias: Some(ALIAS2.to_string()),
3966 blob: None,
3967 },
3968 KeyType::Client,
3969 KeyEntryLoadBits::BOTH,
3970 UID,
3971 |k, av| {
3972 assert_eq!(Domain::APP, k.domain);
3973 assert_eq!(UID as i64, k.nspace);
3974 assert!(av.is_none());
3975 Ok(())
3976 },
3977 )
3978 .unwrap();
3979 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
3980 let (_, key_entry) = db
3981 .load_key_entry(
3982 &KeyDescriptor {
3983 domain: Domain::APP,
3984 nspace: -1,
3985 alias: Some(ALIAS3.to_string()),
3986 blob: None,
3987 },
3988 KeyType::Client,
3989 KeyEntryLoadBits::BOTH,
3990 UID,
3991 |k, av| {
3992 assert_eq!(Domain::APP, k.domain);
3993 assert_eq!(UID as i64, k.nspace);
3994 assert!(av.is_none());
3995 Ok(())
3996 },
3997 )
3998 .unwrap();
3999 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4000
4001 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4002 KeystoreDB::from_0_to_1(tx).no_gc()
4003 })
4004 .unwrap();
4005
4006 let (_, key_entry) = db
4007 .load_key_entry(
4008 &KeyDescriptor {
4009 domain: Domain::APP,
4010 nspace: -1,
4011 alias: Some(ALIAS1.to_string()),
4012 blob: None,
4013 },
4014 KeyType::Client,
4015 KeyEntryLoadBits::BOTH,
4016 UID,
4017 |k, av| {
4018 assert_eq!(Domain::APP, k.domain);
4019 assert_eq!(UID as i64, k.nspace);
4020 assert!(av.is_none());
4021 Ok(())
4022 },
4023 )
4024 .unwrap();
4025 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4026 let (_, key_entry) = db
4027 .load_key_entry(
4028 &KeyDescriptor {
4029 domain: Domain::APP,
4030 nspace: -1,
4031 alias: Some(ALIAS2.to_string()),
4032 blob: None,
4033 },
4034 KeyType::Client,
4035 KeyEntryLoadBits::BOTH,
4036 UID,
4037 |k, av| {
4038 assert_eq!(Domain::APP, k.domain);
4039 assert_eq!(UID as i64, k.nspace);
4040 assert!(av.is_none());
4041 Ok(())
4042 },
4043 )
4044 .unwrap();
4045 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4046 assert_eq!(
4047 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4048 db.load_key_entry(
4049 &KeyDescriptor {
4050 domain: Domain::APP,
4051 nspace: -1,
4052 alias: Some(ALIAS3.to_string()),
4053 blob: None,
4054 },
4055 KeyType::Client,
4056 KeyEntryLoadBits::BOTH,
4057 UID,
4058 |k, av| {
4059 assert_eq!(Domain::APP, k.domain);
4060 assert_eq!(UID as i64, k.nspace);
4061 assert!(av.is_none());
4062 Ok(())
4063 },
4064 )
4065 .unwrap_err()
4066 .root_cause()
4067 .downcast_ref::<KsError>()
4068 );
4069 }
4070
Janis Danisevskisaec14592020-11-12 09:41:49 -08004071 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4072
Janis Danisevskisaec14592020-11-12 09:41:49 -08004073 #[test]
4074 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4075 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004076 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4077 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004078 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004079 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004080 .context("test_insert_and_load_full_keyentry_domain_app")?
4081 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004082 let (_key_guard, key_entry) = db
4083 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004084 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004085 domain: Domain::APP,
4086 nspace: 0,
4087 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4088 blob: None,
4089 },
4090 KeyType::Client,
4091 KeyEntryLoadBits::BOTH,
4092 33,
4093 |_k, _av| Ok(()),
4094 )
4095 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004096 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004097 let state = Arc::new(AtomicU8::new(1));
4098 let state2 = state.clone();
4099
4100 // Spawning a second thread that attempts to acquire the key id lock
4101 // for the same key as the primary thread. The primary thread then
4102 // waits, thereby forcing the secondary thread into the second stage
4103 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4104 // The test succeeds if the secondary thread observes the transition
4105 // of `state` from 1 to 2, despite having a whole second to overtake
4106 // the primary thread.
4107 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004108 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004109 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004110 assert!(db
4111 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004112 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004113 domain: Domain::APP,
4114 nspace: 0,
4115 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4116 blob: None,
4117 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004118 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004119 KeyEntryLoadBits::BOTH,
4120 33,
4121 |_k, _av| Ok(()),
4122 )
4123 .is_ok());
4124 // We should only see a 2 here because we can only return
4125 // from load_key_entry when the `_key_guard` expires,
4126 // which happens at the end of the scope.
4127 assert_eq!(2, state2.load(Ordering::Relaxed));
4128 });
4129
4130 thread::sleep(std::time::Duration::from_millis(1000));
4131
4132 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4133
4134 // Return the handle from this scope so we can join with the
4135 // secondary thread after the key id lock has expired.
4136 handle
4137 // This is where the `_key_guard` goes out of scope,
4138 // which is the reason for concurrent load_key_entry on the same key
4139 // to unblock.
4140 };
4141 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4142 // main test thread. We will not see failing asserts in secondary threads otherwise.
4143 handle.join().unwrap();
4144 Ok(())
4145 }
4146
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004147 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004148 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004149 let temp_dir =
4150 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4151
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004152 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4153 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004154
4155 let _tx1 = db1
4156 .conn
4157 .transaction_with_behavior(TransactionBehavior::Immediate)
4158 .expect("Failed to create first transaction.");
4159
4160 let error = db2
4161 .conn
4162 .transaction_with_behavior(TransactionBehavior::Immediate)
4163 .context("Transaction begin failed.")
4164 .expect_err("This should fail.");
4165 let root_cause = error.root_cause();
4166 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4167 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4168 {
4169 return;
4170 }
4171 panic!(
4172 "Unexpected error {:?} \n{:?} \n{:?}",
4173 error,
4174 root_cause,
4175 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4176 )
4177 }
4178
4179 #[cfg(disabled)]
4180 #[test]
4181 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4182 let temp_dir = Arc::new(
4183 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4184 .expect("Failed to create temp dir."),
4185 );
4186
4187 let test_begin = Instant::now();
4188
Janis Danisevskis66784c42021-01-27 08:40:25 -08004189 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004190 let mut db =
4191 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004192 const OPEN_DB_COUNT: u32 = 50u32;
4193
4194 let mut actual_key_count = KEY_COUNT;
4195 // First insert KEY_COUNT keys.
4196 for count in 0..KEY_COUNT {
4197 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4198 actual_key_count = count;
4199 break;
4200 }
4201 let alias = format!("test_alias_{}", count);
4202 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4203 .expect("Failed to make key entry.");
4204 }
4205
4206 // Insert more keys from a different thread and into a different namespace.
4207 let temp_dir1 = temp_dir.clone();
4208 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004209 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4210 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004211
4212 for count in 0..actual_key_count {
4213 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4214 return;
4215 }
4216 let alias = format!("test_alias_{}", count);
4217 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4218 .expect("Failed to make key entry.");
4219 }
4220
4221 // then unbind them again.
4222 for count in 0..actual_key_count {
4223 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4224 return;
4225 }
4226 let key = KeyDescriptor {
4227 domain: Domain::APP,
4228 nspace: -1,
4229 alias: Some(format!("test_alias_{}", count)),
4230 blob: None,
4231 };
4232 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4233 }
4234 });
4235
4236 // And start unbinding the first set of keys.
4237 let temp_dir2 = temp_dir.clone();
4238 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004239 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4240 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004241
4242 for count in 0..actual_key_count {
4243 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4244 return;
4245 }
4246 let key = KeyDescriptor {
4247 domain: Domain::APP,
4248 nspace: -1,
4249 alias: Some(format!("test_alias_{}", count)),
4250 blob: None,
4251 };
4252 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4253 }
4254 });
4255
Janis Danisevskis66784c42021-01-27 08:40:25 -08004256 // While a lot of inserting and deleting is going on we have to open database connections
4257 // successfully and use them.
4258 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4259 // out of scope.
4260 #[allow(clippy::redundant_clone)]
4261 let temp_dir4 = temp_dir.clone();
4262 let handle4 = thread::spawn(move || {
4263 for count in 0..OPEN_DB_COUNT {
4264 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4265 return;
4266 }
Seth Moore444b51a2021-06-11 09:49:49 -07004267 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4268 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004269
4270 let alias = format!("test_alias_{}", count);
4271 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4272 .expect("Failed to make key entry.");
4273 let key = KeyDescriptor {
4274 domain: Domain::APP,
4275 nspace: -1,
4276 alias: Some(alias),
4277 blob: None,
4278 };
4279 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4280 }
4281 });
4282
4283 handle1.join().expect("Thread 1 panicked.");
4284 handle2.join().expect("Thread 2 panicked.");
4285 handle4.join().expect("Thread 4 panicked.");
4286
Janis Danisevskis66784c42021-01-27 08:40:25 -08004287 Ok(())
4288 }
4289
4290 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004291 fn list() -> Result<()> {
4292 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004293 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004294 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4295 (Domain::APP, 1, "test1"),
4296 (Domain::APP, 1, "test2"),
4297 (Domain::APP, 1, "test3"),
4298 (Domain::APP, 1, "test4"),
4299 (Domain::APP, 1, "test5"),
4300 (Domain::APP, 1, "test6"),
4301 (Domain::APP, 1, "test7"),
4302 (Domain::APP, 2, "test1"),
4303 (Domain::APP, 2, "test2"),
4304 (Domain::APP, 2, "test3"),
4305 (Domain::APP, 2, "test4"),
4306 (Domain::APP, 2, "test5"),
4307 (Domain::APP, 2, "test6"),
4308 (Domain::APP, 2, "test8"),
4309 (Domain::SELINUX, 100, "test1"),
4310 (Domain::SELINUX, 100, "test2"),
4311 (Domain::SELINUX, 100, "test3"),
4312 (Domain::SELINUX, 100, "test4"),
4313 (Domain::SELINUX, 100, "test5"),
4314 (Domain::SELINUX, 100, "test6"),
4315 (Domain::SELINUX, 100, "test9"),
4316 ];
4317
4318 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4319 .iter()
4320 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004321 let entry =
4322 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004323 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4324 });
4325 (entry.id(), *ns)
4326 })
4327 .collect();
4328
4329 for (domain, namespace) in
4330 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4331 {
4332 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4333 .iter()
4334 .filter_map(|(domain, ns, alias)| match ns {
4335 ns if *ns == *namespace => Some(KeyDescriptor {
4336 domain: *domain,
4337 nspace: *ns,
4338 alias: Some(alias.to_string()),
4339 blob: None,
4340 }),
4341 _ => None,
4342 })
4343 .collect();
4344 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004345 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004346 list_result.sort();
4347 assert_eq!(list_o_descriptors, list_result);
4348
4349 let mut list_o_ids: Vec<i64> = list_o_descriptors
4350 .into_iter()
4351 .map(|d| {
4352 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004353 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004354 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004355 KeyType::Client,
4356 KeyEntryLoadBits::NONE,
4357 *namespace as u32,
4358 |_, _| Ok(()),
4359 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004360 .unwrap();
4361 entry.id()
4362 })
4363 .collect();
4364 list_o_ids.sort_unstable();
4365 let mut loaded_entries: Vec<i64> = list_o_keys
4366 .iter()
4367 .filter_map(|(id, ns)| match ns {
4368 ns if *ns == *namespace => Some(*id),
4369 _ => None,
4370 })
4371 .collect();
4372 loaded_entries.sort_unstable();
4373 assert_eq!(list_o_ids, loaded_entries);
4374 }
Eran Messeri24f31972023-01-25 17:00:33 +00004375 assert_eq!(
4376 Vec::<KeyDescriptor>::new(),
4377 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4378 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004379
4380 Ok(())
4381 }
4382
Joel Galenson0891bc12020-07-20 10:37:03 -07004383 // Helpers
4384
4385 // Checks that the given result is an error containing the given string.
4386 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4387 let error_str = format!(
4388 "{:#?}",
4389 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4390 );
4391 assert!(
4392 error_str.contains(target),
4393 "The string \"{}\" should contain \"{}\"",
4394 error_str,
4395 target
4396 );
4397 }
4398
Joel Galenson2aab4432020-07-22 15:27:57 -07004399 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004400 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004401 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004402 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004403 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004404 namespace: Option<i64>,
4405 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004406 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004407 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004408 }
4409
4410 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4411 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004412 .prepare("SELECT * FROM persistent.keyentry;")?
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004413 .query_map([], |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004414 Ok(KeyEntryRow {
4415 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004416 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004417 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004418 namespace: row.get(3)?,
4419 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004420 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004421 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004422 })
4423 })?
4424 .map(|r| r.context("Could not read keyentry row."))
4425 .collect::<Result<Vec<_>>>()
4426 }
4427
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004428 // Note: The parameters and SecurityLevel associations are nonsensical. This
4429 // collection is only used to check if the parameters are preserved as expected by the
4430 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004431 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4432 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004433 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4434 KeyParameter::new(
4435 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4436 SecurityLevel::TRUSTED_ENVIRONMENT,
4437 ),
4438 KeyParameter::new(
4439 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4440 SecurityLevel::TRUSTED_ENVIRONMENT,
4441 ),
4442 KeyParameter::new(
4443 KeyParameterValue::Algorithm(Algorithm::RSA),
4444 SecurityLevel::TRUSTED_ENVIRONMENT,
4445 ),
4446 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4447 KeyParameter::new(
4448 KeyParameterValue::BlockMode(BlockMode::ECB),
4449 SecurityLevel::TRUSTED_ENVIRONMENT,
4450 ),
4451 KeyParameter::new(
4452 KeyParameterValue::BlockMode(BlockMode::GCM),
4453 SecurityLevel::TRUSTED_ENVIRONMENT,
4454 ),
4455 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4456 KeyParameter::new(
4457 KeyParameterValue::Digest(Digest::MD5),
4458 SecurityLevel::TRUSTED_ENVIRONMENT,
4459 ),
4460 KeyParameter::new(
4461 KeyParameterValue::Digest(Digest::SHA_2_224),
4462 SecurityLevel::TRUSTED_ENVIRONMENT,
4463 ),
4464 KeyParameter::new(
4465 KeyParameterValue::Digest(Digest::SHA_2_256),
4466 SecurityLevel::STRONGBOX,
4467 ),
4468 KeyParameter::new(
4469 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4470 SecurityLevel::TRUSTED_ENVIRONMENT,
4471 ),
4472 KeyParameter::new(
4473 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4474 SecurityLevel::TRUSTED_ENVIRONMENT,
4475 ),
4476 KeyParameter::new(
4477 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4478 SecurityLevel::STRONGBOX,
4479 ),
4480 KeyParameter::new(
4481 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4482 SecurityLevel::TRUSTED_ENVIRONMENT,
4483 ),
4484 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4485 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4486 KeyParameter::new(
4487 KeyParameterValue::EcCurve(EcCurve::P_224),
4488 SecurityLevel::TRUSTED_ENVIRONMENT,
4489 ),
4490 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4491 KeyParameter::new(
4492 KeyParameterValue::EcCurve(EcCurve::P_384),
4493 SecurityLevel::TRUSTED_ENVIRONMENT,
4494 ),
4495 KeyParameter::new(
4496 KeyParameterValue::EcCurve(EcCurve::P_521),
4497 SecurityLevel::TRUSTED_ENVIRONMENT,
4498 ),
4499 KeyParameter::new(
4500 KeyParameterValue::RSAPublicExponent(3),
4501 SecurityLevel::TRUSTED_ENVIRONMENT,
4502 ),
4503 KeyParameter::new(
4504 KeyParameterValue::IncludeUniqueID,
4505 SecurityLevel::TRUSTED_ENVIRONMENT,
4506 ),
4507 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4508 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4509 KeyParameter::new(
4510 KeyParameterValue::ActiveDateTime(1234567890),
4511 SecurityLevel::STRONGBOX,
4512 ),
4513 KeyParameter::new(
4514 KeyParameterValue::OriginationExpireDateTime(1234567890),
4515 SecurityLevel::TRUSTED_ENVIRONMENT,
4516 ),
4517 KeyParameter::new(
4518 KeyParameterValue::UsageExpireDateTime(1234567890),
4519 SecurityLevel::TRUSTED_ENVIRONMENT,
4520 ),
4521 KeyParameter::new(
4522 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4523 SecurityLevel::TRUSTED_ENVIRONMENT,
4524 ),
4525 KeyParameter::new(
4526 KeyParameterValue::MaxUsesPerBoot(1234567890),
4527 SecurityLevel::TRUSTED_ENVIRONMENT,
4528 ),
4529 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4530 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4531 KeyParameter::new(
4532 KeyParameterValue::NoAuthRequired,
4533 SecurityLevel::TRUSTED_ENVIRONMENT,
4534 ),
4535 KeyParameter::new(
4536 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4537 SecurityLevel::TRUSTED_ENVIRONMENT,
4538 ),
4539 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4540 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4541 KeyParameter::new(
4542 KeyParameterValue::TrustedUserPresenceRequired,
4543 SecurityLevel::TRUSTED_ENVIRONMENT,
4544 ),
4545 KeyParameter::new(
4546 KeyParameterValue::TrustedConfirmationRequired,
4547 SecurityLevel::TRUSTED_ENVIRONMENT,
4548 ),
4549 KeyParameter::new(
4550 KeyParameterValue::UnlockedDeviceRequired,
4551 SecurityLevel::TRUSTED_ENVIRONMENT,
4552 ),
4553 KeyParameter::new(
4554 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4555 SecurityLevel::SOFTWARE,
4556 ),
4557 KeyParameter::new(
4558 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4559 SecurityLevel::SOFTWARE,
4560 ),
4561 KeyParameter::new(
4562 KeyParameterValue::CreationDateTime(12345677890),
4563 SecurityLevel::SOFTWARE,
4564 ),
4565 KeyParameter::new(
4566 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4567 SecurityLevel::TRUSTED_ENVIRONMENT,
4568 ),
4569 KeyParameter::new(
4570 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4571 SecurityLevel::TRUSTED_ENVIRONMENT,
4572 ),
4573 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4574 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4575 KeyParameter::new(
4576 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4577 SecurityLevel::SOFTWARE,
4578 ),
4579 KeyParameter::new(
4580 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4581 SecurityLevel::TRUSTED_ENVIRONMENT,
4582 ),
4583 KeyParameter::new(
4584 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4585 SecurityLevel::TRUSTED_ENVIRONMENT,
4586 ),
4587 KeyParameter::new(
4588 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4589 SecurityLevel::TRUSTED_ENVIRONMENT,
4590 ),
4591 KeyParameter::new(
4592 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4593 SecurityLevel::TRUSTED_ENVIRONMENT,
4594 ),
4595 KeyParameter::new(
4596 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4597 SecurityLevel::TRUSTED_ENVIRONMENT,
4598 ),
4599 KeyParameter::new(
4600 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4601 SecurityLevel::TRUSTED_ENVIRONMENT,
4602 ),
4603 KeyParameter::new(
4604 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4605 SecurityLevel::TRUSTED_ENVIRONMENT,
4606 ),
4607 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004608 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4609 SecurityLevel::TRUSTED_ENVIRONMENT,
4610 ),
4611 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004612 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4613 SecurityLevel::TRUSTED_ENVIRONMENT,
4614 ),
4615 KeyParameter::new(
4616 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4617 SecurityLevel::TRUSTED_ENVIRONMENT,
4618 ),
4619 KeyParameter::new(
4620 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4621 SecurityLevel::TRUSTED_ENVIRONMENT,
4622 ),
4623 KeyParameter::new(
4624 KeyParameterValue::VendorPatchLevel(3),
4625 SecurityLevel::TRUSTED_ENVIRONMENT,
4626 ),
4627 KeyParameter::new(
4628 KeyParameterValue::BootPatchLevel(4),
4629 SecurityLevel::TRUSTED_ENVIRONMENT,
4630 ),
4631 KeyParameter::new(
4632 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4633 SecurityLevel::TRUSTED_ENVIRONMENT,
4634 ),
4635 KeyParameter::new(
4636 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4637 SecurityLevel::TRUSTED_ENVIRONMENT,
4638 ),
4639 KeyParameter::new(
4640 KeyParameterValue::MacLength(256),
4641 SecurityLevel::TRUSTED_ENVIRONMENT,
4642 ),
4643 KeyParameter::new(
4644 KeyParameterValue::ResetSinceIdRotation,
4645 SecurityLevel::TRUSTED_ENVIRONMENT,
4646 ),
4647 KeyParameter::new(
4648 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4649 SecurityLevel::TRUSTED_ENVIRONMENT,
4650 ),
Qi Wub9433b52020-12-01 14:52:46 +08004651 ];
4652 if let Some(value) = max_usage_count {
4653 params.push(KeyParameter::new(
4654 KeyParameterValue::UsageCountLimit(value),
4655 SecurityLevel::SOFTWARE,
4656 ));
4657 }
4658 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004659 }
4660
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004661 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004662 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004663 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004664 namespace: i64,
4665 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004666 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004667 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004668 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004669 let mut blob_metadata = BlobMetaData::new();
4670 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4671 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4672 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4673 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4674 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4675
4676 db.set_blob(
4677 &key_id,
4678 SubComponentType::KEY_BLOB,
4679 Some(TEST_KEY_BLOB),
4680 Some(&blob_metadata),
4681 )?;
4682 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4683 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004684
4685 let params = make_test_params(max_usage_count);
4686 db.insert_keyparameter(&key_id, &params)?;
4687
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004688 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004689 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004690 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004691 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004692 Ok(key_id)
4693 }
4694
Qi Wub9433b52020-12-01 14:52:46 +08004695 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4696 let params = make_test_params(max_usage_count);
4697
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004698 let mut blob_metadata = BlobMetaData::new();
4699 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4700 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4701 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4702 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4703 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4704
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004705 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004706 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004707
4708 KeyEntry {
4709 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004710 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004711 cert: Some(TEST_CERT_BLOB.to_vec()),
4712 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004713 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004714 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004715 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004716 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004717 }
4718 }
4719
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004720 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004721 db: &mut KeystoreDB,
4722 domain: Domain,
4723 namespace: i64,
4724 alias: &str,
4725 logical_only: bool,
4726 ) -> Result<KeyIdGuard> {
4727 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4728 let mut blob_metadata = BlobMetaData::new();
4729 if !logical_only {
4730 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4731 }
4732 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4733
4734 db.set_blob(
4735 &key_id,
4736 SubComponentType::KEY_BLOB,
4737 Some(TEST_KEY_BLOB),
4738 Some(&blob_metadata),
4739 )?;
4740 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4741 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4742
4743 let mut params = make_test_params(None);
4744 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4745
4746 db.insert_keyparameter(&key_id, &params)?;
4747
4748 let mut metadata = KeyMetaData::new();
4749 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4750 db.insert_key_metadata(&key_id, &metadata)?;
4751 rebind_alias(db, &key_id, alias, domain, namespace)?;
4752 Ok(key_id)
4753 }
4754
4755 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4756 let mut params = make_test_params(None);
4757 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4758
4759 let mut blob_metadata = BlobMetaData::new();
4760 if !logical_only {
4761 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4762 }
4763 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4764
4765 let mut metadata = KeyMetaData::new();
4766 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4767
4768 KeyEntry {
4769 id: key_id,
4770 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4771 cert: Some(TEST_CERT_BLOB.to_vec()),
4772 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4773 km_uuid: KEYSTORE_UUID,
4774 parameters: params,
4775 metadata,
4776 pure_cert: false,
4777 }
4778 }
4779
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004780 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004781 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004782 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004783 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004784 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004785 [],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004786 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004787 Ok((
4788 row.get(0)?,
4789 row.get(1)?,
4790 row.get(2)?,
4791 row.get(3)?,
4792 row.get(4)?,
4793 row.get(5)?,
4794 row.get(6)?,
4795 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004796 },
4797 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004798
4799 println!("Key entry table rows:");
4800 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004801 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004802 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004803 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4804 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004805 );
4806 }
4807 Ok(())
4808 }
4809
4810 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004811 let mut stmt = db
4812 .conn
4813 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Andrew Walbran78abb1e2023-05-30 16:20:56 +00004814 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>([], |row| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004815 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4816 })?;
4817
4818 println!("Grant table rows:");
4819 for r in rows {
4820 let (id, gt, ki, av) = r.unwrap();
4821 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4822 }
4823 Ok(())
4824 }
4825
Joel Galenson0891bc12020-07-20 10:37:03 -07004826 // Use a custom random number generator that repeats each number once.
4827 // This allows us to test repeated elements.
4828
4829 thread_local! {
4830 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4831 }
4832
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004833 fn reset_random() {
4834 RANDOM_COUNTER.with(|counter| {
4835 *counter.borrow_mut() = 0;
4836 })
4837 }
4838
Joel Galenson0891bc12020-07-20 10:37:03 -07004839 pub fn random() -> i64 {
4840 RANDOM_COUNTER.with(|counter| {
4841 let result = *counter.borrow() / 2;
4842 *counter.borrow_mut() += 1;
4843 result
4844 })
4845 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004846
4847 #[test]
4848 fn test_last_off_body() -> Result<()> {
4849 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004850 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004851 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004852 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004853 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004854 let one_second = Duration::from_secs(1);
4855 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004856 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004857 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004858 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004859 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00004860 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004861 Ok(())
4862 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00004863
4864 #[test]
4865 fn test_unbind_keys_for_user() -> Result<()> {
4866 let mut db = new_test_db()?;
4867 db.unbind_keys_for_user(1, false)?;
4868
4869 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4870 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4871 db.unbind_keys_for_user(2, false)?;
4872
Eran Messeri24f31972023-01-25 17:00:33 +00004873 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4874 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004875
4876 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00004877 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004878
4879 Ok(())
4880 }
4881
4882 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004883 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
4884 let mut db = new_test_db()?;
4885 let super_key = keystore2_crypto::generate_aes256_key()?;
4886 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
4887 let (encrypted_super_key, metadata) =
4888 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4889
4890 let key_name_enc = SuperKeyType {
4891 alias: "test_super_key_1",
4892 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004893 name: "test_super_key_1",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004894 };
4895
4896 let key_name_nonenc = SuperKeyType {
4897 alias: "test_super_key_2",
4898 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
Eric Biggers6745f532023-10-27 03:55:28 +00004899 name: "test_super_key_2",
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004900 };
4901
4902 // Install two super keys.
4903 db.store_super_key(
4904 1,
4905 &key_name_nonenc,
4906 &super_key,
4907 &BlobMetaData::new(),
4908 &KeyMetaData::new(),
4909 )?;
4910 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
4911
4912 // Check that both can be found in the database.
4913 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
4914 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
4915
4916 // Install the same keys for a different user.
4917 db.store_super_key(
4918 2,
4919 &key_name_nonenc,
4920 &super_key,
4921 &BlobMetaData::new(),
4922 &KeyMetaData::new(),
4923 )?;
4924 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
4925
4926 // Check that the second pair of keys can be found in the database.
4927 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
4928 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
4929
4930 // Delete only encrypted keys.
4931 db.unbind_keys_for_user(1, true)?;
4932
4933 // The encrypted superkey should be gone now.
4934 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
4935 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
4936
4937 // Reinsert the encrypted key.
4938 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
4939
4940 // Check that both can be found in the database, again..
4941 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
4942 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
4943
4944 // Delete all even unencrypted keys.
4945 db.unbind_keys_for_user(1, false)?;
4946
4947 // Both should be gone now.
4948 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
4949 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
4950
4951 // Check that the second pair of keys was untouched.
4952 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
4953 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
4954
4955 Ok(())
4956 }
4957
4958 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00004959 fn test_store_super_key() -> Result<()> {
4960 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07004961 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00004962 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07004963 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00004964 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07004965 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004966
4967 let (encrypted_super_key, metadata) =
4968 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07004969 db.store_super_key(
4970 1,
Eric Biggers673d34a2023-10-18 01:54:18 +00004971 &USER_AFTER_FIRST_UNLOCK_SUPER_KEY,
Paul Crowley8d5b2532021-03-19 10:53:07 -07004972 &encrypted_super_key,
4973 &metadata,
4974 &KeyMetaData::new(),
4975 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004976
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004977 // Check if super key exists.
Eric Biggers673d34a2023-10-18 01:54:18 +00004978 assert!(db.key_exists(
4979 Domain::APP,
4980 1,
4981 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.alias,
4982 KeyType::Super
4983 )?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00004984
Eric Biggers673d34a2023-10-18 01:54:18 +00004985 let (_, key_entry) = db.load_super_key(&USER_AFTER_FIRST_UNLOCK_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07004986 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
Eric Biggers673d34a2023-10-18 01:54:18 +00004987 USER_AFTER_FIRST_UNLOCK_SUPER_KEY.algorithm,
Paul Crowley8d5b2532021-03-19 10:53:07 -07004988 key_entry,
4989 &pw,
4990 None,
4991 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004992
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08004993 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07004994 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004995
Hasini Gunasingheda895552021-01-27 19:34:37 +00004996 Ok(())
4997 }
Seth Moore78c091f2021-04-09 21:38:30 +00004998
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00004999 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005000 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005001 MetricsStorage::KEY_ENTRY,
5002 MetricsStorage::KEY_ENTRY_ID_INDEX,
5003 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5004 MetricsStorage::BLOB_ENTRY,
5005 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5006 MetricsStorage::KEY_PARAMETER,
5007 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5008 MetricsStorage::KEY_METADATA,
5009 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5010 MetricsStorage::GRANT,
5011 MetricsStorage::AUTH_TOKEN,
5012 MetricsStorage::BLOB_METADATA,
5013 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005014 ]
5015 }
5016
5017 /// Perform a simple check to ensure that we can query all the storage types
5018 /// that are supported by the DB. Check for reasonable values.
5019 #[test]
5020 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005021 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005022
5023 let mut db = new_test_db()?;
5024
5025 for t in get_valid_statsd_storage_types() {
5026 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005027 // AuthToken can be less than a page since it's in a btree, not sqlite
5028 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005029 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005030 } else {
5031 assert!(stat.size >= PAGE_SIZE);
5032 }
Seth Moore78c091f2021-04-09 21:38:30 +00005033 assert!(stat.size >= stat.unused_size);
5034 }
5035
5036 Ok(())
5037 }
5038
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005039 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005040 get_valid_statsd_storage_types()
5041 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005042 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005043 .collect()
5044 }
5045
5046 fn assert_storage_increased(
5047 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005048 increased_storage_types: Vec<MetricsStorage>,
5049 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005050 ) {
5051 for storage in increased_storage_types {
5052 // Verify the expected storage increased.
5053 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005054 let storage = storage;
5055 let old = &baseline[&storage.0];
5056 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005057 assert!(
5058 new.unused_size <= old.unused_size,
5059 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005060 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005061 new.unused_size,
5062 old.unused_size
5063 );
5064
5065 // Update the baseline with the new value so that it succeeds in the
5066 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005067 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005068 }
5069
5070 // Get an updated map of the storage and verify there were no unexpected changes.
5071 let updated_stats = get_storage_stats_map(db);
5072 assert_eq!(updated_stats.len(), baseline.len());
5073
5074 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005075 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005076 let mut s = String::new();
5077 for &k in map.keys() {
5078 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5079 .expect("string concat failed");
5080 }
5081 s
5082 };
5083
5084 assert!(
5085 updated_stats[&k].size == baseline[&k].size
5086 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5087 "updated_stats:\n{}\nbaseline:\n{}",
5088 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005089 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005090 );
5091 }
5092 }
5093
5094 #[test]
5095 fn test_verify_key_table_size_reporting() -> Result<()> {
5096 let mut db = new_test_db()?;
5097 let mut working_stats = get_storage_stats_map(&mut db);
5098
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005099 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005100 assert_storage_increased(
5101 &mut db,
5102 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005103 MetricsStorage::KEY_ENTRY,
5104 MetricsStorage::KEY_ENTRY_ID_INDEX,
5105 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005106 ],
5107 &mut working_stats,
5108 );
5109
5110 let mut blob_metadata = BlobMetaData::new();
5111 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5112 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5113 assert_storage_increased(
5114 &mut db,
5115 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005116 MetricsStorage::BLOB_ENTRY,
5117 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5118 MetricsStorage::BLOB_METADATA,
5119 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005120 ],
5121 &mut working_stats,
5122 );
5123
5124 let params = make_test_params(None);
5125 db.insert_keyparameter(&key_id, &params)?;
5126 assert_storage_increased(
5127 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005128 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005129 &mut working_stats,
5130 );
5131
5132 let mut metadata = KeyMetaData::new();
5133 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5134 db.insert_key_metadata(&key_id, &metadata)?;
5135 assert_storage_increased(
5136 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005137 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005138 &mut working_stats,
5139 );
5140
5141 let mut sum = 0;
5142 for stat in working_stats.values() {
5143 sum += stat.size;
5144 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005145 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005146 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5147
5148 Ok(())
5149 }
5150
5151 #[test]
5152 fn test_verify_auth_table_size_reporting() -> Result<()> {
5153 let mut db = new_test_db()?;
5154 let mut working_stats = get_storage_stats_map(&mut db);
5155 db.insert_auth_token(&HardwareAuthToken {
5156 challenge: 123,
5157 userId: 456,
5158 authenticatorId: 789,
5159 authenticatorType: kmhw_authenticator_type::ANY,
5160 timestamp: Timestamp { milliSeconds: 10 },
5161 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005162 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005163 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005164 Ok(())
5165 }
5166
5167 #[test]
5168 fn test_verify_grant_table_size_reporting() -> Result<()> {
5169 const OWNER: i64 = 1;
5170 let mut db = new_test_db()?;
5171 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5172
5173 let mut working_stats = get_storage_stats_map(&mut db);
5174 db.grant(
5175 &KeyDescriptor {
5176 domain: Domain::APP,
5177 nspace: 0,
5178 alias: Some(TEST_ALIAS.to_string()),
5179 blob: None,
5180 },
5181 OWNER as u32,
5182 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005183 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005184 |_, _| Ok(()),
5185 )?;
5186
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005187 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005188
5189 Ok(())
5190 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005191
5192 #[test]
5193 fn find_auth_token_entry_returns_latest() -> Result<()> {
5194 let mut db = new_test_db()?;
5195 db.insert_auth_token(&HardwareAuthToken {
5196 challenge: 123,
5197 userId: 456,
5198 authenticatorId: 789,
5199 authenticatorType: kmhw_authenticator_type::ANY,
5200 timestamp: Timestamp { milliSeconds: 10 },
5201 mac: b"mac0".to_vec(),
5202 });
5203 std::thread::sleep(std::time::Duration::from_millis(1));
5204 db.insert_auth_token(&HardwareAuthToken {
5205 challenge: 123,
5206 userId: 457,
5207 authenticatorId: 789,
5208 authenticatorType: kmhw_authenticator_type::ANY,
5209 timestamp: Timestamp { milliSeconds: 12 },
5210 mac: b"mac1".to_vec(),
5211 });
5212 std::thread::sleep(std::time::Duration::from_millis(1));
5213 db.insert_auth_token(&HardwareAuthToken {
5214 challenge: 123,
5215 userId: 458,
5216 authenticatorId: 789,
5217 authenticatorType: kmhw_authenticator_type::ANY,
5218 timestamp: Timestamp { milliSeconds: 3 },
5219 mac: b"mac2".to_vec(),
5220 });
5221 // All three entries are in the database
5222 assert_eq!(db.perboot.auth_tokens_len(), 3);
5223 // It selected the most recent timestamp
5224 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5225 Ok(())
5226 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005227
5228 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005229 fn test_load_key_descriptor() -> Result<()> {
5230 let mut db = new_test_db()?;
5231 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5232
5233 let key = db.load_key_descriptor(key_id)?.unwrap();
5234
5235 assert_eq!(key.domain, Domain::APP);
5236 assert_eq!(key.nspace, 1);
5237 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5238
5239 // No such id
5240 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5241 Ok(())
5242 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005243}