blob: 10cadfec747452aff387f53883c567333bd7592c [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};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080058use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080059use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis030ba022021-05-26 11:15:30 -070060use utils as db_utils;
61use utils::SqlField;
Janis Danisevskis60400fe2020-08-26 15:24:42 -070062
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000063use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Tri Voa1634bb2022-12-01 15:54:19 -080064 HardwareAuthToken::HardwareAuthToken, HardwareAuthenticatorType::HardwareAuthenticatorType,
65 SecurityLevel::SecurityLevel,
66};
67use android_security_metrics::aidl::android::security::metrics::{
Tri Vo0346bbe2023-05-12 14:16:31 -040068 Storage::Storage as MetricsStorage, StorageStats::StorageStats,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080069};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070070use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070071 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070072};
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},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080085 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
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);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700908 NO_PARAMS,
909 )
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);",
915 NO_PARAMS,
916 )
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);",
922 NO_PARAMS,
923 )
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);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700932 NO_PARAMS,
933 )
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);",
939 NO_PARAMS,
940 )
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));",
950 NO_PARAMS,
951 )
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);",
957 NO_PARAMS,
958 )
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);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700967 NO_PARAMS,
968 )
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);",
974 NO_PARAMS,
975 )
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));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800984 NO_PARAMS,
985 )
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);",
991 NO_PARAMS,
992 )
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);",
1001 NO_PARAMS,
1002 )
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
Matthew Maurer4fb19112021-05-06 15:40:44 -07001039 // Drop the cache size from default (2M) to 0.5M
1040 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1041 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001042
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001043 Ok(conn)
1044 }
1045
Seth Moore78c091f2021-04-09 21:38:30 +00001046 fn do_table_size_query(
1047 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001048 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001049 query: &str,
1050 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001051 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001052 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001053 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001054 .with_context(|| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001055 ks_err!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001056 })
1057 .no_gc()
1058 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001059 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001060 }
1061
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001062 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001063 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001064 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001065 "SELECT page_count * page_size, freelist_count * page_size
1066 FROM pragma_page_count('persistent'),
1067 pragma_page_size('persistent'),
1068 persistent.pragma_freelist_count();",
1069 &[],
1070 )
1071 }
1072
1073 fn get_table_size(
1074 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001075 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001076 schema: &str,
1077 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001078 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001079 self.do_table_size_query(
1080 storage_type,
1081 "SELECT pgsize,unused FROM dbstat(?1)
1082 WHERE name=?2 AND aggregate=TRUE;",
1083 &[schema, table],
1084 )
1085 }
1086
1087 /// Fetches a storage statisitics atom for a given storage type. For storage
1088 /// types that map to a table, information about the table's storage is
1089 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001090 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001091 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1092
Seth Moore78c091f2021-04-09 21:38:30 +00001093 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001094 MetricsStorage::DATABASE => self.get_total_size(),
1095 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001096 self.get_table_size(storage_type, "persistent", "keyentry")
1097 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001098 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001099 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1100 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001101 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001102 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1103 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001104 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001105 self.get_table_size(storage_type, "persistent", "blobentry")
1106 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001108 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1109 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001110 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001111 self.get_table_size(storage_type, "persistent", "keyparameter")
1112 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001113 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001114 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1115 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001116 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "keymetadata")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001120 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1121 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001122 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1123 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001124 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1125 // reportable
1126 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001127 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001128 storage_type,
1129 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001130 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001131 unused_size: 0,
1132 })
Seth Moore78c091f2021-04-09 21:38:30 +00001133 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001134 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001135 self.get_table_size(storage_type, "persistent", "blobmetadata")
1136 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001137 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001138 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1139 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001140 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001141 }
1142 }
1143
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001144 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001145 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1146 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001147 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1148 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001149 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001150 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001151 blob_ids_to_delete: &[i64],
1152 max_blobs: usize,
1153 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001154 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001155 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001156 // Delete the given blobs.
1157 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001158 tx.execute(
1159 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001160 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001161 )
1162 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001163 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1164 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001165 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001166
1167 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1168
Janis Danisevskis3395f862021-05-06 10:54:17 -07001169 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1170 let result: Vec<(i64, Vec<u8>)> = {
1171 let mut stmt = tx
1172 .prepare(
1173 "SELECT id, blob FROM persistent.blobentry
1174 WHERE subcomponent_type = ?
1175 AND (
1176 id NOT IN (
1177 SELECT MAX(id) FROM persistent.blobentry
1178 WHERE subcomponent_type = ?
1179 GROUP BY keyentryid, subcomponent_type
1180 )
1181 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1182 ) LIMIT ?;",
1183 )
1184 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001185
Janis Danisevskis3395f862021-05-06 10:54:17 -07001186 let rows = stmt
1187 .query_map(
1188 params![
1189 SubComponentType::KEY_BLOB,
1190 SubComponentType::KEY_BLOB,
1191 max_blobs as i64,
1192 ],
1193 |row| Ok((row.get(0)?, row.get(1)?)),
1194 )
1195 .context("Trying to query superseded blob.")?;
1196
1197 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1198 .context("Trying to extract superseded blobs.")?
1199 };
1200
1201 let result = result
1202 .into_iter()
1203 .map(|(blob_id, blob)| {
1204 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1205 })
1206 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1207 .context("Trying to load blob metadata.")?;
1208 if !result.is_empty() {
1209 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001210 }
1211
1212 // We did not find any superseded key blob, so let's remove other superseded blob in
1213 // one transaction.
1214 tx.execute(
1215 "DELETE FROM persistent.blobentry
1216 WHERE NOT subcomponent_type = ?
1217 AND (
1218 id NOT IN (
1219 SELECT MAX(id) FROM persistent.blobentry
1220 WHERE NOT subcomponent_type = ?
1221 GROUP BY keyentryid, subcomponent_type
1222 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1223 );",
1224 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1225 )
1226 .context("Trying to purge superseded blobs.")?;
1227
Janis Danisevskis3395f862021-05-06 10:54:17 -07001228 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001229 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001230 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001231 }
1232
1233 /// This maintenance function should be called only once before the database is used for the
1234 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1235 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1236 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1237 /// Keystore crashed at some point during key generation. Callers may want to log such
1238 /// occurrences.
1239 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1240 /// it to `KeyLifeCycle::Live` may have grants.
1241 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001242 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1243
Janis Danisevskis66784c42021-01-27 08:40:25 -08001244 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1245 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001246 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1247 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1248 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001249 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001250 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001251 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001252 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001253 }
1254
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001255 /// Checks if a key exists with given key type and key descriptor properties.
1256 pub fn key_exists(
1257 &mut self,
1258 domain: Domain,
1259 nspace: i64,
1260 alias: &str,
1261 key_type: KeyType,
1262 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001263 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1264
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001265 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1266 let key_descriptor =
1267 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001268 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001269 match result {
1270 Ok(_) => Ok(true),
1271 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1272 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001273 _ => Err(error).context(ks_err!("Failed to find if the key exists.")),
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001274 },
1275 }
1276 .no_gc()
1277 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001278 .context(ks_err!())
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001279 }
1280
Hasini Gunasingheda895552021-01-27 19:34:37 +00001281 /// Stores a super key in the database.
1282 pub fn store_super_key(
1283 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001284 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001285 key_type: &SuperKeyType,
1286 blob: &[u8],
1287 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001288 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001289 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001290 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1291
Hasini Gunasingheda895552021-01-27 19:34:37 +00001292 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1293 let key_id = Self::insert_with_retry(|id| {
1294 tx.execute(
1295 "INSERT into persistent.keyentry
1296 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001297 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 params![
1299 id,
1300 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001301 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001302 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001303 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001304 KeyLifeCycle::Live,
1305 &KEYSTORE_UUID,
1306 ],
1307 )
1308 })
1309 .context("Failed to insert into keyentry table.")?;
1310
Paul Crowley8d5b2532021-03-19 10:53:07 -07001311 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1312
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001314 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001315 key_id,
1316 SubComponentType::KEY_BLOB,
1317 Some(blob),
1318 Some(blob_metadata),
1319 )
1320 .context("Failed to store key blob.")?;
1321
1322 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1323 .context("Trying to load key components.")
1324 .no_gc()
1325 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001326 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00001327 }
1328
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001329 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001330 pub fn load_super_key(
1331 &mut self,
1332 key_type: &SuperKeyType,
1333 user_id: u32,
1334 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001335 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1336
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001337 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1338 let key_descriptor = KeyDescriptor {
1339 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001340 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001341 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001342 blob: None,
1343 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001344 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001345 match id {
1346 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001347 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001348 .context(ks_err!("Failed to load key entry."))?;
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001349 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1350 }
1351 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1352 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001353 _ => Err(error).context(ks_err!()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001354 },
1355 }
1356 .no_gc()
1357 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001358 .context(ks_err!())
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001359 }
1360
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001361 /// Atomically loads a key entry and associated metadata or creates it using the
1362 /// callback create_new_key callback. The callback is called during a database
1363 /// transaction. This means that implementers should be mindful about using
1364 /// blocking operations such as IPC or grabbing mutexes.
1365 pub fn get_or_create_key_with<F>(
1366 &mut self,
1367 domain: Domain,
1368 namespace: i64,
1369 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001370 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001371 create_new_key: F,
1372 ) -> Result<(KeyIdGuard, KeyEntry)>
1373 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001374 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001375 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001376 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1377
Janis Danisevskis66784c42021-01-27 08:40:25 -08001378 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1379 let id = {
1380 let mut stmt = tx
1381 .prepare(
1382 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001383 WHERE
1384 key_type = ?
1385 AND domain = ?
1386 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001387 AND alias = ?
1388 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001389 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001390 .context(ks_err!("Failed to select from keyentry table."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001391 let mut rows = stmt
1392 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001393 .context(ks_err!("Failed to query from keyentry table."))?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001394
Janis Danisevskis66784c42021-01-27 08:40:25 -08001395 db_utils::with_rows_extract_one(&mut rows, |row| {
1396 Ok(match row {
1397 Some(r) => r.get(0).context("Failed to unpack id.")?,
1398 None => None,
1399 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001400 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001401 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08001402 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 let (id, entry) = match id {
1405 Some(id) => (
1406 id,
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001407 Self::load_key_components(tx, KeyEntryLoadBits::KM, id).context(ks_err!())?,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001408 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001409
Janis Danisevskis66784c42021-01-27 08:40:25 -08001410 None => {
1411 let id = Self::insert_with_retry(|id| {
1412 tx.execute(
1413 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001414 (id, key_type, domain, namespace, alias, state, km_uuid)
1415 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001416 params![
1417 id,
1418 KeyType::Super,
1419 domain.0,
1420 namespace,
1421 alias,
1422 KeyLifeCycle::Live,
1423 km_uuid,
1424 ],
1425 )
1426 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001427 .context(ks_err!())?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001428
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001429 let (blob, metadata) = create_new_key().context(ks_err!())?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001430 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001431 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001432 id,
1433 SubComponentType::KEY_BLOB,
1434 Some(&blob),
1435 Some(&metadata),
1436 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001437 .context(ks_err!())?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001438 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001439 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001440 KeyEntry {
1441 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001442 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001443 pure_cert: false,
1444 ..Default::default()
1445 },
1446 )
1447 }
1448 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001449 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001450 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001451 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001452 }
1453
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001454 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001455 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1456 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001457 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1458 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001459 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001460 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001461 loop {
1462 match self
1463 .conn
1464 .transaction_with_behavior(behavior)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001465 .context(ks_err!())
Janis Danisevskis66784c42021-01-27 08:40:25 -08001466 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1467 .and_then(|(result, tx)| {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001468 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001469 Ok(result)
1470 }) {
1471 Ok(result) => break Ok(result),
1472 Err(e) => {
1473 if Self::is_locked_error(&e) {
1474 std::thread::sleep(std::time::Duration::from_micros(500));
1475 continue;
1476 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001477 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08001478 }
1479 }
1480 }
1481 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001482 .map(|(need_gc, result)| {
1483 if need_gc {
1484 if let Some(ref gc) = self.gc {
1485 gc.notify_gc();
1486 }
1487 }
1488 result
1489 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001490 }
1491
1492 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001493 matches!(
1494 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1495 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1496 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1497 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001498 }
1499
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001500 /// Creates a new key entry and allocates a new randomized id for the new key.
1501 /// The key id gets associated with a domain and namespace but not with an alias.
1502 /// To complete key generation `rebind_alias` should be called after all of the
1503 /// key artifacts, i.e., blobs and parameters have been associated with the new
1504 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1505 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001506 pub fn create_key_entry(
1507 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001508 domain: &Domain,
1509 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001510 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001511 km_uuid: &Uuid,
1512 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001513 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1514
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001515 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001516 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001517 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001518 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001519 }
1520
1521 fn create_key_entry_internal(
1522 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001523 domain: &Domain,
1524 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001525 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001526 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001527 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001528 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001529 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001530 _ => {
1531 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001532 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson0891bc12020-07-20 10:37:03 -07001533 }
1534 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001535 Ok(KEY_ID_LOCK.get(
1536 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001537 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001538 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001539 (id, key_type, domain, namespace, alias, state, km_uuid)
1540 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001541 params![
1542 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001543 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001544 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001545 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001546 KeyLifeCycle::Existing,
1547 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001548 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001549 )
1550 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001551 .context(ks_err!())?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001552 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001553 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001554
Janis Danisevskis377d1002021-01-27 19:07:48 -08001555 /// Set a new blob and associates it with the given key id. Each blob
1556 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001557 /// Each key can have one of each sub component type associated. If more
1558 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001559 /// will get garbage collected.
1560 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1561 /// removed by setting blob to None.
1562 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001563 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001564 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001565 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001566 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001567 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001568 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001569 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1570
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001571 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001572 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001573 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001574 .context(ks_err!())
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001575 }
1576
Janis Danisevskiseed69842021-02-18 20:04:10 -08001577 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1578 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1579 /// We use this to insert key blobs into the database which can then be garbage collected
1580 /// lazily by the key garbage collector.
1581 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001582 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1583
Janis Danisevskiseed69842021-02-18 20:04:10 -08001584 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1585 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001586 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001587 Self::UNASSIGNED_KEY_ID,
1588 SubComponentType::KEY_BLOB,
1589 Some(blob),
1590 Some(blob_metadata),
1591 )
1592 .need_gc()
1593 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001594 .context(ks_err!())
Janis Danisevskiseed69842021-02-18 20:04:10 -08001595 }
1596
Janis Danisevskis377d1002021-01-27 19:07:48 -08001597 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001598 tx: &Transaction,
1599 key_id: i64,
1600 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001601 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001602 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001603 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001604 match (blob, sc_type) {
1605 (Some(blob), _) => {
1606 tx.execute(
1607 "INSERT INTO persistent.blobentry
1608 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1609 params![sc_type, key_id, blob],
1610 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001611 .context(ks_err!("Failed to insert blob."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001612 if let Some(blob_metadata) = blob_metadata {
1613 let blob_id = tx
1614 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1615 row.get(0)
1616 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001617 .context(ks_err!("Failed to get new blob id."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001618 blob_metadata
1619 .store_in_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001620 .context(ks_err!("Trying to store blob metadata."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001621 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001622 }
1623 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1624 tx.execute(
1625 "DELETE FROM persistent.blobentry
1626 WHERE subcomponent_type = ? AND keyentryid = ?;",
1627 params![sc_type, key_id],
1628 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001629 .context(ks_err!("Failed to delete blob."))?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001630 }
1631 (None, _) => {
1632 return Err(KsError::sys())
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001633 .context(ks_err!("Other blobs cannot be deleted in this way."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001634 }
1635 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001636 Ok(())
1637 }
1638
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001639 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1640 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001641 #[cfg(test)]
1642 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001643 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001644 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001645 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001646 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001647 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001648
Janis Danisevskis66784c42021-01-27 08:40:25 -08001649 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001650 tx: &Transaction,
1651 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001652 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001653 ) -> Result<()> {
1654 let mut stmt = tx
1655 .prepare(
1656 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1657 VALUES (?, ?, ?, ?);",
1658 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001659 .context(ks_err!("Failed to prepare statement."))?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001660
Janis Danisevskis66784c42021-01-27 08:40:25 -08001661 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001662 stmt.insert(params![
1663 key_id.0,
1664 p.get_tag().0,
1665 p.key_parameter_value(),
1666 p.security_level().0
1667 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001668 .with_context(|| ks_err!("Failed to insert {:?}", p))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001669 }
1670 Ok(())
1671 }
1672
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001673 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001674 #[cfg(test)]
1675 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001676 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001677 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001678 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001679 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001680 }
1681
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001682 /// Updates the alias column of the given key id `newid` with the given alias,
1683 /// and atomically, removes the alias, domain, and namespace from another row
1684 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001685 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1686 /// collector.
1687 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001688 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001689 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001690 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001691 domain: &Domain,
1692 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001693 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001694 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001695 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001696 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001697 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001698 return Err(KsError::sys())
1699 .context(ks_err!("Domain {:?} must be either App or SELinux.", domain));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001700 }
1701 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001702 let updated = tx
1703 .execute(
1704 "UPDATE persistent.keyentry
1705 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001706 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
1707 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001708 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001709 .context(ks_err!("Failed to rebind existing entry."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001710 let result = tx
1711 .execute(
1712 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001713 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001714 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001715 params![
1716 alias,
1717 KeyLifeCycle::Live,
1718 newid.0,
1719 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001720 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001721 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001722 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001723 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001724 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001725 .context(ks_err!("Failed to set alias."))?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001726 if result != 1 {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001727 return Err(KsError::sys()).context(ks_err!(
1728 "Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001729 result
1730 ));
1731 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001732 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 }
1734
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001735 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
1736 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
1737 pub fn migrate_key_namespace(
1738 &mut self,
1739 key_id_guard: KeyIdGuard,
1740 destination: &KeyDescriptor,
1741 caller_uid: u32,
1742 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
1743 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001744 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
1745
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001746 let destination = match destination.domain {
1747 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
1748 Domain::SELINUX => (*destination).clone(),
1749 domain => {
1750 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1751 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
1752 }
1753 };
1754
1755 // Security critical: Must return immediately on failure. Do not remove the '?';
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001756 check_permission(&destination).context(ks_err!("Trying to check permission."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001757
1758 let alias = destination
1759 .alias
1760 .as_ref()
1761 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001762 .context(ks_err!("Alias must be specified."))?;
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001763
1764 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1765 // Query the destination location. If there is a key, the migration request fails.
1766 if tx
1767 .query_row(
1768 "SELECT id FROM persistent.keyentry
1769 WHERE alias = ? AND domain = ? AND namespace = ?;",
1770 params![alias, destination.domain.0, destination.nspace],
1771 |_| Ok(()),
1772 )
1773 .optional()
1774 .context("Failed to query destination.")?
1775 .is_some()
1776 {
1777 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1778 .context("Target already exists.");
1779 }
1780
1781 let updated = tx
1782 .execute(
1783 "UPDATE persistent.keyentry
1784 SET alias = ?, domain = ?, namespace = ?
1785 WHERE id = ?;",
1786 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
1787 )
1788 .context("Failed to update key entry.")?;
1789
1790 if updated != 1 {
1791 return Err(KsError::sys())
1792 .context(format!("Update succeeded, but {} rows were updated.", updated));
1793 }
1794 Ok(()).no_gc()
1795 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001796 .context(ks_err!())
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07001797 }
1798
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001799 /// Store a new key in a single transaction.
1800 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1801 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001802 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1803 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07001804 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08001805 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001806 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001807 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001808 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001809 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001810 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08001811 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001812 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001813 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001814 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001815 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
1816
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001817 let (alias, domain, namespace) = match key {
1818 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1819 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1820 (alias, key.domain, nspace)
1821 }
1822 _ => {
1823 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001824 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001825 }
1826 };
1827 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001828 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001829 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001830 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
1831
1832 // In some occasions the key blob is already upgraded during the import.
1833 // In order to make sure it gets properly deleted it is inserted into the
1834 // database here and then immediately replaced by the superseding blob.
1835 // The garbage collector will then subject the blob to deleteKey of the
1836 // KM back end to permanently invalidate the key.
1837 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
1838 Self::set_blob_internal(
1839 tx,
1840 key_id.id(),
1841 SubComponentType::KEY_BLOB,
1842 Some(blob),
1843 Some(blob_metadata),
1844 )
1845 .context("Trying to insert superseded key blob.")?;
1846 true
1847 } else {
1848 false
1849 };
1850
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001851 Self::set_blob_internal(
1852 tx,
1853 key_id.id(),
1854 SubComponentType::KEY_BLOB,
1855 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001856 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001857 )
1858 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08001859 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001860 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001861 .context("Trying to insert the certificate.")?;
1862 }
Max Bires8e93d2b2021-01-14 13:17:59 -08001863 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001864 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001865 tx,
1866 key_id.id(),
1867 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001868 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001869 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001870 )
1871 .context("Trying to insert the certificate chain.")?;
1872 }
1873 Self::insert_keyparameter_internal(tx, &key_id, params)
1874 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001875 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001876 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08001877 .context("Trying to rebind alias.")?
1878 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001879 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001880 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001881 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001882 }
1883
Janis Danisevskis377d1002021-01-27 19:07:48 -08001884 /// Store a new certificate
1885 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
1886 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08001887 pub fn store_new_certificate(
1888 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001889 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001890 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001891 cert: &[u8],
1892 km_uuid: &Uuid,
1893 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001894 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
1895
Janis Danisevskis377d1002021-01-27 19:07:48 -08001896 let (alias, domain, namespace) = match key {
1897 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1898 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1899 (alias, key.domain, nspace)
1900 }
1901 _ => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001902 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1903 .context(ks_err!("Need alias and domain must be APP or SELINUX."));
Janis Danisevskis377d1002021-01-27 19:07:48 -08001904 }
1905 };
1906 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001907 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001908 .context("Trying to create new key entry.")?;
1909
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001910 Self::set_blob_internal(
1911 tx,
1912 key_id.id(),
1913 SubComponentType::CERT_CHAIN,
1914 Some(cert),
1915 None,
1916 )
1917 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08001918
1919 let mut metadata = KeyMetaData::new();
1920 metadata.add(KeyMetaEntry::CreationDate(
1921 DateTime::now().context("Trying to make creation time.")?,
1922 ));
1923
1924 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
1925
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001926 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001927 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001928 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08001929 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001930 .context(ks_err!())
Janis Danisevskis377d1002021-01-27 19:07:48 -08001931 }
1932
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001933 // Helper function loading the key_id given the key descriptor
1934 // tuple comprising domain, namespace, and alias.
1935 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001936 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001937 let alias = key
1938 .alias
1939 .as_ref()
1940 .map_or_else(|| Err(KsError::sys()), Ok)
1941 .context("In load_key_entry_id: Alias must be specified.")?;
1942 let mut stmt = tx
1943 .prepare(
1944 "SELECT id FROM persistent.keyentry
1945 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001946 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001947 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001948 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001949 AND alias = ?
1950 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001951 )
1952 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
1953 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001954 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001955 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001956 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001957 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001958 .get(0)
1959 .context("Failed to unpack id.")
1960 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00001961 .context(ks_err!())
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001962 }
1963
1964 /// This helper function completes the access tuple of a key, which is required
1965 /// to perform access control. The strategy depends on the `domain` field in the
1966 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001967 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001968 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001969 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001970 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001971 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001972 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001973 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001974 /// `namespace`.
1975 /// In each case the information returned is sufficient to perform the access
1976 /// check and the key id can be used to load further key artifacts.
1977 fn load_access_tuple(
1978 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001979 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001980 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001981 caller_uid: u32,
1982 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
1983 match key.domain {
1984 // Domain App or SELinux. In this case we load the key_id from
1985 // the keyentry database for further loading of key components.
1986 // We already have the full access tuple to perform access control.
1987 // The only distinction is that we use the caller_uid instead
1988 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001989 // Domain::APP.
1990 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001991 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001992 if access_key.domain == Domain::APP {
1993 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001994 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001995 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001996 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001997
1998 Ok((key_id, access_key, None))
1999 }
2000
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002001 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002002 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002003 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002004 let mut stmt = tx
2005 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002006 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002007 WHERE grantee = ? AND id = ? AND
2008 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002009 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002010 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002011 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002012 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002013 .context("Domain:Grant: query failed.")?;
2014 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002015 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002016 let r =
2017 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002018 Ok((
2019 r.get(0).context("Failed to unpack key_id.")?,
2020 r.get(1).context("Failed to unpack access_vector.")?,
2021 ))
2022 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002023 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002024 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002025 }
2026
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002027 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002028 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002029 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002030 let (domain, namespace): (Domain, i64) = {
2031 let mut stmt = tx
2032 .prepare(
2033 "SELECT domain, namespace FROM persistent.keyentry
2034 WHERE
2035 id = ?
2036 AND state = ?;",
2037 )
2038 .context("Domain::KEY_ID: prepare statement failed")?;
2039 let mut rows = stmt
2040 .query(params![key.nspace, KeyLifeCycle::Live])
2041 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002042 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002043 let r =
2044 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002045 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002046 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002047 r.get(1).context("Failed to unpack namespace.")?,
2048 ))
2049 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002050 .context("Domain::KEY_ID.")?
2051 };
2052
2053 // We may use a key by id after loading it by grant.
2054 // In this case we have to check if the caller has a grant for this particular
2055 // key. We can skip this if we already know that the caller is the owner.
2056 // But we cannot know this if domain is anything but App. E.g. in the case
2057 // of Domain::SELINUX we have to speculatively check for grants because we have to
2058 // consult the SEPolicy before we know if the caller is the owner.
2059 let access_vector: Option<KeyPermSet> =
2060 if domain != Domain::APP || namespace != caller_uid as i64 {
2061 let access_vector: Option<i32> = tx
2062 .query_row(
2063 "SELECT access_vector FROM persistent.grant
2064 WHERE grantee = ? AND keyentryid = ?;",
2065 params![caller_uid as i64, key.nspace],
2066 |row| row.get(0),
2067 )
2068 .optional()
2069 .context("Domain::KEY_ID: query grant failed.")?;
2070 access_vector.map(|p| p.into())
2071 } else {
2072 None
2073 };
2074
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002075 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002076 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002077 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002078 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002079
Janis Danisevskis45760022021-01-19 16:34:10 -08002080 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002081 }
Rajesh Nyamagoud625e5892022-05-18 01:31:26 +00002082 _ => Err(anyhow!(KsError::Rc(ResponseCode::INVALID_ARGUMENT))),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002083 }
2084 }
2085
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002086 fn load_blob_components(
2087 key_id: i64,
2088 load_bits: KeyEntryLoadBits,
2089 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002090 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002091 let mut stmt = tx
2092 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002093 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002094 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2095 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002096 .context(ks_err!("prepare statement failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002097
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002098 let mut rows = stmt.query(params![key_id]).context(ks_err!("query failed."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002099
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002100 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002101 let mut cert_blob: Option<Vec<u8>> = None;
2102 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002103 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002104 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002105 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002106 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002107 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002108 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2109 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002110 key_blob = Some((
2111 row.get(0).context("Failed to extract key blob id.")?,
2112 row.get(2).context("Failed to extract key blob.")?,
2113 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002114 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002115 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002116 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002117 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002118 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002119 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002120 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002121 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002122 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002123 (SubComponentType::CERT, _, _)
2124 | (SubComponentType::CERT_CHAIN, _, _)
2125 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002126 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2127 }
2128 Ok(())
2129 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002130 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002131
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002132 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2133 Ok(Some((
2134 blob,
2135 BlobMetaData::load_from_db(blob_id, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002136 .context(ks_err!("Trying to load blob_metadata."))?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002137 )))
2138 })?;
2139
2140 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002141 }
2142
2143 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2144 let mut stmt = tx
2145 .prepare(
2146 "SELECT tag, data, security_level from persistent.keyparameter
2147 WHERE keyentryid = ?;",
2148 )
2149 .context("In load_key_parameters: prepare statement failed.")?;
2150
2151 let mut parameters: Vec<KeyParameter> = Vec::new();
2152
2153 let mut rows =
2154 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002155 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002156 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2157 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002158 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002159 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002160 .context("Failed to read KeyParameter.")?,
2161 );
2162 Ok(())
2163 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002164 .context(ks_err!())?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002165
2166 Ok(parameters)
2167 }
2168
Qi Wub9433b52020-12-01 14:52:46 +08002169 /// Decrements the usage count of a limited use key. This function first checks whether the
2170 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2171 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2172 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002173 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002174 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2175
Qi Wub9433b52020-12-01 14:52:46 +08002176 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2177 let limit: Option<i32> = tx
2178 .query_row(
2179 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2180 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2181 |row| row.get(0),
2182 )
2183 .optional()
2184 .context("Trying to load usage count")?;
2185
2186 let limit = limit
2187 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2188 .context("The Key no longer exists. Key is exhausted.")?;
2189
2190 tx.execute(
2191 "UPDATE persistent.keyparameter
2192 SET data = data - 1
2193 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2194 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2195 )
2196 .context("Failed to update key usage count.")?;
2197
2198 match limit {
2199 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002200 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002201 .context("Trying to mark limited use key for deletion."),
2202 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002203 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002204 }
2205 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002206 .context(ks_err!())
Qi Wub9433b52020-12-01 14:52:46 +08002207 }
2208
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002209 /// Load a key entry by the given key descriptor.
2210 /// It uses the `check_permission` callback to verify if the access is allowed
2211 /// given the key access tuple read from the database using `load_access_tuple`.
2212 /// With `load_bits` the caller may specify which blobs shall be loaded from
2213 /// the blob database.
2214 pub fn load_key_entry(
2215 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002216 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002217 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002218 load_bits: KeyEntryLoadBits,
2219 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002220 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2221 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002222 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2223
Janis Danisevskis66784c42021-01-27 08:40:25 -08002224 loop {
2225 match self.load_key_entry_internal(
2226 key,
2227 key_type,
2228 load_bits,
2229 caller_uid,
2230 &check_permission,
2231 ) {
2232 Ok(result) => break Ok(result),
2233 Err(e) => {
2234 if Self::is_locked_error(&e) {
2235 std::thread::sleep(std::time::Duration::from_micros(500));
2236 continue;
2237 } else {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002238 return Err(e).context(ks_err!());
Janis Danisevskis66784c42021-01-27 08:40:25 -08002239 }
2240 }
2241 }
2242 }
2243 }
2244
2245 fn load_key_entry_internal(
2246 &mut self,
2247 key: &KeyDescriptor,
2248 key_type: KeyType,
2249 load_bits: KeyEntryLoadBits,
2250 caller_uid: u32,
2251 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002252 ) -> Result<(KeyIdGuard, KeyEntry)> {
2253 // KEY ID LOCK 1/2
2254 // If we got a key descriptor with a key id we can get the lock right away.
2255 // Otherwise we have to defer it until we know the key id.
2256 let key_id_guard = match key.domain {
2257 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2258 _ => None,
2259 };
2260
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002261 let tx = self
2262 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002263 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002264 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002265
2266 // Load the key_id and complete the access control tuple.
2267 let (key_id, access_key_descriptor, access_vector) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002268 Self::load_access_tuple(&tx, key, key_type, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002269
2270 // Perform access control. It is vital that we return here if the permission is denied.
2271 // So do not touch that '?' at the end.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002272 check_permission(&access_key_descriptor, access_vector).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002273
Janis Danisevskisaec14592020-11-12 09:41:49 -08002274 // KEY ID LOCK 2/2
2275 // If we did not get a key id lock by now, it was because we got a key descriptor
2276 // without a key id. At this point we got the key id, so we can try and get a lock.
2277 // However, we cannot block here, because we are in the middle of the transaction.
2278 // So first we try to get the lock non blocking. If that fails, we roll back the
2279 // transaction and block until we get the lock. After we successfully got the lock,
2280 // we start a new transaction and load the access tuple again.
2281 //
2282 // We don't need to perform access control again, because we already established
2283 // that the caller had access to the given key. But we need to make sure that the
2284 // key id still exists. So we have to load the key entry by key id this time.
2285 let (key_id_guard, tx) = match key_id_guard {
2286 None => match KEY_ID_LOCK.try_get(key_id) {
2287 None => {
2288 // Roll back the transaction.
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002289 tx.rollback().context(ks_err!("Failed to roll back transaction."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002290
Janis Danisevskisaec14592020-11-12 09:41:49 -08002291 // Block until we have a key id lock.
2292 let key_id_guard = KEY_ID_LOCK.get(key_id);
2293
2294 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002295 let tx = self
2296 .conn
2297 .unchecked_transaction()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002298 .context(ks_err!("Failed to initialize transaction."))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002299
2300 Self::load_access_tuple(
2301 &tx,
2302 // This time we have to load the key by the retrieved key id, because the
2303 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002304 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002305 domain: Domain::KEY_ID,
2306 nspace: key_id,
2307 ..Default::default()
2308 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002309 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002310 caller_uid,
2311 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002312 .context(ks_err!("(deferred key lock)"))?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002313 (key_id_guard, tx)
2314 }
2315 Some(l) => (l, tx),
2316 },
2317 Some(key_id_guard) => (key_id_guard, tx),
2318 };
2319
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002320 let key_entry =
2321 Self::load_key_components(&tx, load_bits, key_id_guard.id()).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002322
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002323 tx.commit().context(ks_err!("Failed to commit transaction."))?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002324
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002325 Ok((key_id_guard, key_entry))
2326 }
2327
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002328 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002329 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002330 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2331 .context("Trying to delete keyentry.")?;
2332 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2333 .context("Trying to delete keymetadata.")?;
2334 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2335 .context("Trying to delete keyparameters.")?;
2336 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2337 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002338 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002339 }
2340
2341 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002342 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002343 pub fn unbind_key(
2344 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002345 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002346 key_type: KeyType,
2347 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002348 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002349 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002350 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2351
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002352 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2353 let (key_id, access_key_descriptor, access_vector) =
2354 Self::load_access_tuple(tx, key, key_type, caller_uid)
2355 .context("Trying to get access tuple.")?;
2356
2357 // Perform access control. It is vital that we return here if the permission is denied.
2358 // So do not touch that '?' at the end.
2359 check_permission(&access_key_descriptor, access_vector)
2360 .context("While checking permission.")?;
2361
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002362 Self::mark_unreferenced(tx, key_id)
2363 .map(|need_gc| (need_gc, ()))
2364 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002365 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002366 .context(ks_err!())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002367 }
2368
Max Bires8e93d2b2021-01-14 13:17:59 -08002369 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2370 tx.query_row(
2371 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2372 params![key_id],
2373 |row| row.get(0),
2374 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002375 .context(ks_err!())
Max Bires8e93d2b2021-01-14 13:17:59 -08002376 }
2377
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002378 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2379 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2380 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002381 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2382
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002383 if !(domain == Domain::APP || domain == Domain::SELINUX) {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002384 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(ks_err!());
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002385 }
2386 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2387 tx.execute(
2388 "DELETE FROM persistent.keymetadata
2389 WHERE keyentryid IN (
2390 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002391 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002392 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002393 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002394 )
2395 .context("Trying to delete keymetadata.")?;
2396 tx.execute(
2397 "DELETE FROM persistent.keyparameter
2398 WHERE keyentryid IN (
2399 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002400 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002401 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002402 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002403 )
2404 .context("Trying to delete keyparameters.")?;
2405 tx.execute(
2406 "DELETE FROM persistent.grant
2407 WHERE keyentryid IN (
2408 SELECT id FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002409 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002410 );",
Tri Vo0346bbe2023-05-12 14:16:31 -04002411 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002412 )
2413 .context("Trying to delete grants.")?;
2414 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002415 "DELETE FROM persistent.keyentry
Tri Vo0346bbe2023-05-12 14:16:31 -04002416 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2417 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002418 )
2419 .context("Trying to delete keyentry.")?;
2420 Ok(()).need_gc()
2421 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002422 .context(ks_err!())
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002423 }
2424
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002425 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2426 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2427 {
2428 tx.execute(
2429 "DELETE FROM persistent.keymetadata
2430 WHERE keyentryid IN (
2431 SELECT id FROM persistent.keyentry
2432 WHERE state = ?
2433 );",
2434 params![KeyLifeCycle::Unreferenced],
2435 )
2436 .context("Trying to delete keymetadata.")?;
2437 tx.execute(
2438 "DELETE FROM persistent.keyparameter
2439 WHERE keyentryid IN (
2440 SELECT id FROM persistent.keyentry
2441 WHERE state = ?
2442 );",
2443 params![KeyLifeCycle::Unreferenced],
2444 )
2445 .context("Trying to delete keyparameters.")?;
2446 tx.execute(
2447 "DELETE FROM persistent.grant
2448 WHERE keyentryid IN (
2449 SELECT id FROM persistent.keyentry
2450 WHERE state = ?
2451 );",
2452 params![KeyLifeCycle::Unreferenced],
2453 )
2454 .context("Trying to delete grants.")?;
2455 tx.execute(
2456 "DELETE FROM persistent.keyentry
2457 WHERE state = ?;",
2458 params![KeyLifeCycle::Unreferenced],
2459 )
2460 .context("Trying to delete keyentry.")?;
2461 Result::<()>::Ok(())
2462 }
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002463 .context(ks_err!())
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002464 }
2465
Hasini Gunasingheda895552021-01-27 19:34:37 +00002466 /// Delete the keys created on behalf of the user, denoted by the user id.
2467 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2468 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2469 /// The caller of this function should notify the gc if the returned value is true.
2470 pub fn unbind_keys_for_user(
2471 &mut self,
2472 user_id: u32,
2473 keep_non_super_encrypted_keys: bool,
2474 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002475 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2476
Hasini Gunasingheda895552021-01-27 19:34:37 +00002477 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2478 let mut stmt = tx
2479 .prepare(&format!(
2480 "SELECT id from persistent.keyentry
2481 WHERE (
2482 key_type = ?
2483 AND domain = ?
2484 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2485 AND state = ?
2486 ) OR (
2487 key_type = ?
2488 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002489 AND state = ?
2490 );",
2491 aid_user_offset = AID_USER_OFFSET
2492 ))
2493 .context(concat!(
2494 "In unbind_keys_for_user. ",
2495 "Failed to prepare the query to find the keys created by apps."
2496 ))?;
2497
2498 let mut rows = stmt
2499 .query(params![
2500 // WHERE client key:
2501 KeyType::Client,
2502 Domain::APP.0 as u32,
2503 user_id,
2504 KeyLifeCycle::Live,
2505 // OR super key:
2506 KeyType::Super,
2507 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002508 KeyLifeCycle::Live
2509 ])
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002510 .context(ks_err!("Failed to query the keys created by apps."))?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002511
2512 let mut key_ids: Vec<i64> = Vec::new();
2513 db_utils::with_rows_extract_all(&mut rows, |row| {
2514 key_ids
2515 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2516 Ok(())
2517 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002518 .context(ks_err!())?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00002519
2520 let mut notify_gc = false;
2521 for key_id in key_ids {
2522 if keep_non_super_encrypted_keys {
2523 // Load metadata and filter out non-super-encrypted keys.
2524 if let (_, Some((_, blob_metadata)), _, _) =
2525 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002526 .context(ks_err!("Trying to load blob info."))?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002527 {
2528 if blob_metadata.encrypted_by().is_none() {
2529 continue;
2530 }
2531 }
2532 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002533 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002534 .context("In unbind_keys_for_user.")?
2535 || notify_gc;
2536 }
2537 Ok(()).do_gc(notify_gc)
2538 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002539 .context(ks_err!())
Hasini Gunasingheda895552021-01-27 19:34:37 +00002540 }
2541
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002542 fn load_key_components(
2543 tx: &Transaction,
2544 load_bits: KeyEntryLoadBits,
2545 key_id: i64,
2546 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002547 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002548
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002549 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002550 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002551
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002552 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002553 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002554
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002555 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002556 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002557
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002558 Ok(KeyEntry {
2559 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002560 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002561 cert: cert_blob,
2562 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002563 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002564 parameters,
2565 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002566 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002567 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002568 }
2569
Eran Messeri24f31972023-01-25 17:00:33 +00002570 /// Returns a list of KeyDescriptors in the selected domain/namespace whose
2571 /// aliases are greater than the specified 'start_past_alias'. If no value
2572 /// is provided, returns all KeyDescriptors.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002573 /// The key descriptors will have the domain, nspace, and alias field set.
Eran Messeri24f31972023-01-25 17:00:33 +00002574 /// The returned list will be sorted by alias.
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002575 /// Domain must be APP or SELINUX, the caller must make sure of that.
Eran Messeri24f31972023-01-25 17:00:33 +00002576 pub fn list_past_alias(
Janis Danisevskis18313832021-05-17 13:30:32 -07002577 &mut self,
2578 domain: Domain,
2579 namespace: i64,
2580 key_type: KeyType,
Eran Messeri24f31972023-01-25 17:00:33 +00002581 start_past_alias: Option<&str>,
Janis Danisevskis18313832021-05-17 13:30:32 -07002582 ) -> Result<Vec<KeyDescriptor>> {
Eran Messeri24f31972023-01-25 17:00:33 +00002583 let _wp = wd::watch_millis("KeystoreDB::list_past_alias", 500);
Janis Danisevskis850d4862021-05-05 08:41:14 -07002584
Eran Messeri24f31972023-01-25 17:00:33 +00002585 let query = format!(
2586 "SELECT DISTINCT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002587 WHERE domain = ?
2588 AND namespace = ?
2589 AND alias IS NOT NULL
2590 AND state = ?
Eran Messeri24f31972023-01-25 17:00:33 +00002591 AND key_type = ?
2592 {}
2593 ORDER BY alias ASC;",
2594 if start_past_alias.is_some() { " AND alias > ?" } else { "" }
2595 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002596
Eran Messeri24f31972023-01-25 17:00:33 +00002597 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2598 let mut stmt = tx.prepare(&query).context(ks_err!("Failed to prepare."))?;
2599
2600 let mut rows = match start_past_alias {
2601 Some(past_alias) => stmt
2602 .query(params![
2603 domain.0 as u32,
2604 namespace,
2605 KeyLifeCycle::Live,
2606 key_type,
2607 past_alias
2608 ])
2609 .context(ks_err!("Failed to query."))?,
2610 None => stmt
2611 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type,])
2612 .context(ks_err!("Failed to query."))?,
2613 };
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002614
Janis Danisevskis66784c42021-01-27 08:40:25 -08002615 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2616 db_utils::with_rows_extract_all(&mut rows, |row| {
2617 descriptors.push(KeyDescriptor {
2618 domain,
2619 nspace: namespace,
2620 alias: Some(row.get(0).context("Trying to extract alias.")?),
2621 blob: None,
2622 });
2623 Ok(())
2624 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002625 .context(ks_err!("Failed to extract rows."))?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002626 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002627 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002628 }
2629
Eran Messeri24f31972023-01-25 17:00:33 +00002630 /// Returns a number of KeyDescriptors in the selected domain/namespace.
2631 /// Domain must be APP or SELINUX, the caller must make sure of that.
2632 pub fn count_keys(
2633 &mut self,
2634 domain: Domain,
2635 namespace: i64,
2636 key_type: KeyType,
2637 ) -> Result<usize> {
2638 let _wp = wd::watch_millis("KeystoreDB::countKeys", 500);
2639
2640 let num_keys = self.with_transaction(TransactionBehavior::Deferred, |tx| {
2641 tx.query_row(
2642 "SELECT COUNT(alias) FROM persistent.keyentry
2643 WHERE domain = ?
2644 AND namespace = ?
2645 AND alias IS NOT NULL
2646 AND state = ?
2647 AND key_type = ?;",
2648 params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type],
2649 |row| row.get(0),
2650 )
2651 .context(ks_err!("Failed to count number of keys."))
2652 .no_gc()
2653 })?;
2654 Ok(num_keys)
2655 }
2656
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002657 /// Adds a grant to the grant table.
2658 /// Like `load_key_entry` this function loads the access tuple before
2659 /// it uses the callback for a permission check. Upon success,
2660 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2661 /// grant table. The new row will have a randomized id, which is used as
2662 /// grant id in the namespace field of the resulting KeyDescriptor.
2663 pub fn grant(
2664 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002665 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002666 caller_uid: u32,
2667 grantee_uid: u32,
2668 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002669 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002670 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002671 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
2672
Janis Danisevskis66784c42021-01-27 08:40:25 -08002673 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2674 // Load the key_id and complete the access control tuple.
2675 // We ignore the access vector here because grants cannot be granted.
2676 // The access vector returned here expresses the permissions the
2677 // grantee has if key.domain == Domain::GRANT. But this vector
2678 // cannot include the grant permission by design, so there is no way the
2679 // subsequent permission check can pass.
2680 // We could check key.domain == Domain::GRANT and fail early.
2681 // But even if we load the access tuple by grant here, the permission
2682 // check denies the attempt to create a grant by grant descriptor.
2683 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002684 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002685
Janis Danisevskis66784c42021-01-27 08:40:25 -08002686 // Perform access control. It is vital that we return here if the permission
2687 // was denied. So do not touch that '?' at the end of the line.
2688 // This permission check checks if the caller has the grant permission
2689 // for the given key and in addition to all of the permissions
2690 // expressed in `access_vector`.
2691 check_permission(&access_key_descriptor, &access_vector)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002692 .context(ks_err!("check_permission failed"))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002693
Janis Danisevskis66784c42021-01-27 08:40:25 -08002694 let grant_id = if let Some(grant_id) = tx
2695 .query_row(
2696 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002697 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002698 params![key_id, grantee_uid],
2699 |row| row.get(0),
2700 )
2701 .optional()
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002702 .context(ks_err!("Failed get optional existing grant id."))?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002703 {
2704 tx.execute(
2705 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002706 SET access_vector = ?
2707 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002708 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002709 )
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002710 .context(ks_err!("Failed to update existing grant."))?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002711 grant_id
2712 } else {
2713 Self::insert_with_retry(|id| {
2714 tx.execute(
2715 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2716 VALUES (?, ?, ?, ?);",
2717 params![id, grantee_uid, key_id, i32::from(access_vector)],
2718 )
2719 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002720 .context(ks_err!())?
Janis Danisevskis66784c42021-01-27 08:40:25 -08002721 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002722
Janis Danisevskis66784c42021-01-27 08:40:25 -08002723 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002724 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002725 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002726 }
2727
2728 /// This function checks permissions like `grant` and `load_key_entry`
2729 /// before removing a grant from the grant table.
2730 pub fn ungrant(
2731 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002732 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002733 caller_uid: u32,
2734 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002735 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002736 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002737 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
2738
Janis Danisevskis66784c42021-01-27 08:40:25 -08002739 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2740 // Load the key_id and complete the access control tuple.
2741 // We ignore the access vector here because grants cannot be granted.
2742 let (key_id, access_key_descriptor, _) =
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002743 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid).context(ks_err!())?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002744
Janis Danisevskis66784c42021-01-27 08:40:25 -08002745 // Perform access control. We must return here if the permission
2746 // was denied. So do not touch the '?' at the end of this line.
2747 check_permission(&access_key_descriptor)
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002748 .context(ks_err!("check_permission failed."))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002749
Janis Danisevskis66784c42021-01-27 08:40:25 -08002750 tx.execute(
2751 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002752 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002753 params![key_id, grantee_uid],
2754 )
2755 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002756
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002757 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002758 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002759 }
2760
Joel Galenson845f74b2020-09-09 14:11:55 -07002761 // Generates a random id and passes it to the given function, which will
2762 // try to insert it into a database. If that insertion fails, retry;
2763 // otherwise return the id.
2764 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2765 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002766 let newid: i64 = match random() {
2767 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2768 i => i,
2769 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002770 match inserter(newid) {
2771 // If the id already existed, try again.
2772 Err(rusqlite::Error::SqliteFailure(
2773 libsqlite3_sys::Error {
2774 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2775 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2776 },
2777 _,
2778 )) => (),
2779 Err(e) => {
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002780 return Err(e).context(ks_err!("failed to insert into database."));
Joel Galenson845f74b2020-09-09 14:11:55 -07002781 }
2782 _ => return Ok(newid),
2783 }
2784 }
2785 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002786
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002787 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
2788 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
2789 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
2790 auth_token.clone(),
2791 MonotonicRawTime::now(),
2792 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002793 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002794
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002795 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002796 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002797 where
2798 F: Fn(&AuthTokenEntry) -> bool,
2799 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002800 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002801 }
2802
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002803 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002804 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
2805 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002806 }
2807
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002808 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002809 pub fn update_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 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002814 fn get_last_off_body(&self) -> MonotonicRawTime {
2815 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002816 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01002817
2818 /// Load descriptor of a key by key id
2819 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
2820 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
2821
2822 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2823 tx.query_row(
2824 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
2825 params![key_id],
2826 |row| {
2827 Ok(KeyDescriptor {
2828 domain: Domain(row.get(0)?),
2829 nspace: row.get(1)?,
2830 alias: row.get(2)?,
2831 blob: None,
2832 })
2833 },
2834 )
2835 .optional()
2836 .context("Trying to load key descriptor")
2837 .no_gc()
2838 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002839 .context(ks_err!())
Pavel Grafovf45034a2021-05-12 22:35:45 +01002840 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002841}
2842
2843#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08002844pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07002845
2846 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002847 use crate::key_parameter::{
2848 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2849 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2850 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002851 use crate::key_perm_set;
2852 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08002853 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002854 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002855 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2856 HardwareAuthToken::HardwareAuthToken,
2857 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002858 };
2859 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002860 Timestamp::Timestamp,
2861 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002862 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002863 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07002864 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00002865 use std::collections::BTreeMap;
2866 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002867 use std::sync::atomic::{AtomicU8, Ordering};
Tri Vo0346bbe2023-05-12 14:16:31 -04002868 use std::sync::Arc;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002869 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002870 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002871 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002872 #[cfg(disabled)]
2873 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002874
Seth Moore7ee79f92021-12-07 11:42:49 -08002875 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002876 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002877
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002878 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002879 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002880 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002881 })?;
2882 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002883 }
2884
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002885 fn rebind_alias(
2886 db: &mut KeystoreDB,
2887 newid: &KeyIdGuard,
2888 alias: &str,
2889 domain: Domain,
2890 namespace: i64,
2891 ) -> Result<bool> {
2892 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002893 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002894 })
Shaquille Johnson9da2e1c2022-09-19 12:39:01 +00002895 .context(ks_err!())
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002896 }
2897
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002898 #[test]
2899 fn datetime() -> Result<()> {
2900 let conn = Connection::open_in_memory()?;
2901 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
2902 let now = SystemTime::now();
2903 let duration = Duration::from_secs(1000);
2904 let then = now.checked_sub(duration).unwrap();
2905 let soon = now.checked_add(duration).unwrap();
2906 conn.execute(
2907 "INSERT INTO test (ts) VALUES (?), (?), (?);",
2908 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
2909 )?;
2910 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
2911 let mut rows = stmt.query(NO_PARAMS)?;
2912 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
2913 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
2914 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
2915 assert!(rows.next()?.is_none());
2916 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
2917 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
2918 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
2919 Ok(())
2920 }
2921
Joel Galenson0891bc12020-07-20 10:37:03 -07002922 // Ensure that we're using the "injected" random function, not the real one.
2923 #[test]
2924 fn test_mocked_random() {
2925 let rand1 = random();
2926 let rand2 = random();
2927 let rand3 = random();
2928 if rand1 == rand2 {
2929 assert_eq!(rand2 + 1, rand3);
2930 } else {
2931 assert_eq!(rand1 + 1, rand2);
2932 assert_eq!(rand2, rand3);
2933 }
2934 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002935
Joel Galenson26f4d012020-07-17 14:57:21 -07002936 // Test that we have the correct tables.
2937 #[test]
2938 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002939 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07002940 let tables = db
2941 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07002942 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07002943 .query_map(params![], |row| row.get(0))?
2944 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002945 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002946 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002947 assert_eq!(tables[1], "blobmetadata");
2948 assert_eq!(tables[2], "grant");
2949 assert_eq!(tables[3], "keyentry");
2950 assert_eq!(tables[4], "keymetadata");
2951 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07002952 Ok(())
2953 }
2954
2955 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002956 fn test_auth_token_table_invariant() -> Result<()> {
2957 let mut db = new_test_db()?;
2958 let auth_token1 = HardwareAuthToken {
2959 challenge: i64::MAX,
2960 userId: 200,
2961 authenticatorId: 200,
2962 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2963 timestamp: Timestamp { milliSeconds: 500 },
2964 mac: String::from("mac").into_bytes(),
2965 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002966 db.insert_auth_token(&auth_token1);
2967 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002968 assert_eq!(auth_tokens_returned.len(), 1);
2969
2970 // insert another auth token with the same values for the columns in the UNIQUE constraint
2971 // of the auth token table and different value for timestamp
2972 let auth_token2 = HardwareAuthToken {
2973 challenge: i64::MAX,
2974 userId: 200,
2975 authenticatorId: 200,
2976 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2977 timestamp: Timestamp { milliSeconds: 600 },
2978 mac: String::from("mac").into_bytes(),
2979 };
2980
Matthew Maurerd7815ca2021-05-06 21:58:45 -07002981 db.insert_auth_token(&auth_token2);
2982 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002983 assert_eq!(auth_tokens_returned.len(), 1);
2984
2985 if let Some(auth_token) = auth_tokens_returned.pop() {
2986 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
2987 }
2988
2989 // insert another auth token with the different values for the columns in the UNIQUE
2990 // constraint of the auth token table
2991 let auth_token3 = HardwareAuthToken {
2992 challenge: i64::MAX,
2993 userId: 201,
2994 authenticatorId: 200,
2995 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
2996 timestamp: Timestamp { milliSeconds: 600 },
2997 mac: String::from("mac").into_bytes(),
2998 };
2999
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003000 db.insert_auth_token(&auth_token3);
3001 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003002 assert_eq!(auth_tokens_returned.len(), 2);
3003
3004 Ok(())
3005 }
3006
3007 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003008 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3009 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003010 }
3011
3012 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003013 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003014 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003015 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003016
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003017 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003018 let entries = get_keyentry(&db)?;
3019 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003020
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003021 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003022
3023 let entries_new = get_keyentry(&db)?;
3024 assert_eq!(entries, entries_new);
3025 Ok(())
3026 }
3027
3028 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003029 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003030 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3031 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003032 }
3033
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003034 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003035
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003036 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3037 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003038
3039 let entries = get_keyentry(&db)?;
3040 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003041 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3042 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003043
3044 // Test that we must pass in a valid Domain.
3045 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003046 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003047 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson0891bc12020-07-20 10:37:03 -07003048 );
3049 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003050 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003051 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
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::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003055 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson0891bc12020-07-20 10:37:03 -07003056 );
3057
3058 Ok(())
3059 }
3060
Joel Galenson33c04ad2020-08-03 11:04:38 -07003061 #[test]
3062 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003063 fn extractor(
3064 ke: &KeyEntryRow,
3065 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3066 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003067 }
3068
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003069 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003070 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3071 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003072 let entries = get_keyentry(&db)?;
3073 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003074 assert_eq!(
3075 extractor(&entries[0]),
3076 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3077 );
3078 assert_eq!(
3079 extractor(&entries[1]),
3080 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3081 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003082
3083 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003084 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003085 let entries = get_keyentry(&db)?;
3086 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003087 assert_eq!(
3088 extractor(&entries[0]),
3089 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3090 );
3091 assert_eq!(
3092 extractor(&entries[1]),
3093 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3094 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003095
3096 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003097 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003098 let entries = get_keyentry(&db)?;
3099 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003100 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3101 assert_eq!(
3102 extractor(&entries[1]),
3103 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3104 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003105
3106 // Test that we must pass in a valid Domain.
3107 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003108 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003109 &format!("Domain {:?} must be either App or SELinux.", Domain::GRANT),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003110 );
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::BLOB, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003113 &format!("Domain {:?} must be either App or SELinux.", Domain::BLOB),
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::KEY_ID, 42),
Shaquille Johnson1f1d5152022-10-11 13:29:43 +01003117 &format!("Domain {:?} must be either App or SELinux.", Domain::KEY_ID),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003118 );
3119
3120 // Test that we correctly handle setting an alias for something that does not exist.
3121 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003122 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003123 "Expected to update a single entry but instead updated 0",
3124 );
3125 // Test that we correctly abort the transaction in this case.
3126 let entries = get_keyentry(&db)?;
3127 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003128 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3129 assert_eq!(
3130 extractor(&entries[1]),
3131 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3132 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003133
3134 Ok(())
3135 }
3136
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003137 #[test]
3138 fn test_grant_ungrant() -> Result<()> {
3139 const CALLER_UID: u32 = 15;
3140 const GRANTEE_UID: u32 = 12;
3141 const SELINUX_NAMESPACE: i64 = 7;
3142
3143 let mut db = new_test_db()?;
3144 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003145 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3146 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3147 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003148 )?;
3149 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003150 domain: super::Domain::APP,
3151 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003152 alias: Some("key".to_string()),
3153 blob: None,
3154 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003155 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3156 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003157
3158 // Reset totally predictable random number generator in case we
3159 // are not the first test running on this thread.
3160 reset_random();
3161 let next_random = 0i64;
3162
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003163 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003164 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003165 assert_eq!(*a, PVEC1);
3166 assert_eq!(
3167 *k,
3168 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003169 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003170 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003171 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003172 alias: Some("key".to_string()),
3173 blob: None,
3174 }
3175 );
3176 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003177 })
3178 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003179
3180 assert_eq!(
3181 app_granted_key,
3182 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003183 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003184 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003185 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003186 alias: None,
3187 blob: None,
3188 }
3189 );
3190
3191 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003192 domain: super::Domain::SELINUX,
3193 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003194 alias: Some("yek".to_string()),
3195 blob: None,
3196 };
3197
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003198 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003199 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003200 assert_eq!(*a, PVEC1);
3201 assert_eq!(
3202 *k,
3203 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003204 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003205 // namespace must be the supplied SELinux
3206 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003207 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003208 alias: Some("yek".to_string()),
3209 blob: None,
3210 }
3211 );
3212 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003213 })
3214 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003215
3216 assert_eq!(
3217 selinux_granted_key,
3218 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003219 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003220 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003221 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003222 alias: None,
3223 blob: None,
3224 }
3225 );
3226
3227 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003228 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003229 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003230 assert_eq!(*a, PVEC2);
3231 assert_eq!(
3232 *k,
3233 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003234 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003235 // namespace must be the supplied SELinux
3236 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003237 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003238 alias: Some("yek".to_string()),
3239 blob: None,
3240 }
3241 );
3242 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003243 })
3244 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003245
3246 assert_eq!(
3247 selinux_granted_key,
3248 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003249 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003250 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003251 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003252 alias: None,
3253 blob: None,
3254 }
3255 );
3256
3257 {
3258 // Limiting scope of stmt, because it borrows db.
3259 let mut stmt = db
3260 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003261 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003262 let mut rows =
3263 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3264 Ok((
3265 row.get(0)?,
3266 row.get(1)?,
3267 row.get(2)?,
3268 KeyPermSet::from(row.get::<_, i32>(3)?),
3269 ))
3270 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003271
3272 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003273 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003274 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003275 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003276 assert!(rows.next().is_none());
3277 }
3278
3279 debug_dump_keyentry_table(&mut db)?;
3280 println!("app_key {:?}", app_key);
3281 println!("selinux_key {:?}", selinux_key);
3282
Janis Danisevskis66784c42021-01-27 08:40:25 -08003283 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3284 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003285
3286 Ok(())
3287 }
3288
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003289 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003290 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3291 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3292
3293 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003294 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003295 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003296 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003297 let mut blob_metadata = BlobMetaData::new();
3298 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3299 db.set_blob(
3300 &key_id,
3301 SubComponentType::KEY_BLOB,
3302 Some(TEST_KEY_BLOB),
3303 Some(&blob_metadata),
3304 )?;
3305 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3306 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003307 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003308
3309 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003310 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003311 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003312 )?;
3313 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003314 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3315 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003316 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003317 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003318 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_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, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003321 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003322 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003323
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003324 drop(rows);
3325 drop(stmt);
3326
3327 assert_eq!(
3328 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3329 BlobMetaData::load_from_db(id, tx).no_gc()
3330 })
3331 .expect("Should find blob metadata."),
3332 blob_metadata
3333 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003334 Ok(())
3335 }
3336
3337 static TEST_ALIAS: &str = "my super duper key";
3338
3339 #[test]
3340 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3341 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003342 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003343 .context("test_insert_and_load_full_keyentry_domain_app")?
3344 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003345 let (_key_guard, key_entry) = db
3346 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003347 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003348 domain: Domain::APP,
3349 nspace: 0,
3350 alias: Some(TEST_ALIAS.to_string()),
3351 blob: None,
3352 },
3353 KeyType::Client,
3354 KeyEntryLoadBits::BOTH,
3355 1,
3356 |_k, _av| Ok(()),
3357 )
3358 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003359 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003360
3361 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003362 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003363 domain: Domain::APP,
3364 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003365 alias: Some(TEST_ALIAS.to_string()),
3366 blob: None,
3367 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003368 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003369 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003370 |_, _| Ok(()),
3371 )
3372 .unwrap();
3373
3374 assert_eq!(
3375 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3376 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003377 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003378 domain: Domain::APP,
3379 nspace: 0,
3380 alias: Some(TEST_ALIAS.to_string()),
3381 blob: None,
3382 },
3383 KeyType::Client,
3384 KeyEntryLoadBits::NONE,
3385 1,
3386 |_k, _av| Ok(()),
3387 )
3388 .unwrap_err()
3389 .root_cause()
3390 .downcast_ref::<KsError>()
3391 );
3392
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003393 Ok(())
3394 }
3395
3396 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003397 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3398 let mut db = new_test_db()?;
3399
3400 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003401 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003402 domain: Domain::APP,
3403 nspace: 1,
3404 alias: Some(TEST_ALIAS.to_string()),
3405 blob: None,
3406 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003407 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003408 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003409 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003410 )
3411 .expect("Trying to insert cert.");
3412
3413 let (_key_guard, mut key_entry) = db
3414 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003415 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003416 domain: Domain::APP,
3417 nspace: 1,
3418 alias: Some(TEST_ALIAS.to_string()),
3419 blob: None,
3420 },
3421 KeyType::Client,
3422 KeyEntryLoadBits::PUBLIC,
3423 1,
3424 |_k, _av| Ok(()),
3425 )
3426 .expect("Trying to read certificate entry.");
3427
3428 assert!(key_entry.pure_cert());
3429 assert!(key_entry.cert().is_none());
3430 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3431
3432 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003433 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003434 domain: Domain::APP,
3435 nspace: 1,
3436 alias: Some(TEST_ALIAS.to_string()),
3437 blob: None,
3438 },
3439 KeyType::Client,
3440 1,
3441 |_, _| Ok(()),
3442 )
3443 .unwrap();
3444
3445 assert_eq!(
3446 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3447 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003448 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003449 domain: Domain::APP,
3450 nspace: 1,
3451 alias: Some(TEST_ALIAS.to_string()),
3452 blob: None,
3453 },
3454 KeyType::Client,
3455 KeyEntryLoadBits::NONE,
3456 1,
3457 |_k, _av| Ok(()),
3458 )
3459 .unwrap_err()
3460 .root_cause()
3461 .downcast_ref::<KsError>()
3462 );
3463
3464 Ok(())
3465 }
3466
3467 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003468 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3469 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003470 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003471 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3472 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003473 let (_key_guard, key_entry) = db
3474 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003475 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003476 domain: Domain::SELINUX,
3477 nspace: 1,
3478 alias: Some(TEST_ALIAS.to_string()),
3479 blob: None,
3480 },
3481 KeyType::Client,
3482 KeyEntryLoadBits::BOTH,
3483 1,
3484 |_k, _av| Ok(()),
3485 )
3486 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003487 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003488
3489 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003490 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003491 domain: Domain::SELINUX,
3492 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003493 alias: Some(TEST_ALIAS.to_string()),
3494 blob: None,
3495 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003496 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003497 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003498 |_, _| Ok(()),
3499 )
3500 .unwrap();
3501
3502 assert_eq!(
3503 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3504 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003505 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003506 domain: Domain::SELINUX,
3507 nspace: 1,
3508 alias: Some(TEST_ALIAS.to_string()),
3509 blob: None,
3510 },
3511 KeyType::Client,
3512 KeyEntryLoadBits::NONE,
3513 1,
3514 |_k, _av| Ok(()),
3515 )
3516 .unwrap_err()
3517 .root_cause()
3518 .downcast_ref::<KsError>()
3519 );
3520
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003521 Ok(())
3522 }
3523
3524 #[test]
3525 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3526 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003527 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003528 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3529 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003530 let (_, key_entry) = db
3531 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003532 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003533 KeyType::Client,
3534 KeyEntryLoadBits::BOTH,
3535 1,
3536 |_k, _av| Ok(()),
3537 )
3538 .unwrap();
3539
Qi Wub9433b52020-12-01 14:52:46 +08003540 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003541
3542 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003543 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003544 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003545 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003546 |_, _| Ok(()),
3547 )
3548 .unwrap();
3549
3550 assert_eq!(
3551 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3552 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003553 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003554 KeyType::Client,
3555 KeyEntryLoadBits::NONE,
3556 1,
3557 |_k, _av| Ok(()),
3558 )
3559 .unwrap_err()
3560 .root_cause()
3561 .downcast_ref::<KsError>()
3562 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003563
3564 Ok(())
3565 }
3566
3567 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003568 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3569 let mut db = new_test_db()?;
3570 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3571 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3572 .0;
3573 // Update the usage count of the limited use key.
3574 db.check_and_update_key_usage_count(key_id)?;
3575
3576 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003577 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003578 KeyType::Client,
3579 KeyEntryLoadBits::BOTH,
3580 1,
3581 |_k, _av| Ok(()),
3582 )?;
3583
3584 // The usage count is decremented now.
3585 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3586
3587 Ok(())
3588 }
3589
3590 #[test]
3591 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3592 let mut db = new_test_db()?;
3593 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3594 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3595 .0;
3596 // Update the usage count of the limited use key.
3597 db.check_and_update_key_usage_count(key_id).expect(concat!(
3598 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3599 "This should succeed."
3600 ));
3601
3602 // Try to update the exhausted limited use key.
3603 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3604 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3605 "This should fail."
3606 ));
3607 assert_eq!(
3608 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3609 e.root_cause().downcast_ref::<KsError>().unwrap()
3610 );
3611
3612 Ok(())
3613 }
3614
3615 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003616 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3617 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003618 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003619 .context("test_insert_and_load_full_keyentry_from_grant")?
3620 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003621
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003622 let granted_key = db
3623 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003624 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003625 domain: Domain::APP,
3626 nspace: 0,
3627 alias: Some(TEST_ALIAS.to_string()),
3628 blob: None,
3629 },
3630 1,
3631 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003632 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003633 |_k, _av| Ok(()),
3634 )
3635 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003636
3637 debug_dump_grant_table(&mut db)?;
3638
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003639 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003640 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3641 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003642 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08003643 Ok(())
3644 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003645 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003646
Qi Wub9433b52020-12-01 14:52:46 +08003647 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003648
Janis Danisevskis66784c42021-01-27 08:40:25 -08003649 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003650
3651 assert_eq!(
3652 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3653 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003654 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003655 KeyType::Client,
3656 KeyEntryLoadBits::NONE,
3657 2,
3658 |_k, _av| Ok(()),
3659 )
3660 .unwrap_err()
3661 .root_cause()
3662 .downcast_ref::<KsError>()
3663 );
3664
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003665 Ok(())
3666 }
3667
Janis Danisevskis45760022021-01-19 16:34:10 -08003668 // This test attempts to load a key by key id while the caller is not the owner
3669 // but a grant exists for the given key and the caller.
3670 #[test]
3671 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3672 let mut db = new_test_db()?;
3673 const OWNER_UID: u32 = 1u32;
3674 const GRANTEE_UID: u32 = 2u32;
3675 const SOMEONE_ELSE_UID: u32 = 3u32;
3676 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3677 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3678 .0;
3679
3680 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003681 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003682 domain: Domain::APP,
3683 nspace: 0,
3684 alias: Some(TEST_ALIAS.to_string()),
3685 blob: None,
3686 },
3687 OWNER_UID,
3688 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003689 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08003690 |_k, _av| Ok(()),
3691 )
3692 .unwrap();
3693
3694 debug_dump_grant_table(&mut db)?;
3695
3696 let id_descriptor =
3697 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3698
3699 let (_, key_entry) = db
3700 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003701 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003702 KeyType::Client,
3703 KeyEntryLoadBits::BOTH,
3704 GRANTEE_UID,
3705 |k, av| {
3706 assert_eq!(Domain::APP, k.domain);
3707 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003708 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08003709 Ok(())
3710 },
3711 )
3712 .unwrap();
3713
3714 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3715
3716 let (_, key_entry) = db
3717 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003718 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003719 KeyType::Client,
3720 KeyEntryLoadBits::BOTH,
3721 SOMEONE_ELSE_UID,
3722 |k, av| {
3723 assert_eq!(Domain::APP, k.domain);
3724 assert_eq!(OWNER_UID as i64, k.nspace);
3725 assert!(av.is_none());
3726 Ok(())
3727 },
3728 )
3729 .unwrap();
3730
3731 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3732
Janis Danisevskis66784c42021-01-27 08:40:25 -08003733 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08003734
3735 assert_eq!(
3736 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3737 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003738 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003739 KeyType::Client,
3740 KeyEntryLoadBits::NONE,
3741 GRANTEE_UID,
3742 |_k, _av| Ok(()),
3743 )
3744 .unwrap_err()
3745 .root_cause()
3746 .downcast_ref::<KsError>()
3747 );
3748
3749 Ok(())
3750 }
3751
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003752 // Creates a key migrates it to a different location and then tries to access it by the old
3753 // and new location.
3754 #[test]
3755 fn test_migrate_key_app_to_app() -> Result<()> {
3756 let mut db = new_test_db()?;
3757 const SOURCE_UID: u32 = 1u32;
3758 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003759 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3760 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003761 let key_id_guard =
3762 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3763 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3764
3765 let source_descriptor: KeyDescriptor = KeyDescriptor {
3766 domain: Domain::APP,
3767 nspace: -1,
3768 alias: Some(SOURCE_ALIAS.to_string()),
3769 blob: None,
3770 };
3771
3772 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3773 domain: Domain::APP,
3774 nspace: -1,
3775 alias: Some(DESTINATION_ALIAS.to_string()),
3776 blob: None,
3777 };
3778
3779 let key_id = key_id_guard.id();
3780
3781 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3782 Ok(())
3783 })
3784 .unwrap();
3785
3786 let (_, key_entry) = db
3787 .load_key_entry(
3788 &destination_descriptor,
3789 KeyType::Client,
3790 KeyEntryLoadBits::BOTH,
3791 DESTINATION_UID,
3792 |k, av| {
3793 assert_eq!(Domain::APP, k.domain);
3794 assert_eq!(DESTINATION_UID as i64, k.nspace);
3795 assert!(av.is_none());
3796 Ok(())
3797 },
3798 )
3799 .unwrap();
3800
3801 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3802
3803 assert_eq!(
3804 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3805 db.load_key_entry(
3806 &source_descriptor,
3807 KeyType::Client,
3808 KeyEntryLoadBits::NONE,
3809 SOURCE_UID,
3810 |_k, _av| Ok(()),
3811 )
3812 .unwrap_err()
3813 .root_cause()
3814 .downcast_ref::<KsError>()
3815 );
3816
3817 Ok(())
3818 }
3819
3820 // Creates a key migrates it to a different location and then tries to access it by the old
3821 // and new location.
3822 #[test]
3823 fn test_migrate_key_app_to_selinux() -> Result<()> {
3824 let mut db = new_test_db()?;
3825 const SOURCE_UID: u32 = 1u32;
3826 const DESTINATION_UID: u32 = 2u32;
3827 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003828 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3829 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003830 let key_id_guard =
3831 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3832 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3833
3834 let source_descriptor: KeyDescriptor = KeyDescriptor {
3835 domain: Domain::APP,
3836 nspace: -1,
3837 alias: Some(SOURCE_ALIAS.to_string()),
3838 blob: None,
3839 };
3840
3841 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3842 domain: Domain::SELINUX,
3843 nspace: DESTINATION_NAMESPACE,
3844 alias: Some(DESTINATION_ALIAS.to_string()),
3845 blob: None,
3846 };
3847
3848 let key_id = key_id_guard.id();
3849
3850 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
3851 Ok(())
3852 })
3853 .unwrap();
3854
3855 let (_, key_entry) = db
3856 .load_key_entry(
3857 &destination_descriptor,
3858 KeyType::Client,
3859 KeyEntryLoadBits::BOTH,
3860 DESTINATION_UID,
3861 |k, av| {
3862 assert_eq!(Domain::SELINUX, k.domain);
Charisee03e00842023-01-25 01:41:23 +00003863 assert_eq!(DESTINATION_NAMESPACE, k.nspace);
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003864 assert!(av.is_none());
3865 Ok(())
3866 },
3867 )
3868 .unwrap();
3869
3870 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3871
3872 assert_eq!(
3873 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3874 db.load_key_entry(
3875 &source_descriptor,
3876 KeyType::Client,
3877 KeyEntryLoadBits::NONE,
3878 SOURCE_UID,
3879 |_k, _av| Ok(()),
3880 )
3881 .unwrap_err()
3882 .root_cause()
3883 .downcast_ref::<KsError>()
3884 );
3885
3886 Ok(())
3887 }
3888
3889 // Creates two keys and tries to migrate the first to the location of the second which
3890 // is expected to fail.
3891 #[test]
3892 fn test_migrate_key_destination_occupied() -> Result<()> {
3893 let mut db = new_test_db()?;
3894 const SOURCE_UID: u32 = 1u32;
3895 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003896 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
3897 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07003898 let key_id_guard =
3899 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
3900 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3901 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
3902 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
3903
3904 let destination_descriptor: KeyDescriptor = KeyDescriptor {
3905 domain: Domain::APP,
3906 nspace: -1,
3907 alias: Some(DESTINATION_ALIAS.to_string()),
3908 blob: None,
3909 };
3910
3911 assert_eq!(
3912 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
3913 db.migrate_key_namespace(
3914 key_id_guard,
3915 &destination_descriptor,
3916 DESTINATION_UID,
3917 |_k| Ok(())
3918 )
3919 .unwrap_err()
3920 .root_cause()
3921 .downcast_ref::<KsError>()
3922 );
3923
3924 Ok(())
3925 }
3926
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003927 #[test]
3928 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003929 const ALIAS1: &str = "test_upgrade_0_to_1_1";
3930 const ALIAS2: &str = "test_upgrade_0_to_1_2";
3931 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07003932 const UID: u32 = 33;
3933 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
3934 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
3935 let key_id_untouched1 =
3936 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
3937 let key_id_untouched2 =
3938 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
3939 let key_id_deleted =
3940 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
3941
3942 let (_, key_entry) = db
3943 .load_key_entry(
3944 &KeyDescriptor {
3945 domain: Domain::APP,
3946 nspace: -1,
3947 alias: Some(ALIAS1.to_string()),
3948 blob: None,
3949 },
3950 KeyType::Client,
3951 KeyEntryLoadBits::BOTH,
3952 UID,
3953 |k, av| {
3954 assert_eq!(Domain::APP, k.domain);
3955 assert_eq!(UID as i64, k.nspace);
3956 assert!(av.is_none());
3957 Ok(())
3958 },
3959 )
3960 .unwrap();
3961 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
3962 let (_, key_entry) = db
3963 .load_key_entry(
3964 &KeyDescriptor {
3965 domain: Domain::APP,
3966 nspace: -1,
3967 alias: Some(ALIAS2.to_string()),
3968 blob: None,
3969 },
3970 KeyType::Client,
3971 KeyEntryLoadBits::BOTH,
3972 UID,
3973 |k, av| {
3974 assert_eq!(Domain::APP, k.domain);
3975 assert_eq!(UID as i64, k.nspace);
3976 assert!(av.is_none());
3977 Ok(())
3978 },
3979 )
3980 .unwrap();
3981 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
3982 let (_, key_entry) = db
3983 .load_key_entry(
3984 &KeyDescriptor {
3985 domain: Domain::APP,
3986 nspace: -1,
3987 alias: Some(ALIAS3.to_string()),
3988 blob: None,
3989 },
3990 KeyType::Client,
3991 KeyEntryLoadBits::BOTH,
3992 UID,
3993 |k, av| {
3994 assert_eq!(Domain::APP, k.domain);
3995 assert_eq!(UID as i64, k.nspace);
3996 assert!(av.is_none());
3997 Ok(())
3998 },
3999 )
4000 .unwrap();
4001 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4002
4003 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4004 KeystoreDB::from_0_to_1(tx).no_gc()
4005 })
4006 .unwrap();
4007
4008 let (_, key_entry) = db
4009 .load_key_entry(
4010 &KeyDescriptor {
4011 domain: Domain::APP,
4012 nspace: -1,
4013 alias: Some(ALIAS1.to_string()),
4014 blob: None,
4015 },
4016 KeyType::Client,
4017 KeyEntryLoadBits::BOTH,
4018 UID,
4019 |k, av| {
4020 assert_eq!(Domain::APP, k.domain);
4021 assert_eq!(UID as i64, k.nspace);
4022 assert!(av.is_none());
4023 Ok(())
4024 },
4025 )
4026 .unwrap();
4027 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4028 let (_, key_entry) = db
4029 .load_key_entry(
4030 &KeyDescriptor {
4031 domain: Domain::APP,
4032 nspace: -1,
4033 alias: Some(ALIAS2.to_string()),
4034 blob: None,
4035 },
4036 KeyType::Client,
4037 KeyEntryLoadBits::BOTH,
4038 UID,
4039 |k, av| {
4040 assert_eq!(Domain::APP, k.domain);
4041 assert_eq!(UID as i64, k.nspace);
4042 assert!(av.is_none());
4043 Ok(())
4044 },
4045 )
4046 .unwrap();
4047 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4048 assert_eq!(
4049 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4050 db.load_key_entry(
4051 &KeyDescriptor {
4052 domain: Domain::APP,
4053 nspace: -1,
4054 alias: Some(ALIAS3.to_string()),
4055 blob: None,
4056 },
4057 KeyType::Client,
4058 KeyEntryLoadBits::BOTH,
4059 UID,
4060 |k, av| {
4061 assert_eq!(Domain::APP, k.domain);
4062 assert_eq!(UID as i64, k.nspace);
4063 assert!(av.is_none());
4064 Ok(())
4065 },
4066 )
4067 .unwrap_err()
4068 .root_cause()
4069 .downcast_ref::<KsError>()
4070 );
4071 }
4072
Janis Danisevskisaec14592020-11-12 09:41:49 -08004073 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4074
Janis Danisevskisaec14592020-11-12 09:41:49 -08004075 #[test]
4076 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4077 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004078 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4079 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004080 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004081 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004082 .context("test_insert_and_load_full_keyentry_domain_app")?
4083 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004084 let (_key_guard, key_entry) = db
4085 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004086 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004087 domain: Domain::APP,
4088 nspace: 0,
4089 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4090 blob: None,
4091 },
4092 KeyType::Client,
4093 KeyEntryLoadBits::BOTH,
4094 33,
4095 |_k, _av| Ok(()),
4096 )
4097 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004098 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004099 let state = Arc::new(AtomicU8::new(1));
4100 let state2 = state.clone();
4101
4102 // Spawning a second thread that attempts to acquire the key id lock
4103 // for the same key as the primary thread. The primary thread then
4104 // waits, thereby forcing the secondary thread into the second stage
4105 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4106 // The test succeeds if the secondary thread observes the transition
4107 // of `state` from 1 to 2, despite having a whole second to overtake
4108 // the primary thread.
4109 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004110 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004111 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004112 assert!(db
4113 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004114 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004115 domain: Domain::APP,
4116 nspace: 0,
4117 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4118 blob: None,
4119 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004120 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004121 KeyEntryLoadBits::BOTH,
4122 33,
4123 |_k, _av| Ok(()),
4124 )
4125 .is_ok());
4126 // We should only see a 2 here because we can only return
4127 // from load_key_entry when the `_key_guard` expires,
4128 // which happens at the end of the scope.
4129 assert_eq!(2, state2.load(Ordering::Relaxed));
4130 });
4131
4132 thread::sleep(std::time::Duration::from_millis(1000));
4133
4134 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4135
4136 // Return the handle from this scope so we can join with the
4137 // secondary thread after the key id lock has expired.
4138 handle
4139 // This is where the `_key_guard` goes out of scope,
4140 // which is the reason for concurrent load_key_entry on the same key
4141 // to unblock.
4142 };
4143 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4144 // main test thread. We will not see failing asserts in secondary threads otherwise.
4145 handle.join().unwrap();
4146 Ok(())
4147 }
4148
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004149 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004150 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004151 let temp_dir =
4152 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4153
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004154 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4155 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004156
4157 let _tx1 = db1
4158 .conn
4159 .transaction_with_behavior(TransactionBehavior::Immediate)
4160 .expect("Failed to create first transaction.");
4161
4162 let error = db2
4163 .conn
4164 .transaction_with_behavior(TransactionBehavior::Immediate)
4165 .context("Transaction begin failed.")
4166 .expect_err("This should fail.");
4167 let root_cause = error.root_cause();
4168 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4169 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4170 {
4171 return;
4172 }
4173 panic!(
4174 "Unexpected error {:?} \n{:?} \n{:?}",
4175 error,
4176 root_cause,
4177 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4178 )
4179 }
4180
4181 #[cfg(disabled)]
4182 #[test]
4183 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4184 let temp_dir = Arc::new(
4185 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4186 .expect("Failed to create temp dir."),
4187 );
4188
4189 let test_begin = Instant::now();
4190
Janis Danisevskis66784c42021-01-27 08:40:25 -08004191 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004192 let mut db =
4193 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004194 const OPEN_DB_COUNT: u32 = 50u32;
4195
4196 let mut actual_key_count = KEY_COUNT;
4197 // First insert KEY_COUNT keys.
4198 for count in 0..KEY_COUNT {
4199 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4200 actual_key_count = count;
4201 break;
4202 }
4203 let alias = format!("test_alias_{}", count);
4204 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4205 .expect("Failed to make key entry.");
4206 }
4207
4208 // Insert more keys from a different thread and into a different namespace.
4209 let temp_dir1 = temp_dir.clone();
4210 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004211 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4212 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004213
4214 for count in 0..actual_key_count {
4215 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4216 return;
4217 }
4218 let alias = format!("test_alias_{}", count);
4219 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4220 .expect("Failed to make key entry.");
4221 }
4222
4223 // then unbind them again.
4224 for count in 0..actual_key_count {
4225 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4226 return;
4227 }
4228 let key = KeyDescriptor {
4229 domain: Domain::APP,
4230 nspace: -1,
4231 alias: Some(format!("test_alias_{}", count)),
4232 blob: None,
4233 };
4234 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4235 }
4236 });
4237
4238 // And start unbinding the first set of keys.
4239 let temp_dir2 = temp_dir.clone();
4240 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004241 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4242 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004243
4244 for count in 0..actual_key_count {
4245 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4246 return;
4247 }
4248 let key = KeyDescriptor {
4249 domain: Domain::APP,
4250 nspace: -1,
4251 alias: Some(format!("test_alias_{}", count)),
4252 blob: None,
4253 };
4254 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4255 }
4256 });
4257
Janis Danisevskis66784c42021-01-27 08:40:25 -08004258 // While a lot of inserting and deleting is going on we have to open database connections
4259 // successfully and use them.
4260 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4261 // out of scope.
4262 #[allow(clippy::redundant_clone)]
4263 let temp_dir4 = temp_dir.clone();
4264 let handle4 = thread::spawn(move || {
4265 for count in 0..OPEN_DB_COUNT {
4266 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4267 return;
4268 }
Seth Moore444b51a2021-06-11 09:49:49 -07004269 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4270 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004271
4272 let alias = format!("test_alias_{}", count);
4273 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4274 .expect("Failed to make key entry.");
4275 let key = KeyDescriptor {
4276 domain: Domain::APP,
4277 nspace: -1,
4278 alias: Some(alias),
4279 blob: None,
4280 };
4281 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4282 }
4283 });
4284
4285 handle1.join().expect("Thread 1 panicked.");
4286 handle2.join().expect("Thread 2 panicked.");
4287 handle4.join().expect("Thread 4 panicked.");
4288
Janis Danisevskis66784c42021-01-27 08:40:25 -08004289 Ok(())
4290 }
4291
4292 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004293 fn list() -> Result<()> {
4294 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004295 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004296 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4297 (Domain::APP, 1, "test1"),
4298 (Domain::APP, 1, "test2"),
4299 (Domain::APP, 1, "test3"),
4300 (Domain::APP, 1, "test4"),
4301 (Domain::APP, 1, "test5"),
4302 (Domain::APP, 1, "test6"),
4303 (Domain::APP, 1, "test7"),
4304 (Domain::APP, 2, "test1"),
4305 (Domain::APP, 2, "test2"),
4306 (Domain::APP, 2, "test3"),
4307 (Domain::APP, 2, "test4"),
4308 (Domain::APP, 2, "test5"),
4309 (Domain::APP, 2, "test6"),
4310 (Domain::APP, 2, "test8"),
4311 (Domain::SELINUX, 100, "test1"),
4312 (Domain::SELINUX, 100, "test2"),
4313 (Domain::SELINUX, 100, "test3"),
4314 (Domain::SELINUX, 100, "test4"),
4315 (Domain::SELINUX, 100, "test5"),
4316 (Domain::SELINUX, 100, "test6"),
4317 (Domain::SELINUX, 100, "test9"),
4318 ];
4319
4320 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4321 .iter()
4322 .map(|(domain, ns, alias)| {
Chris Wailesdabb6fe2022-11-16 15:56:19 -08004323 let entry =
4324 make_test_key_entry(&mut db, *domain, *ns, alias, None).unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004325 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4326 });
4327 (entry.id(), *ns)
4328 })
4329 .collect();
4330
4331 for (domain, namespace) in
4332 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4333 {
4334 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4335 .iter()
4336 .filter_map(|(domain, ns, alias)| match ns {
4337 ns if *ns == *namespace => Some(KeyDescriptor {
4338 domain: *domain,
4339 nspace: *ns,
4340 alias: Some(alias.to_string()),
4341 blob: None,
4342 }),
4343 _ => None,
4344 })
4345 .collect();
4346 list_o_descriptors.sort();
Eran Messeri24f31972023-01-25 17:00:33 +00004347 let mut list_result = db.list_past_alias(*domain, *namespace, KeyType::Client, None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004348 list_result.sort();
4349 assert_eq!(list_o_descriptors, list_result);
4350
4351 let mut list_o_ids: Vec<i64> = list_o_descriptors
4352 .into_iter()
4353 .map(|d| {
4354 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004355 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004356 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004357 KeyType::Client,
4358 KeyEntryLoadBits::NONE,
4359 *namespace as u32,
4360 |_, _| Ok(()),
4361 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004362 .unwrap();
4363 entry.id()
4364 })
4365 .collect();
4366 list_o_ids.sort_unstable();
4367 let mut loaded_entries: Vec<i64> = list_o_keys
4368 .iter()
4369 .filter_map(|(id, ns)| match ns {
4370 ns if *ns == *namespace => Some(*id),
4371 _ => None,
4372 })
4373 .collect();
4374 loaded_entries.sort_unstable();
4375 assert_eq!(list_o_ids, loaded_entries);
4376 }
Eran Messeri24f31972023-01-25 17:00:33 +00004377 assert_eq!(
4378 Vec::<KeyDescriptor>::new(),
4379 db.list_past_alias(Domain::SELINUX, 101, KeyType::Client, None)?
4380 );
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004381
4382 Ok(())
4383 }
4384
Joel Galenson0891bc12020-07-20 10:37:03 -07004385 // Helpers
4386
4387 // Checks that the given result is an error containing the given string.
4388 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4389 let error_str = format!(
4390 "{:#?}",
4391 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4392 );
4393 assert!(
4394 error_str.contains(target),
4395 "The string \"{}\" should contain \"{}\"",
4396 error_str,
4397 target
4398 );
4399 }
4400
Joel Galenson2aab4432020-07-22 15:27:57 -07004401 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004402 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004403 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004404 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004405 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004406 namespace: Option<i64>,
4407 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004408 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004409 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004410 }
4411
4412 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4413 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004414 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004415 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004416 Ok(KeyEntryRow {
4417 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004418 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004419 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004420 namespace: row.get(3)?,
4421 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004422 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004423 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004424 })
4425 })?
4426 .map(|r| r.context("Could not read keyentry row."))
4427 .collect::<Result<Vec<_>>>()
4428 }
4429
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004430 // Note: The parameters and SecurityLevel associations are nonsensical. This
4431 // collection is only used to check if the parameters are preserved as expected by the
4432 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004433 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4434 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004435 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4436 KeyParameter::new(
4437 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4438 SecurityLevel::TRUSTED_ENVIRONMENT,
4439 ),
4440 KeyParameter::new(
4441 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4442 SecurityLevel::TRUSTED_ENVIRONMENT,
4443 ),
4444 KeyParameter::new(
4445 KeyParameterValue::Algorithm(Algorithm::RSA),
4446 SecurityLevel::TRUSTED_ENVIRONMENT,
4447 ),
4448 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4449 KeyParameter::new(
4450 KeyParameterValue::BlockMode(BlockMode::ECB),
4451 SecurityLevel::TRUSTED_ENVIRONMENT,
4452 ),
4453 KeyParameter::new(
4454 KeyParameterValue::BlockMode(BlockMode::GCM),
4455 SecurityLevel::TRUSTED_ENVIRONMENT,
4456 ),
4457 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4458 KeyParameter::new(
4459 KeyParameterValue::Digest(Digest::MD5),
4460 SecurityLevel::TRUSTED_ENVIRONMENT,
4461 ),
4462 KeyParameter::new(
4463 KeyParameterValue::Digest(Digest::SHA_2_224),
4464 SecurityLevel::TRUSTED_ENVIRONMENT,
4465 ),
4466 KeyParameter::new(
4467 KeyParameterValue::Digest(Digest::SHA_2_256),
4468 SecurityLevel::STRONGBOX,
4469 ),
4470 KeyParameter::new(
4471 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4472 SecurityLevel::TRUSTED_ENVIRONMENT,
4473 ),
4474 KeyParameter::new(
4475 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4476 SecurityLevel::TRUSTED_ENVIRONMENT,
4477 ),
4478 KeyParameter::new(
4479 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4480 SecurityLevel::STRONGBOX,
4481 ),
4482 KeyParameter::new(
4483 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4484 SecurityLevel::TRUSTED_ENVIRONMENT,
4485 ),
4486 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4487 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4488 KeyParameter::new(
4489 KeyParameterValue::EcCurve(EcCurve::P_224),
4490 SecurityLevel::TRUSTED_ENVIRONMENT,
4491 ),
4492 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4493 KeyParameter::new(
4494 KeyParameterValue::EcCurve(EcCurve::P_384),
4495 SecurityLevel::TRUSTED_ENVIRONMENT,
4496 ),
4497 KeyParameter::new(
4498 KeyParameterValue::EcCurve(EcCurve::P_521),
4499 SecurityLevel::TRUSTED_ENVIRONMENT,
4500 ),
4501 KeyParameter::new(
4502 KeyParameterValue::RSAPublicExponent(3),
4503 SecurityLevel::TRUSTED_ENVIRONMENT,
4504 ),
4505 KeyParameter::new(
4506 KeyParameterValue::IncludeUniqueID,
4507 SecurityLevel::TRUSTED_ENVIRONMENT,
4508 ),
4509 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4510 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4511 KeyParameter::new(
4512 KeyParameterValue::ActiveDateTime(1234567890),
4513 SecurityLevel::STRONGBOX,
4514 ),
4515 KeyParameter::new(
4516 KeyParameterValue::OriginationExpireDateTime(1234567890),
4517 SecurityLevel::TRUSTED_ENVIRONMENT,
4518 ),
4519 KeyParameter::new(
4520 KeyParameterValue::UsageExpireDateTime(1234567890),
4521 SecurityLevel::TRUSTED_ENVIRONMENT,
4522 ),
4523 KeyParameter::new(
4524 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4525 SecurityLevel::TRUSTED_ENVIRONMENT,
4526 ),
4527 KeyParameter::new(
4528 KeyParameterValue::MaxUsesPerBoot(1234567890),
4529 SecurityLevel::TRUSTED_ENVIRONMENT,
4530 ),
4531 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4532 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4533 KeyParameter::new(
4534 KeyParameterValue::NoAuthRequired,
4535 SecurityLevel::TRUSTED_ENVIRONMENT,
4536 ),
4537 KeyParameter::new(
4538 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4539 SecurityLevel::TRUSTED_ENVIRONMENT,
4540 ),
4541 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4542 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4543 KeyParameter::new(
4544 KeyParameterValue::TrustedUserPresenceRequired,
4545 SecurityLevel::TRUSTED_ENVIRONMENT,
4546 ),
4547 KeyParameter::new(
4548 KeyParameterValue::TrustedConfirmationRequired,
4549 SecurityLevel::TRUSTED_ENVIRONMENT,
4550 ),
4551 KeyParameter::new(
4552 KeyParameterValue::UnlockedDeviceRequired,
4553 SecurityLevel::TRUSTED_ENVIRONMENT,
4554 ),
4555 KeyParameter::new(
4556 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4557 SecurityLevel::SOFTWARE,
4558 ),
4559 KeyParameter::new(
4560 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4561 SecurityLevel::SOFTWARE,
4562 ),
4563 KeyParameter::new(
4564 KeyParameterValue::CreationDateTime(12345677890),
4565 SecurityLevel::SOFTWARE,
4566 ),
4567 KeyParameter::new(
4568 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4569 SecurityLevel::TRUSTED_ENVIRONMENT,
4570 ),
4571 KeyParameter::new(
4572 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4573 SecurityLevel::TRUSTED_ENVIRONMENT,
4574 ),
4575 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4576 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4577 KeyParameter::new(
4578 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4579 SecurityLevel::SOFTWARE,
4580 ),
4581 KeyParameter::new(
4582 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4583 SecurityLevel::TRUSTED_ENVIRONMENT,
4584 ),
4585 KeyParameter::new(
4586 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4587 SecurityLevel::TRUSTED_ENVIRONMENT,
4588 ),
4589 KeyParameter::new(
4590 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4591 SecurityLevel::TRUSTED_ENVIRONMENT,
4592 ),
4593 KeyParameter::new(
4594 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4595 SecurityLevel::TRUSTED_ENVIRONMENT,
4596 ),
4597 KeyParameter::new(
4598 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4599 SecurityLevel::TRUSTED_ENVIRONMENT,
4600 ),
4601 KeyParameter::new(
4602 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4603 SecurityLevel::TRUSTED_ENVIRONMENT,
4604 ),
4605 KeyParameter::new(
4606 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4607 SecurityLevel::TRUSTED_ENVIRONMENT,
4608 ),
4609 KeyParameter::new(
Eran Messeri637259c2022-10-31 12:23:36 +00004610 KeyParameterValue::AttestationIdSecondIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4611 SecurityLevel::TRUSTED_ENVIRONMENT,
4612 ),
4613 KeyParameter::new(
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004614 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4615 SecurityLevel::TRUSTED_ENVIRONMENT,
4616 ),
4617 KeyParameter::new(
4618 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4619 SecurityLevel::TRUSTED_ENVIRONMENT,
4620 ),
4621 KeyParameter::new(
4622 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4623 SecurityLevel::TRUSTED_ENVIRONMENT,
4624 ),
4625 KeyParameter::new(
4626 KeyParameterValue::VendorPatchLevel(3),
4627 SecurityLevel::TRUSTED_ENVIRONMENT,
4628 ),
4629 KeyParameter::new(
4630 KeyParameterValue::BootPatchLevel(4),
4631 SecurityLevel::TRUSTED_ENVIRONMENT,
4632 ),
4633 KeyParameter::new(
4634 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4635 SecurityLevel::TRUSTED_ENVIRONMENT,
4636 ),
4637 KeyParameter::new(
4638 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4639 SecurityLevel::TRUSTED_ENVIRONMENT,
4640 ),
4641 KeyParameter::new(
4642 KeyParameterValue::MacLength(256),
4643 SecurityLevel::TRUSTED_ENVIRONMENT,
4644 ),
4645 KeyParameter::new(
4646 KeyParameterValue::ResetSinceIdRotation,
4647 SecurityLevel::TRUSTED_ENVIRONMENT,
4648 ),
4649 KeyParameter::new(
4650 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4651 SecurityLevel::TRUSTED_ENVIRONMENT,
4652 ),
Qi Wub9433b52020-12-01 14:52:46 +08004653 ];
4654 if let Some(value) = max_usage_count {
4655 params.push(KeyParameter::new(
4656 KeyParameterValue::UsageCountLimit(value),
4657 SecurityLevel::SOFTWARE,
4658 ));
4659 }
4660 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004661 }
4662
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004663 pub fn make_test_key_entry(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004664 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004665 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004666 namespace: i64,
4667 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004668 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004669 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004670 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004671 let mut blob_metadata = BlobMetaData::new();
4672 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4673 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4674 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4675 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4676 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4677
4678 db.set_blob(
4679 &key_id,
4680 SubComponentType::KEY_BLOB,
4681 Some(TEST_KEY_BLOB),
4682 Some(&blob_metadata),
4683 )?;
4684 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4685 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004686
4687 let params = make_test_params(max_usage_count);
4688 db.insert_keyparameter(&key_id, &params)?;
4689
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004690 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004691 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004692 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004693 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004694 Ok(key_id)
4695 }
4696
Qi Wub9433b52020-12-01 14:52:46 +08004697 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4698 let params = make_test_params(max_usage_count);
4699
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004700 let mut blob_metadata = BlobMetaData::new();
4701 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4702 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4703 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4704 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4705 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4706
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004707 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004708 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004709
4710 KeyEntry {
4711 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004712 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004713 cert: Some(TEST_CERT_BLOB.to_vec()),
4714 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004715 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004716 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004717 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004718 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004719 }
4720 }
4721
Nathan Huckleberry95dca012023-05-10 18:02:11 +00004722 pub fn make_bootlevel_key_entry(
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004723 db: &mut KeystoreDB,
4724 domain: Domain,
4725 namespace: i64,
4726 alias: &str,
4727 logical_only: bool,
4728 ) -> Result<KeyIdGuard> {
4729 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
4730 let mut blob_metadata = BlobMetaData::new();
4731 if !logical_only {
4732 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4733 }
4734 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4735
4736 db.set_blob(
4737 &key_id,
4738 SubComponentType::KEY_BLOB,
4739 Some(TEST_KEY_BLOB),
4740 Some(&blob_metadata),
4741 )?;
4742 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4743 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
4744
4745 let mut params = make_test_params(None);
4746 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4747
4748 db.insert_keyparameter(&key_id, &params)?;
4749
4750 let mut metadata = KeyMetaData::new();
4751 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4752 db.insert_key_metadata(&key_id, &metadata)?;
4753 rebind_alias(db, &key_id, alias, domain, namespace)?;
4754 Ok(key_id)
4755 }
4756
4757 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
4758 let mut params = make_test_params(None);
4759 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
4760
4761 let mut blob_metadata = BlobMetaData::new();
4762 if !logical_only {
4763 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
4764 }
4765 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4766
4767 let mut metadata = KeyMetaData::new();
4768 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
4769
4770 KeyEntry {
4771 id: key_id,
4772 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
4773 cert: Some(TEST_CERT_BLOB.to_vec()),
4774 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
4775 km_uuid: KEYSTORE_UUID,
4776 parameters: params,
4777 metadata,
4778 pure_cert: false,
4779 }
4780 }
4781
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004782 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004783 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004784 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004785 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004786 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004787 NO_PARAMS,
4788 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004789 Ok((
4790 row.get(0)?,
4791 row.get(1)?,
4792 row.get(2)?,
4793 row.get(3)?,
4794 row.get(4)?,
4795 row.get(5)?,
4796 row.get(6)?,
4797 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004798 },
4799 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004800
4801 println!("Key entry table rows:");
4802 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004803 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004804 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004805 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4806 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004807 );
4808 }
4809 Ok(())
4810 }
4811
4812 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004813 let mut stmt = db
4814 .conn
4815 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004816 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
4817 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4818 })?;
4819
4820 println!("Grant table rows:");
4821 for r in rows {
4822 let (id, gt, ki, av) = r.unwrap();
4823 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4824 }
4825 Ok(())
4826 }
4827
Joel Galenson0891bc12020-07-20 10:37:03 -07004828 // Use a custom random number generator that repeats each number once.
4829 // This allows us to test repeated elements.
4830
4831 thread_local! {
4832 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4833 }
4834
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004835 fn reset_random() {
4836 RANDOM_COUNTER.with(|counter| {
4837 *counter.borrow_mut() = 0;
4838 })
4839 }
4840
Joel Galenson0891bc12020-07-20 10:37:03 -07004841 pub fn random() -> i64 {
4842 RANDOM_COUNTER.with(|counter| {
4843 let result = *counter.borrow() / 2;
4844 *counter.borrow_mut() += 1;
4845 result
4846 })
4847 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004848
4849 #[test]
4850 fn test_last_off_body() -> Result<()> {
4851 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004852 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004853 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004854 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004855 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004856 let one_second = Duration::from_secs(1);
4857 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004858 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004859 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004860 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07004861 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00004862 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004863 Ok(())
4864 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00004865
4866 #[test]
4867 fn test_unbind_keys_for_user() -> Result<()> {
4868 let mut db = new_test_db()?;
4869 db.unbind_keys_for_user(1, false)?;
4870
4871 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4872 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4873 db.unbind_keys_for_user(2, false)?;
4874
Eran Messeri24f31972023-01-25 17:00:33 +00004875 assert_eq!(1, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
4876 assert_eq!(0, db.list_past_alias(Domain::APP, 210000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004877
4878 db.unbind_keys_for_user(1, true)?;
Eran Messeri24f31972023-01-25 17:00:33 +00004879 assert_eq!(0, db.list_past_alias(Domain::APP, 110000, KeyType::Client, None)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00004880
4881 Ok(())
4882 }
4883
4884 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004885 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
4886 let mut db = new_test_db()?;
4887 let super_key = keystore2_crypto::generate_aes256_key()?;
4888 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
4889 let (encrypted_super_key, metadata) =
4890 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4891
4892 let key_name_enc = SuperKeyType {
4893 alias: "test_super_key_1",
4894 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
4895 };
4896
4897 let key_name_nonenc = SuperKeyType {
4898 alias: "test_super_key_2",
4899 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
4900 };
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,
4971 &USER_SUPER_KEY,
4972 &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.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004978 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00004979
Paul Crowley7a658392021-03-18 17:08:20 -07004980 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07004981 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
4982 USER_SUPER_KEY.algorithm,
4983 key_entry,
4984 &pw,
4985 None,
4986 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00004987
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08004988 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07004989 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08004990
Hasini Gunasingheda895552021-01-27 19:34:37 +00004991 Ok(())
4992 }
Seth Moore78c091f2021-04-09 21:38:30 +00004993
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00004994 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00004995 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00004996 MetricsStorage::KEY_ENTRY,
4997 MetricsStorage::KEY_ENTRY_ID_INDEX,
4998 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
4999 MetricsStorage::BLOB_ENTRY,
5000 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5001 MetricsStorage::KEY_PARAMETER,
5002 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5003 MetricsStorage::KEY_METADATA,
5004 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5005 MetricsStorage::GRANT,
5006 MetricsStorage::AUTH_TOKEN,
5007 MetricsStorage::BLOB_METADATA,
5008 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005009 ]
5010 }
5011
5012 /// Perform a simple check to ensure that we can query all the storage types
5013 /// that are supported by the DB. Check for reasonable values.
5014 #[test]
5015 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005016 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005017
5018 let mut db = new_test_db()?;
5019
5020 for t in get_valid_statsd_storage_types() {
5021 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005022 // AuthToken can be less than a page since it's in a btree, not sqlite
5023 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005024 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005025 } else {
5026 assert!(stat.size >= PAGE_SIZE);
5027 }
Seth Moore78c091f2021-04-09 21:38:30 +00005028 assert!(stat.size >= stat.unused_size);
5029 }
5030
5031 Ok(())
5032 }
5033
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005034 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005035 get_valid_statsd_storage_types()
5036 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005037 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005038 .collect()
5039 }
5040
5041 fn assert_storage_increased(
5042 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005043 increased_storage_types: Vec<MetricsStorage>,
5044 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005045 ) {
5046 for storage in increased_storage_types {
5047 // Verify the expected storage increased.
5048 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005049 let storage = storage;
5050 let old = &baseline[&storage.0];
5051 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005052 assert!(
5053 new.unused_size <= old.unused_size,
5054 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005055 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005056 new.unused_size,
5057 old.unused_size
5058 );
5059
5060 // Update the baseline with the new value so that it succeeds in the
5061 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005062 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005063 }
5064
5065 // Get an updated map of the storage and verify there were no unexpected changes.
5066 let updated_stats = get_storage_stats_map(db);
5067 assert_eq!(updated_stats.len(), baseline.len());
5068
5069 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005070 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005071 let mut s = String::new();
5072 for &k in map.keys() {
5073 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5074 .expect("string concat failed");
5075 }
5076 s
5077 };
5078
5079 assert!(
5080 updated_stats[&k].size == baseline[&k].size
5081 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5082 "updated_stats:\n{}\nbaseline:\n{}",
5083 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005084 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005085 );
5086 }
5087 }
5088
5089 #[test]
5090 fn test_verify_key_table_size_reporting() -> Result<()> {
5091 let mut db = new_test_db()?;
5092 let mut working_stats = get_storage_stats_map(&mut db);
5093
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005094 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005095 assert_storage_increased(
5096 &mut db,
5097 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005098 MetricsStorage::KEY_ENTRY,
5099 MetricsStorage::KEY_ENTRY_ID_INDEX,
5100 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005101 ],
5102 &mut working_stats,
5103 );
5104
5105 let mut blob_metadata = BlobMetaData::new();
5106 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5107 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5108 assert_storage_increased(
5109 &mut db,
5110 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005111 MetricsStorage::BLOB_ENTRY,
5112 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5113 MetricsStorage::BLOB_METADATA,
5114 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005115 ],
5116 &mut working_stats,
5117 );
5118
5119 let params = make_test_params(None);
5120 db.insert_keyparameter(&key_id, &params)?;
5121 assert_storage_increased(
5122 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005123 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005124 &mut working_stats,
5125 );
5126
5127 let mut metadata = KeyMetaData::new();
5128 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5129 db.insert_key_metadata(&key_id, &metadata)?;
5130 assert_storage_increased(
5131 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005132 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005133 &mut working_stats,
5134 );
5135
5136 let mut sum = 0;
5137 for stat in working_stats.values() {
5138 sum += stat.size;
5139 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005140 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005141 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5142
5143 Ok(())
5144 }
5145
5146 #[test]
5147 fn test_verify_auth_table_size_reporting() -> Result<()> {
5148 let mut db = new_test_db()?;
5149 let mut working_stats = get_storage_stats_map(&mut db);
5150 db.insert_auth_token(&HardwareAuthToken {
5151 challenge: 123,
5152 userId: 456,
5153 authenticatorId: 789,
5154 authenticatorType: kmhw_authenticator_type::ANY,
5155 timestamp: Timestamp { milliSeconds: 10 },
5156 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005157 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005158 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005159 Ok(())
5160 }
5161
5162 #[test]
5163 fn test_verify_grant_table_size_reporting() -> Result<()> {
5164 const OWNER: i64 = 1;
5165 let mut db = new_test_db()?;
5166 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5167
5168 let mut working_stats = get_storage_stats_map(&mut db);
5169 db.grant(
5170 &KeyDescriptor {
5171 domain: Domain::APP,
5172 nspace: 0,
5173 alias: Some(TEST_ALIAS.to_string()),
5174 blob: None,
5175 },
5176 OWNER as u32,
5177 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005178 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005179 |_, _| Ok(()),
5180 )?;
5181
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005182 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005183
5184 Ok(())
5185 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005186
5187 #[test]
5188 fn find_auth_token_entry_returns_latest() -> Result<()> {
5189 let mut db = new_test_db()?;
5190 db.insert_auth_token(&HardwareAuthToken {
5191 challenge: 123,
5192 userId: 456,
5193 authenticatorId: 789,
5194 authenticatorType: kmhw_authenticator_type::ANY,
5195 timestamp: Timestamp { milliSeconds: 10 },
5196 mac: b"mac0".to_vec(),
5197 });
5198 std::thread::sleep(std::time::Duration::from_millis(1));
5199 db.insert_auth_token(&HardwareAuthToken {
5200 challenge: 123,
5201 userId: 457,
5202 authenticatorId: 789,
5203 authenticatorType: kmhw_authenticator_type::ANY,
5204 timestamp: Timestamp { milliSeconds: 12 },
5205 mac: b"mac1".to_vec(),
5206 });
5207 std::thread::sleep(std::time::Duration::from_millis(1));
5208 db.insert_auth_token(&HardwareAuthToken {
5209 challenge: 123,
5210 userId: 458,
5211 authenticatorId: 789,
5212 authenticatorType: kmhw_authenticator_type::ANY,
5213 timestamp: Timestamp { milliSeconds: 3 },
5214 mac: b"mac2".to_vec(),
5215 });
5216 // All three entries are in the database
5217 assert_eq!(db.perboot.auth_tokens_len(), 3);
5218 // It selected the most recent timestamp
5219 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5220 Ok(())
5221 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005222
5223 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005224 fn test_load_key_descriptor() -> Result<()> {
5225 let mut db = new_test_db()?;
5226 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5227
5228 let key = db.load_key_descriptor(key_id)?.unwrap();
5229
5230 assert_eq!(key.domain, Domain::APP);
5231 assert_eq!(key.nspace, 1);
5232 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5233
5234 // No such id
5235 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5236 Ok(())
5237 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005238}