blob: 28a2e9dc6c3f0a26249f376f1b535e3a8d82ac1d [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};
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000051use crate::metrics_store::log_rkp_error_stats;
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::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080064 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000065 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080066};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070067use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070068 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070069};
Max Bires2b2e6562020-09-22 11:22:36 -070070use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
71 AttestationPoolStatus::AttestationPoolStatus,
72};
Hasini Gunasinghe15891e62021-06-10 16:23:27 +000073use android_security_metrics::aidl::android::security::metrics::{
74 StorageStats::StorageStats,
75 Storage::Storage as MetricsStorage,
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +000076 RkpError::RkpError as MetricsRkpError,
Seth Moore78c091f2021-04-09 21:38:30 +000077};
Max Bires2b2e6562020-09-22 11:22:36 -070078
79use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080080use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000081use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070082#[cfg(not(test))]
83use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070084use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070085 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080086 types::FromSql,
87 types::FromSqlResult,
88 types::ToSqlOutput,
89 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080090 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070091};
Max Bires2b2e6562020-09-22 11:22:36 -070092
Janis Danisevskisaec14592020-11-12 09:41:49 -080093use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080095 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070096 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080097 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080098};
Max Bires2b2e6562020-09-22 11:22:36 -070099
Joel Galenson0891bc12020-07-20 10:37:03 -0700100#[cfg(test)]
101use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -0700102
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800103impl_metadata!(
104 /// A set of metadata for key entries.
105 #[derive(Debug, Default, Eq, PartialEq)]
106 pub struct KeyMetaData;
107 /// A metadata entry for key entries.
108 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
109 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800110 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800111 CreationDate(DateTime) with accessor creation_date,
112 /// Expiration date for attestation keys.
113 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700114 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
115 /// provisioning
116 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
117 /// Vector representing the raw public key so results from the server can be matched
118 /// to the right entry
119 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700120 /// SEC1 public key for ECDH encryption
121 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800122 // --- ADD NEW META DATA FIELDS HERE ---
123 // For backwards compatibility add new entries only to
124 // end of this list and above this comment.
125 };
126);
127
128impl KeyMetaData {
129 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
130 let mut stmt = tx
131 .prepare(
132 "SELECT tag, data from persistent.keymetadata
133 WHERE keyentryid = ?;",
134 )
135 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
136
137 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
138
139 let mut rows =
140 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
141 db_utils::with_rows_extract_all(&mut rows, |row| {
142 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
143 metadata.insert(
144 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700145 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800146 .context("Failed to read KeyMetaEntry.")?,
147 );
148 Ok(())
149 })
150 .context("In KeyMetaData::load_from_db.")?;
151
152 Ok(Self { data: metadata })
153 }
154
155 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
156 let mut stmt = tx
157 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000158 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800159 VALUES (?, ?, ?);",
160 )
161 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
162
163 let iter = self.data.iter();
164 for (tag, entry) in iter {
165 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
166 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
167 })?;
168 }
169 Ok(())
170 }
171}
172
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800173impl_metadata!(
174 /// A set of metadata for key blobs.
175 #[derive(Debug, Default, Eq, PartialEq)]
176 pub struct BlobMetaData;
177 /// A metadata entry for key blobs.
178 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
179 pub enum BlobMetaEntry {
180 /// If present, indicates that the blob is encrypted with another key or a key derived
181 /// from a password.
182 EncryptedBy(EncryptedBy) with accessor encrypted_by,
183 /// If the blob is password encrypted this field is set to the
184 /// salt used for the key derivation.
185 Salt(Vec<u8>) with accessor salt,
186 /// If the blob is encrypted, this field is set to the initialization vector.
187 Iv(Vec<u8>) with accessor iv,
188 /// If the blob is encrypted, this field holds the AEAD TAG.
189 AeadTag(Vec<u8>) with accessor aead_tag,
190 /// The uuid of the owning KeyMint instance.
191 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700192 /// If the key is ECDH encrypted, this is the ephemeral public key
193 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000194 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
195 /// of that key
196 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800197 // --- ADD NEW META DATA FIELDS HERE ---
198 // For backwards compatibility add new entries only to
199 // end of this list and above this comment.
200 };
201);
202
203impl BlobMetaData {
204 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
205 let mut stmt = tx
206 .prepare(
207 "SELECT tag, data from persistent.blobmetadata
208 WHERE blobentryid = ?;",
209 )
210 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
211
212 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
213
214 let mut rows =
215 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
216 db_utils::with_rows_extract_all(&mut rows, |row| {
217 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
218 metadata.insert(
219 db_tag,
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700220 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, row))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800221 .context("Failed to read BlobMetaEntry.")?,
222 );
223 Ok(())
224 })
225 .context("In BlobMetaData::load_from_db.")?;
226
227 Ok(Self { data: metadata })
228 }
229
230 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
231 let mut stmt = tx
232 .prepare(
233 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
234 VALUES (?, ?, ?);",
235 )
236 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
237
238 let iter = self.data.iter();
239 for (tag, entry) in iter {
240 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
241 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
242 })?;
243 }
244 Ok(())
245 }
246}
247
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800248/// Indicates the type of the keyentry.
249#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
250pub enum KeyType {
251 /// This is a client key type. These keys are created or imported through the Keystore 2.0
252 /// AIDL interface android.system.keystore2.
253 Client,
254 /// This is a super key type. These keys are created by keystore itself and used to encrypt
255 /// other key blobs to provide LSKF binding.
256 Super,
257 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
258 Attestation,
259}
260
261impl ToSql for KeyType {
262 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
263 Ok(ToSqlOutput::Owned(Value::Integer(match self {
264 KeyType::Client => 0,
265 KeyType::Super => 1,
266 KeyType::Attestation => 2,
267 })))
268 }
269}
270
271impl FromSql for KeyType {
272 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
273 match i64::column_result(value)? {
274 0 => Ok(KeyType::Client),
275 1 => Ok(KeyType::Super),
276 2 => Ok(KeyType::Attestation),
277 v => Err(FromSqlError::OutOfRange(v)),
278 }
279 }
280}
281
Max Bires8e93d2b2021-01-14 13:17:59 -0800282/// Uuid representation that can be stored in the database.
283/// Right now it can only be initialized from SecurityLevel.
284/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
285#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
286pub struct Uuid([u8; 16]);
287
288impl Deref for Uuid {
289 type Target = [u8; 16];
290
291 fn deref(&self) -> &Self::Target {
292 &self.0
293 }
294}
295
296impl From<SecurityLevel> for Uuid {
297 fn from(sec_level: SecurityLevel) -> Self {
298 Self((sec_level.0 as u128).to_be_bytes())
299 }
300}
301
302impl ToSql for Uuid {
303 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
304 self.0.to_sql()
305 }
306}
307
308impl FromSql for Uuid {
309 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
310 let blob = Vec::<u8>::column_result(value)?;
311 if blob.len() != 16 {
312 return Err(FromSqlError::OutOfRange(blob.len() as i64));
313 }
314 let mut arr = [0u8; 16];
315 arr.copy_from_slice(&blob);
316 Ok(Self(arr))
317 }
318}
319
320/// Key entries that are not associated with any KeyMint instance, such as pure certificate
321/// entries are associated with this UUID.
322pub static KEYSTORE_UUID: Uuid = Uuid([
323 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
324]);
325
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800326/// Indicates how the sensitive part of this key blob is encrypted.
327#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
328pub enum EncryptedBy {
329 /// The keyblob is encrypted by a user password.
330 /// In the database this variant is represented as NULL.
331 Password,
332 /// The keyblob is encrypted by another key with wrapped key id.
333 /// In the database this variant is represented as non NULL value
334 /// that is convertible to i64, typically NUMERIC.
335 KeyId(i64),
336}
337
338impl ToSql for EncryptedBy {
339 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
340 match self {
341 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
342 Self::KeyId(id) => id.to_sql(),
343 }
344 }
345}
346
347impl FromSql for EncryptedBy {
348 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
349 match value {
350 ValueRef::Null => Ok(Self::Password),
351 _ => Ok(Self::KeyId(i64::column_result(value)?)),
352 }
353 }
354}
355
356/// A database representation of wall clock time. DateTime stores unix epoch time as
357/// i64 in milliseconds.
358#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
359pub struct DateTime(i64);
360
361/// Error type returned when creating DateTime or converting it from and to
362/// SystemTime.
363#[derive(thiserror::Error, Debug)]
364pub enum DateTimeError {
365 /// This is returned when SystemTime and Duration computations fail.
366 #[error(transparent)]
367 SystemTimeError(#[from] SystemTimeError),
368
369 /// This is returned when type conversions fail.
370 #[error(transparent)]
371 TypeConversion(#[from] std::num::TryFromIntError),
372
373 /// This is returned when checked time arithmetic failed.
374 #[error("Time arithmetic failed.")]
375 TimeArithmetic,
376}
377
378impl DateTime {
379 /// Constructs a new DateTime object denoting the current time. This may fail during
380 /// conversion to unix epoch time and during conversion to the internal i64 representation.
381 pub fn now() -> Result<Self, DateTimeError> {
382 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
383 }
384
385 /// Constructs a new DateTime object from milliseconds.
386 pub fn from_millis_epoch(millis: i64) -> Self {
387 Self(millis)
388 }
389
390 /// Returns unix epoch time in milliseconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700391 pub fn to_millis_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800392 self.0
393 }
394
395 /// Returns unix epoch time in seconds.
Chris Wailes3877f292021-07-26 19:24:18 -0700396 pub fn to_secs_epoch(self) -> i64 {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800397 self.0 / 1000
398 }
399}
400
401impl ToSql for DateTime {
402 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
403 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
404 }
405}
406
407impl FromSql for DateTime {
408 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
409 Ok(Self(i64::column_result(value)?))
410 }
411}
412
413impl TryInto<SystemTime> for DateTime {
414 type Error = DateTimeError;
415
416 fn try_into(self) -> Result<SystemTime, Self::Error> {
417 // We want to construct a SystemTime representation equivalent to self, denoting
418 // a point in time THEN, but we cannot set the time directly. We can only construct
419 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
420 // and between EPOCH and THEN. With this common reference we can construct the
421 // duration between NOW and THEN which we can add to our SystemTime representation
422 // of NOW to get a SystemTime representation of THEN.
423 // Durations can only be positive, thus the if statement below.
424 let now = SystemTime::now();
425 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
426 let then_epoch = Duration::from_millis(self.0.try_into()?);
427 Ok(if now_epoch > then_epoch {
428 // then = now - (now_epoch - then_epoch)
429 now_epoch
430 .checked_sub(then_epoch)
431 .and_then(|d| now.checked_sub(d))
432 .ok_or(DateTimeError::TimeArithmetic)?
433 } else {
434 // then = now + (then_epoch - now_epoch)
435 then_epoch
436 .checked_sub(now_epoch)
437 .and_then(|d| now.checked_add(d))
438 .ok_or(DateTimeError::TimeArithmetic)?
439 })
440 }
441}
442
443impl TryFrom<SystemTime> for DateTime {
444 type Error = DateTimeError;
445
446 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
447 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
448 }
449}
450
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800451#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
452enum KeyLifeCycle {
453 /// Existing keys have a key ID but are not fully populated yet.
454 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
455 /// them to Unreferenced for garbage collection.
456 Existing,
457 /// A live key is fully populated and usable by clients.
458 Live,
459 /// An unreferenced key is scheduled for garbage collection.
460 Unreferenced,
461}
462
463impl ToSql for KeyLifeCycle {
464 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
465 match self {
466 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
467 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
468 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
469 }
470 }
471}
472
473impl FromSql for KeyLifeCycle {
474 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
475 match i64::column_result(value)? {
476 0 => Ok(KeyLifeCycle::Existing),
477 1 => Ok(KeyLifeCycle::Live),
478 2 => Ok(KeyLifeCycle::Unreferenced),
479 v => Err(FromSqlError::OutOfRange(v)),
480 }
481 }
482}
483
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700484/// Keys have a KeyMint blob component and optional public certificate and
485/// certificate chain components.
486/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
487/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800488#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700489pub struct KeyEntryLoadBits(u32);
490
491impl KeyEntryLoadBits {
492 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
493 pub const NONE: KeyEntryLoadBits = Self(0);
494 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
495 pub const KM: KeyEntryLoadBits = Self(1);
496 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
497 pub const PUBLIC: KeyEntryLoadBits = Self(2);
498 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
499 pub const BOTH: KeyEntryLoadBits = Self(3);
500
501 /// Returns true if this object indicates that the public components shall be loaded.
502 pub const fn load_public(&self) -> bool {
503 self.0 & Self::PUBLIC.0 != 0
504 }
505
506 /// Returns true if the object indicates that the KeyMint component shall be loaded.
507 pub const fn load_km(&self) -> bool {
508 self.0 & Self::KM.0 != 0
509 }
510}
511
Janis Danisevskisaec14592020-11-12 09:41:49 -0800512lazy_static! {
513 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
514}
515
516struct KeyIdLockDb {
517 locked_keys: Mutex<HashSet<i64>>,
518 cond_var: Condvar,
519}
520
521/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
522/// from the database a second time. Most functions manipulating the key blob database
523/// require a KeyIdGuard.
524#[derive(Debug)]
525pub struct KeyIdGuard(i64);
526
527impl KeyIdLockDb {
528 fn new() -> Self {
529 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
530 }
531
532 /// This function blocks until an exclusive lock for the given key entry id can
533 /// be acquired. It returns a guard object, that represents the lifecycle of the
534 /// acquired lock.
535 pub fn get(&self, key_id: i64) -> KeyIdGuard {
536 let mut locked_keys = self.locked_keys.lock().unwrap();
537 while locked_keys.contains(&key_id) {
538 locked_keys = self.cond_var.wait(locked_keys).unwrap();
539 }
540 locked_keys.insert(key_id);
541 KeyIdGuard(key_id)
542 }
543
544 /// This function attempts to acquire an exclusive lock on a given key id. If the
545 /// given key id is already taken the function returns None immediately. If a lock
546 /// can be acquired this function returns a guard object, that represents the
547 /// lifecycle of the acquired lock.
548 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
549 let mut locked_keys = self.locked_keys.lock().unwrap();
550 if locked_keys.insert(key_id) {
551 Some(KeyIdGuard(key_id))
552 } else {
553 None
554 }
555 }
556}
557
558impl KeyIdGuard {
559 /// Get the numeric key id of the locked key.
560 pub fn id(&self) -> i64 {
561 self.0
562 }
563}
564
565impl Drop for KeyIdGuard {
566 fn drop(&mut self) {
567 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
568 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800569 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800570 KEY_ID_LOCK.cond_var.notify_all();
571 }
572}
573
Max Bires8e93d2b2021-01-14 13:17:59 -0800574/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700575#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800576pub struct CertificateInfo {
577 cert: Option<Vec<u8>>,
578 cert_chain: Option<Vec<u8>>,
579}
580
Janis Danisevskisf84d0b02022-01-26 14:11:14 -0800581/// This type represents a Blob with its metadata and an optional superseded blob.
582#[derive(Debug)]
583pub struct BlobInfo<'a> {
584 blob: &'a [u8],
585 metadata: &'a BlobMetaData,
586 /// Superseded blobs are an artifact of legacy import. In some rare occasions
587 /// the key blob needs to be upgraded during import. In that case two
588 /// blob are imported, the superseded one will have to be imported first,
589 /// so that the garbage collector can reap it.
590 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
591}
592
593impl<'a> BlobInfo<'a> {
594 /// Create a new instance of blob info with blob and corresponding metadata
595 /// and no superseded blob info.
596 pub fn new(blob: &'a [u8], metadata: &'a BlobMetaData) -> Self {
597 Self { blob, metadata, superseded_blob: None }
598 }
599
600 /// Create a new instance of blob info with blob and corresponding metadata
601 /// as well as superseded blob info.
602 pub fn new_with_superseded(
603 blob: &'a [u8],
604 metadata: &'a BlobMetaData,
605 superseded_blob: Option<(&'a [u8], &'a BlobMetaData)>,
606 ) -> Self {
607 Self { blob, metadata, superseded_blob }
608 }
609}
610
Max Bires8e93d2b2021-01-14 13:17:59 -0800611impl CertificateInfo {
612 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
613 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
614 Self { cert, cert_chain }
615 }
616
617 /// Take the cert
618 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
619 self.cert.take()
620 }
621
622 /// Take the cert chain
623 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
624 self.cert_chain.take()
625 }
626}
627
Max Bires2b2e6562020-09-22 11:22:36 -0700628/// This type represents a certificate chain with a private key corresponding to the leaf
629/// 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 -0700630pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800631 /// A KM key blob
632 pub private_key: ZVec,
633 /// A batch cert for private_key
634 pub batch_cert: Vec<u8>,
635 /// A full certificate chain from root signing authority to private_key, including batch_cert
636 /// for convenience.
637 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700638}
639
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700640/// This type represents a Keystore 2.0 key entry.
641/// An entry has a unique `id` by which it can be found in the database.
642/// It has a security level field, key parameters, and three optional fields
643/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800644#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700645pub struct KeyEntry {
646 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800647 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700648 cert: Option<Vec<u8>>,
649 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800650 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700651 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800652 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800653 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700654}
655
656impl KeyEntry {
657 /// Returns the unique id of the Key entry.
658 pub fn id(&self) -> i64 {
659 self.id
660 }
661 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800662 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
663 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700664 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800665 /// Extracts the Optional KeyMint blob including its metadata.
666 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
667 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700668 }
669 /// Exposes the optional public certificate.
670 pub fn cert(&self) -> &Option<Vec<u8>> {
671 &self.cert
672 }
673 /// Extracts the optional public certificate.
674 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
675 self.cert.take()
676 }
677 /// Exposes the optional public certificate chain.
678 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
679 &self.cert_chain
680 }
681 /// Extracts the optional public certificate_chain.
682 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
683 self.cert_chain.take()
684 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800685 /// Returns the uuid of the owning KeyMint instance.
686 pub fn km_uuid(&self) -> &Uuid {
687 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700688 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700689 /// Exposes the key parameters of this key entry.
690 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
691 &self.parameters
692 }
693 /// Consumes this key entry and extracts the keyparameters from it.
694 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
695 self.parameters
696 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800697 /// Exposes the key metadata of this key entry.
698 pub fn metadata(&self) -> &KeyMetaData {
699 &self.metadata
700 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800701 /// This returns true if the entry is a pure certificate entry with no
702 /// private key component.
703 pub fn pure_cert(&self) -> bool {
704 self.pure_cert
705 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000706 /// Consumes this key entry and extracts the keyparameters and metadata from it.
707 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
708 (self.parameters, self.metadata)
709 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700710}
711
712/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800713#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700714pub struct SubComponentType(u32);
715impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800716 /// Persistent identifier for a key blob.
717 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700718 /// Persistent identifier for a certificate blob.
719 pub const CERT: SubComponentType = Self(1);
720 /// Persistent identifier for a certificate chain blob.
721 pub const CERT_CHAIN: SubComponentType = Self(2);
722}
723
724impl ToSql for SubComponentType {
725 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
726 self.0.to_sql()
727 }
728}
729
730impl FromSql for SubComponentType {
731 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
732 Ok(Self(u32::column_result(value)?))
733 }
734}
735
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800736/// This trait is private to the database module. It is used to convey whether or not the garbage
737/// collector shall be invoked after a database access. All closures passed to
738/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
739/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
740/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
741/// `.need_gc()`.
742trait DoGc<T> {
743 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
744
745 fn no_gc(self) -> Result<(bool, T)>;
746
747 fn need_gc(self) -> Result<(bool, T)>;
748}
749
750impl<T> DoGc<T> for Result<T> {
751 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
752 self.map(|r| (need_gc, r))
753 }
754
755 fn no_gc(self) -> Result<(bool, T)> {
756 self.do_gc(false)
757 }
758
759 fn need_gc(self) -> Result<(bool, T)> {
760 self.do_gc(true)
761 }
762}
763
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700764/// KeystoreDB wraps a connection to an SQLite database and tracks its
765/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700766pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700767 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700768 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700769 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700770}
771
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000772/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000773/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000774#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
775pub struct MonotonicRawTime(i64);
776
777impl MonotonicRawTime {
778 /// Constructs a new MonotonicRawTime
779 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000780 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000781 }
782
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000783 /// Returns the value of MonotonicRawTime in milliseconds as i64
784 pub fn milliseconds(&self) -> i64 {
785 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000786 }
787
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 /// Returns the integer value of MonotonicRawTime as i64
789 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000790 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000791 }
792
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800793 /// Like i64::checked_sub.
794 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
795 self.0.checked_sub(other.0).map(Self)
796 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000797}
798
799impl ToSql for MonotonicRawTime {
800 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
801 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
802 }
803}
804
805impl FromSql for MonotonicRawTime {
806 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
807 Ok(Self(i64::column_result(value)?))
808 }
809}
810
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000811/// This struct encapsulates the information to be stored in the database about the auth tokens
812/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700813#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000814pub struct AuthTokenEntry {
815 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000816 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000817 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000818}
819
820impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000821 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822 AuthTokenEntry { auth_token, time_received }
823 }
824
825 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800826 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000827 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800828 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
829 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000830 })
831 }
832
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000833 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800834 pub fn auth_token(&self) -> &HardwareAuthToken {
835 &self.auth_token
836 }
837
838 /// Returns the auth token wrapped by the AuthTokenEntry
839 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000840 self.auth_token
841 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800842
843 /// Returns the time that this auth token was received.
844 pub fn time_received(&self) -> MonotonicRawTime {
845 self.time_received
846 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000847
848 /// Returns the challenge value of the auth token.
849 pub fn challenge(&self) -> i64 {
850 self.auth_token.challenge
851 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000852}
853
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800854/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
855/// This object does not allow access to the database connection. But it keeps a database
856/// connection alive in order to keep the in memory per boot database alive.
857pub struct PerBootDbKeepAlive(Connection);
858
Joel Galenson26f4d012020-07-17 14:57:21 -0700859impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800860 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700861 const CURRENT_DB_VERSION: u32 = 1;
862 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800863
Seth Moore78c091f2021-04-09 21:38:30 +0000864 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700865 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000866
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700867 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800868 /// files persistent.sqlite and perboot.sqlite in the given directory.
869 /// It also attempts to initialize all of the tables.
870 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700871 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700872 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700873 let _wp = wd::watch_millis("KeystoreDB::new", 500);
874
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700875 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700876 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800877
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700878 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800879 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700880 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
881 .context("In KeystoreDB::new: trying to upgrade database.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800882 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800883 })?;
884 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700885 }
886
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700887 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
888 // cryptographic binding to the boot level keys was implemented.
889 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
890 tx.execute(
891 "UPDATE persistent.keyentry SET state = ?
892 WHERE
893 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
894 AND
895 id NOT IN (
896 SELECT keyentryid FROM persistent.blobentry
897 WHERE id IN (
898 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
899 )
900 );",
901 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
902 )
903 .context("In from_0_to_1: Failed to delete logical boot level keys.")?;
904 Ok(1)
905 }
906
Janis Danisevskis66784c42021-01-27 08:40:25 -0800907 fn init_tables(tx: &Transaction) -> Result<()> {
908 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700910 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800911 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700912 domain INTEGER,
913 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800914 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800915 state INTEGER,
916 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700917 NO_PARAMS,
918 )
919 .context("Failed to initialize \"keyentry\" table.")?;
920
Janis Danisevskis66784c42021-01-27 08:40:25 -0800921 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800922 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
923 ON keyentry(id);",
924 NO_PARAMS,
925 )
926 .context("Failed to create index keyentry_id_index.")?;
927
928 tx.execute(
929 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
930 ON keyentry(domain, namespace, alias);",
931 NO_PARAMS,
932 )
933 .context("Failed to create index keyentry_domain_namespace_index.")?;
934
935 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700936 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
937 id INTEGER PRIMARY KEY,
938 subcomponent_type INTEGER,
939 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800940 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700941 NO_PARAMS,
942 )
943 .context("Failed to initialize \"blobentry\" table.")?;
944
Janis Danisevskis66784c42021-01-27 08:40:25 -0800945 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800946 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
947 ON blobentry(keyentryid);",
948 NO_PARAMS,
949 )
950 .context("Failed to create index blobentry_keyentryid_index.")?;
951
952 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800953 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
954 id INTEGER PRIMARY KEY,
955 blobentryid INTEGER,
956 tag INTEGER,
957 data ANY,
958 UNIQUE (blobentryid, tag));",
959 NO_PARAMS,
960 )
961 .context("Failed to initialize \"blobmetadata\" table.")?;
962
963 tx.execute(
964 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
965 ON blobmetadata(blobentryid);",
966 NO_PARAMS,
967 )
968 .context("Failed to create index blobmetadata_blobentryid_index.")?;
969
970 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700971 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000972 keyentryid INTEGER,
973 tag INTEGER,
974 data ANY,
975 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700976 NO_PARAMS,
977 )
978 .context("Failed to initialize \"keyparameter\" table.")?;
979
Janis Danisevskis66784c42021-01-27 08:40:25 -0800980 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800981 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
982 ON keyparameter(keyentryid);",
983 NO_PARAMS,
984 )
985 .context("Failed to create index keyparameter_keyentryid_index.")?;
986
987 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800988 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
989 keyentryid INTEGER,
990 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000991 data ANY,
992 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800993 NO_PARAMS,
994 )
995 .context("Failed to initialize \"keymetadata\" table.")?;
996
Janis Danisevskis66784c42021-01-27 08:40:25 -0800997 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800998 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
999 ON keymetadata(keyentryid);",
1000 NO_PARAMS,
1001 )
1002 .context("Failed to create index keymetadata_keyentryid_index.")?;
1003
1004 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08001005 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001006 id INTEGER UNIQUE,
1007 grantee INTEGER,
1008 keyentryid INTEGER,
1009 access_vector INTEGER);",
1010 NO_PARAMS,
1011 )
1012 .context("Failed to initialize \"grant\" table.")?;
1013
Joel Galenson0891bc12020-07-20 10:37:03 -07001014 Ok(())
1015 }
1016
Seth Moore472fcbb2021-05-12 10:07:51 -07001017 fn make_persistent_path(db_root: &Path) -> Result<String> {
1018 // Build the path to the sqlite file.
1019 let mut persistent_path = db_root.to_path_buf();
1020 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
1021
1022 // Now convert them to strings prefixed with "file:"
1023 let mut persistent_path_str = "file:".to_owned();
1024 persistent_path_str.push_str(&persistent_path.to_string_lossy());
1025
1026 Ok(persistent_path_str)
1027 }
1028
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001029 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001030 let conn =
1031 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1032
Janis Danisevskis66784c42021-01-27 08:40:25 -08001033 loop {
1034 if let Err(e) = conn
1035 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1036 .context("Failed to attach database persistent.")
1037 {
1038 if Self::is_locked_error(&e) {
1039 std::thread::sleep(std::time::Duration::from_micros(500));
1040 continue;
1041 } else {
1042 return Err(e);
1043 }
1044 }
1045 break;
1046 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001047
Matthew Maurer4fb19112021-05-06 15:40:44 -07001048 // Drop the cache size from default (2M) to 0.5M
1049 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1050 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001051
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001052 Ok(conn)
1053 }
1054
Seth Moore78c091f2021-04-09 21:38:30 +00001055 fn do_table_size_query(
1056 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001057 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001058 query: &str,
1059 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001060 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001061 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001062 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001063 .with_context(|| {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001064 format!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001065 })
1066 .no_gc()
1067 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001068 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001069 }
1070
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001071 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001072 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001073 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001074 "SELECT page_count * page_size, freelist_count * page_size
1075 FROM pragma_page_count('persistent'),
1076 pragma_page_size('persistent'),
1077 persistent.pragma_freelist_count();",
1078 &[],
1079 )
1080 }
1081
1082 fn get_table_size(
1083 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001084 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001085 schema: &str,
1086 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001087 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001088 self.do_table_size_query(
1089 storage_type,
1090 "SELECT pgsize,unused FROM dbstat(?1)
1091 WHERE name=?2 AND aggregate=TRUE;",
1092 &[schema, table],
1093 )
1094 }
1095
1096 /// Fetches a storage statisitics atom for a given storage type. For storage
1097 /// types that map to a table, information about the table's storage is
1098 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001099 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001100 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1101
Seth Moore78c091f2021-04-09 21:38:30 +00001102 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001103 MetricsStorage::DATABASE => self.get_total_size(),
1104 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001105 self.get_table_size(storage_type, "persistent", "keyentry")
1106 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001107 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001108 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1109 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001110 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001111 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1112 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001113 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001114 self.get_table_size(storage_type, "persistent", "blobentry")
1115 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001116 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001120 self.get_table_size(storage_type, "persistent", "keyparameter")
1121 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001122 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001123 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1124 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001125 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001126 self.get_table_size(storage_type, "persistent", "keymetadata")
1127 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001128 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001129 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1130 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001131 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1132 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001133 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1134 // reportable
1135 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001136 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001137 storage_type,
1138 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001139 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001140 unused_size: 0,
1141 })
Seth Moore78c091f2021-04-09 21:38:30 +00001142 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001143 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001144 self.get_table_size(storage_type, "persistent", "blobmetadata")
1145 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001146 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001147 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1148 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001149 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001150 }
1151 }
1152
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001153 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001154 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1155 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001156 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1157 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001158 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001159 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001160 blob_ids_to_delete: &[i64],
1161 max_blobs: usize,
1162 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001163 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001164 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 // Delete the given blobs.
1166 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167 tx.execute(
1168 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001169 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001170 )
1171 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001172 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1173 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001174 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001175
1176 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1177
Janis Danisevskis3395f862021-05-06 10:54:17 -07001178 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1179 let result: Vec<(i64, Vec<u8>)> = {
1180 let mut stmt = tx
1181 .prepare(
1182 "SELECT id, blob FROM persistent.blobentry
1183 WHERE subcomponent_type = ?
1184 AND (
1185 id NOT IN (
1186 SELECT MAX(id) FROM persistent.blobentry
1187 WHERE subcomponent_type = ?
1188 GROUP BY keyentryid, subcomponent_type
1189 )
1190 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1191 ) LIMIT ?;",
1192 )
1193 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001194
Janis Danisevskis3395f862021-05-06 10:54:17 -07001195 let rows = stmt
1196 .query_map(
1197 params![
1198 SubComponentType::KEY_BLOB,
1199 SubComponentType::KEY_BLOB,
1200 max_blobs as i64,
1201 ],
1202 |row| Ok((row.get(0)?, row.get(1)?)),
1203 )
1204 .context("Trying to query superseded blob.")?;
1205
1206 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1207 .context("Trying to extract superseded blobs.")?
1208 };
1209
1210 let result = result
1211 .into_iter()
1212 .map(|(blob_id, blob)| {
1213 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1214 })
1215 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1216 .context("Trying to load blob metadata.")?;
1217 if !result.is_empty() {
1218 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001219 }
1220
1221 // We did not find any superseded key blob, so let's remove other superseded blob in
1222 // one transaction.
1223 tx.execute(
1224 "DELETE FROM persistent.blobentry
1225 WHERE NOT subcomponent_type = ?
1226 AND (
1227 id NOT IN (
1228 SELECT MAX(id) FROM persistent.blobentry
1229 WHERE NOT subcomponent_type = ?
1230 GROUP BY keyentryid, subcomponent_type
1231 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1232 );",
1233 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1234 )
1235 .context("Trying to purge superseded blobs.")?;
1236
Janis Danisevskis3395f862021-05-06 10:54:17 -07001237 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001238 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001239 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001240 }
1241
1242 /// This maintenance function should be called only once before the database is used for the
1243 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1244 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1245 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1246 /// Keystore crashed at some point during key generation. Callers may want to log such
1247 /// occurrences.
1248 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1249 /// it to `KeyLifeCycle::Live` may have grants.
1250 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001251 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1252
Janis Danisevskis66784c42021-01-27 08:40:25 -08001253 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1254 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001255 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1256 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1257 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001258 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001259 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001260 })
1261 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001262 }
1263
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001264 /// Checks if a key exists with given key type and key descriptor properties.
1265 pub fn key_exists(
1266 &mut self,
1267 domain: Domain,
1268 nspace: i64,
1269 alias: &str,
1270 key_type: KeyType,
1271 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001272 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1273
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001274 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1275 let key_descriptor =
1276 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001277 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001278 match result {
1279 Ok(_) => Ok(true),
1280 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1281 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1282 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1283 },
1284 }
1285 .no_gc()
1286 })
1287 .context("In key_exists.")
1288 }
1289
Hasini Gunasingheda895552021-01-27 19:34:37 +00001290 /// Stores a super key in the database.
1291 pub fn store_super_key(
1292 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001293 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001294 key_type: &SuperKeyType,
1295 blob: &[u8],
1296 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001297 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001298 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001299 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1300
Hasini Gunasingheda895552021-01-27 19:34:37 +00001301 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1302 let key_id = Self::insert_with_retry(|id| {
1303 tx.execute(
1304 "INSERT into persistent.keyentry
1305 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001306 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001307 params![
1308 id,
1309 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001310 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001311 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001312 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001313 KeyLifeCycle::Live,
1314 &KEYSTORE_UUID,
1315 ],
1316 )
1317 })
1318 .context("Failed to insert into keyentry table.")?;
1319
Paul Crowley8d5b2532021-03-19 10:53:07 -07001320 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1321
Hasini Gunasingheda895552021-01-27 19:34:37 +00001322 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001323 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001324 key_id,
1325 SubComponentType::KEY_BLOB,
1326 Some(blob),
1327 Some(blob_metadata),
1328 )
1329 .context("Failed to store key blob.")?;
1330
1331 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1332 .context("Trying to load key components.")
1333 .no_gc()
1334 })
1335 .context("In store_super_key.")
1336 }
1337
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001338 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001339 pub fn load_super_key(
1340 &mut self,
1341 key_type: &SuperKeyType,
1342 user_id: u32,
1343 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001344 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1345
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001346 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1347 let key_descriptor = KeyDescriptor {
1348 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001349 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001350 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001351 blob: None,
1352 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001353 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001354 match id {
1355 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001356 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001357 .context("In load_super_key. Failed to load key entry.")?;
1358 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1359 }
1360 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1361 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1362 _ => Err(error).context("In load_super_key."),
1363 },
1364 }
1365 .no_gc()
1366 })
1367 .context("In load_super_key.")
1368 }
1369
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001370 /// Atomically loads a key entry and associated metadata or creates it using the
1371 /// callback create_new_key callback. The callback is called during a database
1372 /// transaction. This means that implementers should be mindful about using
1373 /// blocking operations such as IPC or grabbing mutexes.
1374 pub fn get_or_create_key_with<F>(
1375 &mut self,
1376 domain: Domain,
1377 namespace: i64,
1378 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001379 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001380 create_new_key: F,
1381 ) -> Result<(KeyIdGuard, KeyEntry)>
1382 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001383 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001384 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001385 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1386
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1388 let id = {
1389 let mut stmt = tx
1390 .prepare(
1391 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001392 WHERE
1393 key_type = ?
1394 AND domain = ?
1395 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001396 AND alias = ?
1397 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001398 )
1399 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1400 let mut rows = stmt
1401 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1402 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001403
Janis Danisevskis66784c42021-01-27 08:40:25 -08001404 db_utils::with_rows_extract_one(&mut rows, |row| {
1405 Ok(match row {
1406 Some(r) => r.get(0).context("Failed to unpack id.")?,
1407 None => None,
1408 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001409 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001410 .context("In get_or_create_key_with.")?
1411 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001412
Janis Danisevskis66784c42021-01-27 08:40:25 -08001413 let (id, entry) = match id {
1414 Some(id) => (
1415 id,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001416 Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Janis Danisevskis66784c42021-01-27 08:40:25 -08001417 .context("In get_or_create_key_with.")?,
1418 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001419
Janis Danisevskis66784c42021-01-27 08:40:25 -08001420 None => {
1421 let id = Self::insert_with_retry(|id| {
1422 tx.execute(
1423 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001424 (id, key_type, domain, namespace, alias, state, km_uuid)
1425 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001426 params![
1427 id,
1428 KeyType::Super,
1429 domain.0,
1430 namespace,
1431 alias,
1432 KeyLifeCycle::Live,
1433 km_uuid,
1434 ],
1435 )
1436 })
1437 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001438
Janis Danisevskis66784c42021-01-27 08:40:25 -08001439 let (blob, metadata) =
1440 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001441 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001442 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001443 id,
1444 SubComponentType::KEY_BLOB,
1445 Some(&blob),
1446 Some(&metadata),
1447 )
Paul Crowley7a658392021-03-18 17:08:20 -07001448 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001449 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001450 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001451 KeyEntry {
1452 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001453 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001454 pure_cert: false,
1455 ..Default::default()
1456 },
1457 )
1458 }
1459 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001460 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001461 })
1462 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001463 }
1464
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001465 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001466 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1467 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001468 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1469 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001470 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001471 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001472 loop {
1473 match self
1474 .conn
1475 .transaction_with_behavior(behavior)
1476 .context("In with_transaction.")
1477 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1478 .and_then(|(result, tx)| {
1479 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1480 Ok(result)
1481 }) {
1482 Ok(result) => break Ok(result),
1483 Err(e) => {
1484 if Self::is_locked_error(&e) {
1485 std::thread::sleep(std::time::Duration::from_micros(500));
1486 continue;
1487 } else {
1488 return Err(e).context("In with_transaction.");
1489 }
1490 }
1491 }
1492 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001493 .map(|(need_gc, result)| {
1494 if need_gc {
1495 if let Some(ref gc) = self.gc {
1496 gc.notify_gc();
1497 }
1498 }
1499 result
1500 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001501 }
1502
1503 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001504 matches!(
1505 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1506 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1507 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1508 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001509 }
1510
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001511 /// Creates a new key entry and allocates a new randomized id for the new key.
1512 /// The key id gets associated with a domain and namespace but not with an alias.
1513 /// To complete key generation `rebind_alias` should be called after all of the
1514 /// key artifacts, i.e., blobs and parameters have been associated with the new
1515 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1516 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001517 pub fn create_key_entry(
1518 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001519 domain: &Domain,
1520 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001521 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001522 km_uuid: &Uuid,
1523 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001524 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1525
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001526 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001527 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 })
1529 .context("In create_key_entry.")
1530 }
1531
1532 fn create_key_entry_internal(
1533 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001534 domain: &Domain,
1535 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001536 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001537 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001538 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001539 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001540 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001541 _ => {
1542 return Err(KsError::sys())
1543 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1544 }
1545 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001546 Ok(KEY_ID_LOCK.get(
1547 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001548 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001549 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001550 (id, key_type, domain, namespace, alias, state, km_uuid)
1551 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001552 params![
1553 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001554 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001555 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001556 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001557 KeyLifeCycle::Existing,
1558 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001559 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001560 )
1561 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001562 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001563 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001564 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001565
Max Bires2b2e6562020-09-22 11:22:36 -07001566 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1567 /// The key id gets associated with a domain and namespace later but not with an alias. The
1568 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1569 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1570 /// a key.
1571 pub fn create_attestation_key_entry(
1572 &mut self,
1573 maced_public_key: &[u8],
1574 raw_public_key: &[u8],
1575 private_key: &[u8],
1576 km_uuid: &Uuid,
1577 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001578 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1579
Max Bires2b2e6562020-09-22 11:22:36 -07001580 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1581 let key_id = KEY_ID_LOCK.get(
1582 Self::insert_with_retry(|id| {
1583 tx.execute(
1584 "INSERT into persistent.keyentry
1585 (id, key_type, domain, namespace, alias, state, km_uuid)
1586 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1587 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1588 )
1589 })
1590 .context("In create_key_entry")?,
1591 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001592 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001593 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001594 key_id.0,
1595 SubComponentType::KEY_BLOB,
1596 Some(private_key),
1597 None,
1598 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001599 let mut metadata = KeyMetaData::new();
1600 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1601 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001602 metadata.store_in_db(key_id.0, tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001603 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001604 })
1605 .context("In create_attestation_key_entry")
1606 }
1607
Janis Danisevskis377d1002021-01-27 19:07:48 -08001608 /// Set a new blob and associates it with the given key id. Each blob
1609 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001610 /// Each key can have one of each sub component type associated. If more
1611 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001612 /// will get garbage collected.
1613 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1614 /// removed by setting blob to None.
1615 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001616 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001617 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001618 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001619 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001620 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001621 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001622 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1623
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001624 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001625 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001626 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001627 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001628 }
1629
Janis Danisevskiseed69842021-02-18 20:04:10 -08001630 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1631 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1632 /// We use this to insert key blobs into the database which can then be garbage collected
1633 /// lazily by the key garbage collector.
1634 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001635 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1636
Janis Danisevskiseed69842021-02-18 20:04:10 -08001637 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1638 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001639 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001640 Self::UNASSIGNED_KEY_ID,
1641 SubComponentType::KEY_BLOB,
1642 Some(blob),
1643 Some(blob_metadata),
1644 )
1645 .need_gc()
1646 })
1647 .context("In set_deleted_blob.")
1648 }
1649
Janis Danisevskis377d1002021-01-27 19:07:48 -08001650 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001651 tx: &Transaction,
1652 key_id: i64,
1653 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001654 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001655 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001656 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001657 match (blob, sc_type) {
1658 (Some(blob), _) => {
1659 tx.execute(
1660 "INSERT INTO persistent.blobentry
1661 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1662 params![sc_type, key_id, blob],
1663 )
1664 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001665 if let Some(blob_metadata) = blob_metadata {
1666 let blob_id = tx
1667 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1668 row.get(0)
1669 })
1670 .context("In set_blob_internal: Failed to get new blob id.")?;
1671 blob_metadata
1672 .store_in_db(blob_id, tx)
1673 .context("In set_blob_internal: Trying to store blob metadata.")?;
1674 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001675 }
1676 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1677 tx.execute(
1678 "DELETE FROM persistent.blobentry
1679 WHERE subcomponent_type = ? AND keyentryid = ?;",
1680 params![sc_type, key_id],
1681 )
1682 .context("In set_blob_internal: Failed to delete blob.")?;
1683 }
1684 (None, _) => {
1685 return Err(KsError::sys())
1686 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1687 }
1688 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001689 Ok(())
1690 }
1691
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001692 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1693 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001694 #[cfg(test)]
1695 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001696 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001697 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001698 })
1699 .context("In insert_keyparameter.")
1700 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001701
Janis Danisevskis66784c42021-01-27 08:40:25 -08001702 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001703 tx: &Transaction,
1704 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001705 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001706 ) -> Result<()> {
1707 let mut stmt = tx
1708 .prepare(
1709 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1710 VALUES (?, ?, ?, ?);",
1711 )
1712 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1713
Janis Danisevskis66784c42021-01-27 08:40:25 -08001714 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001715 stmt.insert(params![
1716 key_id.0,
1717 p.get_tag().0,
1718 p.key_parameter_value(),
1719 p.security_level().0
1720 ])
1721 .with_context(|| {
1722 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1723 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001724 }
1725 Ok(())
1726 }
1727
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001728 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001729 #[cfg(test)]
1730 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001731 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001732 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001733 })
1734 .context("In insert_key_metadata.")
1735 }
1736
Max Bires2b2e6562020-09-22 11:22:36 -07001737 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1738 /// on the public key.
1739 pub fn store_signed_attestation_certificate_chain(
1740 &mut self,
1741 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001742 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001743 cert_chain: &[u8],
1744 expiration_date: i64,
1745 km_uuid: &Uuid,
1746 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001747 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1748
Max Bires2b2e6562020-09-22 11:22:36 -07001749 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1750 let mut stmt = tx
1751 .prepare(
1752 "SELECT keyentryid
1753 FROM persistent.keymetadata
1754 WHERE tag = ? AND data = ? AND keyentryid IN
1755 (SELECT id
1756 FROM persistent.keyentry
1757 WHERE
1758 alias IS NULL AND
1759 domain IS NULL AND
1760 namespace IS NULL AND
1761 key_type = ? AND
1762 km_uuid = ?);",
1763 )
1764 .context("Failed to store attestation certificate chain.")?;
1765 let mut rows = stmt
1766 .query(params![
1767 KeyMetaData::AttestationRawPubKey,
1768 raw_public_key,
1769 KeyType::Attestation,
1770 km_uuid
1771 ])
1772 .context("Failed to fetch keyid")?;
1773 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1774 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1775 .get(0)
1776 .context("Failed to unpack id.")
1777 })
1778 .context("Failed to get key_id.")?;
1779 let num_updated = tx
1780 .execute(
1781 "UPDATE persistent.keyentry
1782 SET alias = ?
1783 WHERE id = ?;",
1784 params!["signed", key_id],
1785 )
1786 .context("Failed to update alias.")?;
1787 if num_updated != 1 {
1788 return Err(KsError::sys()).context("Alias not updated for the key.");
1789 }
1790 let mut metadata = KeyMetaData::new();
1791 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1792 expiration_date,
1793 )));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001794 metadata.store_in_db(key_id, tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001795 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001796 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001797 key_id,
1798 SubComponentType::CERT_CHAIN,
1799 Some(cert_chain),
1800 None,
1801 )
1802 .context("Failed to insert cert chain")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001803 Self::set_blob_internal(tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
Max Biresb2e1d032021-02-08 21:35:05 -08001804 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001805 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001806 })
1807 .context("In store_signed_attestation_certificate_chain: ")
1808 }
1809
1810 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1811 /// currently have a key assigned to it.
1812 pub fn assign_attestation_key(
1813 &mut self,
1814 domain: Domain,
1815 namespace: i64,
1816 km_uuid: &Uuid,
1817 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001818 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1819
Max Bires2b2e6562020-09-22 11:22:36 -07001820 match domain {
1821 Domain::APP | Domain::SELINUX => {}
1822 _ => {
1823 return Err(KsError::sys()).context(format!(
1824 concat!(
1825 "In assign_attestation_key: Domain {:?} ",
1826 "must be either App or SELinux.",
1827 ),
1828 domain
1829 ));
1830 }
1831 }
1832 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1833 let result = tx
1834 .execute(
1835 "UPDATE persistent.keyentry
1836 SET domain=?1, namespace=?2
1837 WHERE
1838 id =
1839 (SELECT MIN(id)
1840 FROM persistent.keyentry
1841 WHERE ALIAS IS NOT NULL
1842 AND domain IS NULL
1843 AND key_type IS ?3
1844 AND state IS ?4
1845 AND km_uuid IS ?5)
1846 AND
1847 (SELECT COUNT(*)
1848 FROM persistent.keyentry
1849 WHERE domain=?1
1850 AND namespace=?2
1851 AND key_type IS ?3
1852 AND state IS ?4
1853 AND km_uuid IS ?5) = 0;",
1854 params![
1855 domain.0 as u32,
1856 namespace,
1857 KeyType::Attestation,
1858 KeyLifeCycle::Live,
1859 km_uuid,
1860 ],
1861 )
1862 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001863 if result == 0 {
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +00001864 log_rkp_error_stats(MetricsRkpError::OUT_OF_KEYS);
Max Bires01f8af22021-03-02 23:24:50 -08001865 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1866 } else if result > 1 {
1867 return Err(KsError::sys())
1868 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001869 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001870 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001871 })
1872 .context("In assign_attestation_key: ")
1873 }
1874
1875 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1876 /// provisioning server, or the maximum number available if there are not num_keys number of
1877 /// entries in the table.
1878 pub fn fetch_unsigned_attestation_keys(
1879 &mut self,
1880 num_keys: i32,
1881 km_uuid: &Uuid,
1882 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001883 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1884
Max Bires2b2e6562020-09-22 11:22:36 -07001885 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1886 let mut stmt = tx
1887 .prepare(
1888 "SELECT data
1889 FROM persistent.keymetadata
1890 WHERE tag = ? AND keyentryid IN
1891 (SELECT id
1892 FROM persistent.keyentry
1893 WHERE
1894 alias IS NULL AND
1895 domain IS NULL AND
1896 namespace IS NULL AND
1897 key_type = ? AND
1898 km_uuid = ?
1899 LIMIT ?);",
1900 )
1901 .context("Failed to prepare statement")?;
1902 let rows = stmt
1903 .query_map(
1904 params![
1905 KeyMetaData::AttestationMacedPublicKey,
1906 KeyType::Attestation,
1907 km_uuid,
1908 num_keys
1909 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001910 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001911 )?
1912 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1913 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001914 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001915 })
1916 .context("In fetch_unsigned_attestation_keys")
1917 }
1918
1919 /// Removes any keys that have expired as of the current time. Returns the number of keys
1920 /// marked unreferenced that are bound to be garbage collected.
1921 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001922 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1923
Max Bires2b2e6562020-09-22 11:22:36 -07001924 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1925 let mut stmt = tx
1926 .prepare(
1927 "SELECT keyentryid, data
1928 FROM persistent.keymetadata
1929 WHERE tag = ? AND keyentryid IN
1930 (SELECT id
1931 FROM persistent.keyentry
1932 WHERE key_type = ?);",
1933 )
1934 .context("Failed to prepare query")?;
1935 let key_ids_to_check = stmt
1936 .query_map(
1937 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1938 |row| Ok((row.get(0)?, row.get(1)?)),
1939 )?
1940 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1941 .context("Failed to get date metadata")?;
1942 let curr_time = DateTime::from_millis_epoch(
1943 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1944 );
1945 let mut num_deleted = 0;
1946 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001947 if Self::mark_unreferenced(tx, id)? {
Max Bires2b2e6562020-09-22 11:22:36 -07001948 num_deleted += 1;
1949 }
1950 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001951 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001952 })
1953 .context("In delete_expired_attestation_keys: ")
1954 }
1955
Max Bires60d7ed12021-03-05 15:59:22 -08001956 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1957 /// they are in. This is useful primarily as a testing mechanism.
1958 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001959 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1960
Max Bires60d7ed12021-03-05 15:59:22 -08001961 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1962 let mut stmt = tx
1963 .prepare(
1964 "SELECT id FROM persistent.keyentry
1965 WHERE key_type IS ?;",
1966 )
1967 .context("Failed to prepare statement")?;
1968 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001969 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001970 .collect::<rusqlite::Result<Vec<i64>>>()
1971 .context("Failed to execute statement")?;
1972 let num_deleted = keys_to_delete
1973 .iter()
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001974 .map(|id| Self::mark_unreferenced(tx, *id))
Max Bires60d7ed12021-03-05 15:59:22 -08001975 .collect::<Result<Vec<bool>>>()
1976 .context("Failed to execute mark_unreferenced on a keyid")?
1977 .into_iter()
1978 .filter(|result| *result)
1979 .count() as i64;
1980 Ok(num_deleted).do_gc(num_deleted != 0)
1981 })
1982 .context("In delete_all_attestation_keys: ")
1983 }
1984
Max Bires2b2e6562020-09-22 11:22:36 -07001985 /// Counts the number of keys that will expire by the provided epoch date and the number of
1986 /// keys not currently assigned to a domain.
1987 pub fn get_attestation_pool_status(
1988 &mut self,
1989 date: i64,
1990 km_uuid: &Uuid,
1991 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001992 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1993
Max Bires2b2e6562020-09-22 11:22:36 -07001994 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1995 let mut stmt = tx.prepare(
1996 "SELECT data
1997 FROM persistent.keymetadata
1998 WHERE tag = ? AND keyentryid IN
1999 (SELECT id
2000 FROM persistent.keyentry
2001 WHERE alias IS NOT NULL
2002 AND key_type = ?
2003 AND km_uuid = ?
2004 AND state = ?);",
2005 )?;
2006 let times = stmt
2007 .query_map(
2008 params![
2009 KeyMetaData::AttestationExpirationDate,
2010 KeyType::Attestation,
2011 km_uuid,
2012 KeyLifeCycle::Live
2013 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07002014 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07002015 )?
2016 .collect::<rusqlite::Result<Vec<DateTime>>>()
2017 .context("Failed to execute metadata statement")?;
2018 let expiring =
2019 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
2020 as i32;
2021 stmt = tx.prepare(
2022 "SELECT alias, domain
2023 FROM persistent.keyentry
2024 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
2025 )?;
2026 let rows = stmt
2027 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2028 Ok((row.get(0)?, row.get(1)?))
2029 })?
2030 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2031 .context("Failed to execute keyentry statement")?;
2032 let mut unassigned = 0i32;
2033 let mut attested = 0i32;
2034 let total = rows.len() as i32;
2035 for (alias, domain) in rows {
2036 match (alias, domain) {
2037 (Some(_alias), None) => {
2038 attested += 1;
2039 unassigned += 1;
2040 }
2041 (Some(_alias), Some(_domain)) => {
2042 attested += 1;
2043 }
2044 _ => {}
2045 }
2046 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002047 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002048 })
2049 .context("In get_attestation_pool_status: ")
2050 }
2051
Max Bires55620ff2022-02-11 13:34:15 -08002052 fn query_kid_for_attestation_key_and_cert_chain(
2053 &self,
2054 tx: &Transaction,
2055 domain: Domain,
2056 namespace: i64,
2057 km_uuid: &Uuid,
2058 ) -> Result<Option<i64>> {
2059 let mut stmt = tx.prepare(
2060 "SELECT id
2061 FROM persistent.keyentry
2062 WHERE key_type = ?
2063 AND domain = ?
2064 AND namespace = ?
2065 AND state = ?
2066 AND km_uuid = ?;",
2067 )?;
2068 let rows = stmt
2069 .query_map(
2070 params![
2071 KeyType::Attestation,
2072 domain.0 as u32,
2073 namespace,
2074 KeyLifeCycle::Live,
2075 km_uuid
2076 ],
2077 |row| row.get(0),
2078 )?
2079 .collect::<rusqlite::Result<Vec<i64>>>()
2080 .context("query failed.")?;
2081 if rows.is_empty() {
2082 return Ok(None);
2083 }
2084 Ok(Some(rows[0]))
2085 }
2086
Max Bires2b2e6562020-09-22 11:22:36 -07002087 /// Fetches the private key and corresponding certificate chain assigned to a
2088 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2089 /// not assigned, or one CertificateChain.
2090 pub fn retrieve_attestation_key_and_cert_chain(
2091 &mut self,
2092 domain: Domain,
2093 namespace: i64,
2094 km_uuid: &Uuid,
Max Bires55620ff2022-02-11 13:34:15 -08002095 ) -> Result<Option<(KeyIdGuard, CertificateChain)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002096 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2097
Max Bires2b2e6562020-09-22 11:22:36 -07002098 match domain {
2099 Domain::APP | Domain::SELINUX => {}
2100 _ => {
2101 return Err(KsError::sys())
2102 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2103 }
2104 }
Max Bires55620ff2022-02-11 13:34:15 -08002105
2106 let tx = self.conn.unchecked_transaction().context(
2107 "In retrieve_attestation_key_and_cert_chain: Failed to initialize transaction.",
2108 )?;
2109 let key_id: i64;
2110 match self.query_kid_for_attestation_key_and_cert_chain(&tx, domain, namespace, km_uuid)? {
2111 None => return Ok(None),
2112 Some(kid) => key_id = kid,
2113 }
2114 tx.commit()
2115 .context("In retrieve_attestation_key_and_cert_chain: Failed to commit keyid query")?;
2116 let key_id_guard = KEY_ID_LOCK.get(key_id);
2117 let tx = self.conn.unchecked_transaction().context(
2118 "In retrieve_attestation_key_and_cert_chain: Failed to initialize transaction.",
2119 )?;
2120 let mut stmt = tx.prepare(
2121 "SELECT subcomponent_type, blob
2122 FROM persistent.blobentry
2123 WHERE keyentryid = ?;",
2124 )?;
2125 let rows = stmt
2126 .query_map(params![key_id_guard.id()], |row| Ok((row.get(0)?, row.get(1)?)))?
2127 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
2128 .context("query failed.")?;
2129 if rows.is_empty() {
2130 return Ok(None);
2131 } else if rows.len() != 3 {
2132 return Err(KsError::sys()).context(format!(
2133 concat!(
2134 "Expected to get a single attestation",
2135 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2136 ),
2137 rows.len()
2138 ));
2139 }
2140 let mut km_blob: Vec<u8> = Vec::new();
2141 let mut cert_chain_blob: Vec<u8> = Vec::new();
2142 let mut batch_cert_blob: Vec<u8> = Vec::new();
2143 for row in rows {
2144 let sub_type: SubComponentType = row.0;
2145 match sub_type {
2146 SubComponentType::KEY_BLOB => {
2147 km_blob = row.1;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002148 }
Max Bires55620ff2022-02-11 13:34:15 -08002149 SubComponentType::CERT_CHAIN => {
2150 cert_chain_blob = row.1;
2151 }
2152 SubComponentType::CERT => {
2153 batch_cert_blob = row.1;
2154 }
2155 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002156 }
Max Bires55620ff2022-02-11 13:34:15 -08002157 }
2158 Ok(Some((
2159 key_id_guard,
2160 CertificateChain {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002161 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002162 batch_cert: batch_cert_blob,
2163 cert_chain: cert_chain_blob,
Max Bires55620ff2022-02-11 13:34:15 -08002164 },
2165 )))
Max Bires2b2e6562020-09-22 11:22:36 -07002166 }
2167
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002168 /// Updates the alias column of the given key id `newid` with the given alias,
2169 /// and atomically, removes the alias, domain, and namespace from another row
2170 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002171 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2172 /// collector.
2173 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002174 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002175 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002176 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002177 domain: &Domain,
2178 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002179 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002180 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002181 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002182 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002183 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002184 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002185 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002186 domain
2187 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002188 }
2189 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002190 let updated = tx
2191 .execute(
2192 "UPDATE persistent.keyentry
2193 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002194 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2195 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002196 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002197 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002198 let result = tx
2199 .execute(
2200 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002201 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002202 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002203 params![
2204 alias,
2205 KeyLifeCycle::Live,
2206 newid.0,
2207 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002208 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002209 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002210 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002211 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002212 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002213 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002214 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002215 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002216 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002217 result
2218 ));
2219 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002220 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002221 }
2222
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002223 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2224 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2225 pub fn migrate_key_namespace(
2226 &mut self,
2227 key_id_guard: KeyIdGuard,
2228 destination: &KeyDescriptor,
2229 caller_uid: u32,
2230 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2231 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002232 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2233
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002234 let destination = match destination.domain {
2235 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2236 Domain::SELINUX => (*destination).clone(),
2237 domain => {
2238 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2239 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2240 }
2241 };
2242
2243 // Security critical: Must return immediately on failure. Do not remove the '?';
2244 check_permission(&destination)
2245 .context("In migrate_key_namespace: Trying to check permission.")?;
2246
2247 let alias = destination
2248 .alias
2249 .as_ref()
2250 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2251 .context("In migrate_key_namespace: Alias must be specified.")?;
2252
2253 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2254 // Query the destination location. If there is a key, the migration request fails.
2255 if tx
2256 .query_row(
2257 "SELECT id FROM persistent.keyentry
2258 WHERE alias = ? AND domain = ? AND namespace = ?;",
2259 params![alias, destination.domain.0, destination.nspace],
2260 |_| Ok(()),
2261 )
2262 .optional()
2263 .context("Failed to query destination.")?
2264 .is_some()
2265 {
2266 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2267 .context("Target already exists.");
2268 }
2269
2270 let updated = tx
2271 .execute(
2272 "UPDATE persistent.keyentry
2273 SET alias = ?, domain = ?, namespace = ?
2274 WHERE id = ?;",
2275 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2276 )
2277 .context("Failed to update key entry.")?;
2278
2279 if updated != 1 {
2280 return Err(KsError::sys())
2281 .context(format!("Update succeeded, but {} rows were updated.", updated));
2282 }
2283 Ok(()).no_gc()
2284 })
2285 .context("In migrate_key_namespace:")
2286 }
2287
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002288 /// Store a new key in a single transaction.
2289 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2290 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002291 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2292 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07002293 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002294 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002295 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002296 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002297 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002298 params: &[KeyParameter],
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002299 blob_info: &BlobInfo,
Max Bires8e93d2b2021-01-14 13:17:59 -08002300 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002301 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002302 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002303 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002304 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2305
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002306 let (alias, domain, namespace) = match key {
2307 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2308 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2309 (alias, key.domain, nspace)
2310 }
2311 _ => {
2312 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2313 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2314 }
2315 };
2316 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002317 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002318 .context("Trying to create new key entry.")?;
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002319 let BlobInfo { blob, metadata: blob_metadata, superseded_blob } = *blob_info;
2320
2321 // In some occasions the key blob is already upgraded during the import.
2322 // In order to make sure it gets properly deleted it is inserted into the
2323 // database here and then immediately replaced by the superseding blob.
2324 // The garbage collector will then subject the blob to deleteKey of the
2325 // KM back end to permanently invalidate the key.
2326 let need_gc = if let Some((blob, blob_metadata)) = superseded_blob {
2327 Self::set_blob_internal(
2328 tx,
2329 key_id.id(),
2330 SubComponentType::KEY_BLOB,
2331 Some(blob),
2332 Some(blob_metadata),
2333 )
2334 .context("Trying to insert superseded key blob.")?;
2335 true
2336 } else {
2337 false
2338 };
2339
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002340 Self::set_blob_internal(
2341 tx,
2342 key_id.id(),
2343 SubComponentType::KEY_BLOB,
2344 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002345 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002346 )
2347 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002348 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002349 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002350 .context("Trying to insert the certificate.")?;
2351 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002352 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002353 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002354 tx,
2355 key_id.id(),
2356 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002357 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002358 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002359 )
2360 .context("Trying to insert the certificate chain.")?;
2361 }
2362 Self::insert_keyparameter_internal(tx, &key_id, params)
2363 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002364 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002365 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08002366 .context("Trying to rebind alias.")?
2367 || need_gc;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002368 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002369 })
2370 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002371 }
2372
Janis Danisevskis377d1002021-01-27 19:07:48 -08002373 /// Store a new certificate
2374 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2375 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002376 pub fn store_new_certificate(
2377 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002378 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002379 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002380 cert: &[u8],
2381 km_uuid: &Uuid,
2382 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002383 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2384
Janis Danisevskis377d1002021-01-27 19:07:48 -08002385 let (alias, domain, namespace) = match key {
2386 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2387 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2388 (alias, key.domain, nspace)
2389 }
2390 _ => {
2391 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2392 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2393 )
2394 }
2395 };
2396 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002397 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002398 .context("Trying to create new key entry.")?;
2399
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002400 Self::set_blob_internal(
2401 tx,
2402 key_id.id(),
2403 SubComponentType::CERT_CHAIN,
2404 Some(cert),
2405 None,
2406 )
2407 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002408
2409 let mut metadata = KeyMetaData::new();
2410 metadata.add(KeyMetaEntry::CreationDate(
2411 DateTime::now().context("Trying to make creation time.")?,
2412 ));
2413
2414 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2415
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002416 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002417 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002418 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002419 })
2420 .context("In store_new_certificate.")
2421 }
2422
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002423 // Helper function loading the key_id given the key descriptor
2424 // tuple comprising domain, namespace, and alias.
2425 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002426 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002427 let alias = key
2428 .alias
2429 .as_ref()
2430 .map_or_else(|| Err(KsError::sys()), Ok)
2431 .context("In load_key_entry_id: Alias must be specified.")?;
2432 let mut stmt = tx
2433 .prepare(
2434 "SELECT id FROM persistent.keyentry
2435 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002436 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002437 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002438 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002439 AND alias = ?
2440 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002441 )
2442 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2443 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002444 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002445 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002446 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002447 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002448 .get(0)
2449 .context("Failed to unpack id.")
2450 })
2451 .context("In load_key_entry_id.")
2452 }
2453
2454 /// This helper function completes the access tuple of a key, which is required
2455 /// to perform access control. The strategy depends on the `domain` field in the
2456 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002457 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002458 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002459 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002460 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002461 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002462 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002463 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002464 /// `namespace`.
2465 /// In each case the information returned is sufficient to perform the access
2466 /// check and the key id can be used to load further key artifacts.
2467 fn load_access_tuple(
2468 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002469 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002470 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002471 caller_uid: u32,
2472 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2473 match key.domain {
2474 // Domain App or SELinux. In this case we load the key_id from
2475 // the keyentry database for further loading of key components.
2476 // We already have the full access tuple to perform access control.
2477 // The only distinction is that we use the caller_uid instead
2478 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002479 // Domain::APP.
2480 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002481 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002482 if access_key.domain == Domain::APP {
2483 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002484 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002485 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002486 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002487
2488 Ok((key_id, access_key, None))
2489 }
2490
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002491 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002492 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002493 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002494 let mut stmt = tx
2495 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002496 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002497 WHERE grantee = ? AND id = ? AND
2498 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002499 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002500 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002501 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002502 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002503 .context("Domain:Grant: query failed.")?;
2504 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002505 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002506 let r =
2507 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002508 Ok((
2509 r.get(0).context("Failed to unpack key_id.")?,
2510 r.get(1).context("Failed to unpack access_vector.")?,
2511 ))
2512 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002513 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002514 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002515 }
2516
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002517 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002518 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002519 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002520 let (domain, namespace): (Domain, i64) = {
2521 let mut stmt = tx
2522 .prepare(
2523 "SELECT domain, namespace FROM persistent.keyentry
2524 WHERE
2525 id = ?
2526 AND state = ?;",
2527 )
2528 .context("Domain::KEY_ID: prepare statement failed")?;
2529 let mut rows = stmt
2530 .query(params![key.nspace, KeyLifeCycle::Live])
2531 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002532 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002533 let r =
2534 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002535 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002536 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002537 r.get(1).context("Failed to unpack namespace.")?,
2538 ))
2539 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002540 .context("Domain::KEY_ID.")?
2541 };
2542
2543 // We may use a key by id after loading it by grant.
2544 // In this case we have to check if the caller has a grant for this particular
2545 // key. We can skip this if we already know that the caller is the owner.
2546 // But we cannot know this if domain is anything but App. E.g. in the case
2547 // of Domain::SELINUX we have to speculatively check for grants because we have to
2548 // consult the SEPolicy before we know if the caller is the owner.
2549 let access_vector: Option<KeyPermSet> =
2550 if domain != Domain::APP || namespace != caller_uid as i64 {
2551 let access_vector: Option<i32> = tx
2552 .query_row(
2553 "SELECT access_vector FROM persistent.grant
2554 WHERE grantee = ? AND keyentryid = ?;",
2555 params![caller_uid as i64, key.nspace],
2556 |row| row.get(0),
2557 )
2558 .optional()
2559 .context("Domain::KEY_ID: query grant failed.")?;
2560 access_vector.map(|p| p.into())
2561 } else {
2562 None
2563 };
2564
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002565 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002566 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002567 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002568 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002569
Janis Danisevskis45760022021-01-19 16:34:10 -08002570 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002571 }
2572 _ => Err(anyhow!(KsError::sys())),
2573 }
2574 }
2575
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002576 fn load_blob_components(
2577 key_id: i64,
2578 load_bits: KeyEntryLoadBits,
2579 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002580 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002581 let mut stmt = tx
2582 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002583 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002584 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2585 )
2586 .context("In load_blob_components: prepare statement failed.")?;
2587
2588 let mut rows =
2589 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2590
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002591 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002592 let mut cert_blob: Option<Vec<u8>> = None;
2593 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002594 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002595 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002596 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002597 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002598 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002599 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2600 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002601 key_blob = Some((
2602 row.get(0).context("Failed to extract key blob id.")?,
2603 row.get(2).context("Failed to extract key blob.")?,
2604 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002605 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002606 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002607 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002608 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002609 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002610 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002611 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002612 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002613 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002614 (SubComponentType::CERT, _, _)
2615 | (SubComponentType::CERT_CHAIN, _, _)
2616 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002617 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2618 }
2619 Ok(())
2620 })
2621 .context("In load_blob_components.")?;
2622
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002623 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2624 Ok(Some((
2625 blob,
2626 BlobMetaData::load_from_db(blob_id, tx)
2627 .context("In load_blob_components: Trying to load blob_metadata.")?,
2628 )))
2629 })?;
2630
2631 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002632 }
2633
2634 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2635 let mut stmt = tx
2636 .prepare(
2637 "SELECT tag, data, security_level from persistent.keyparameter
2638 WHERE keyentryid = ?;",
2639 )
2640 .context("In load_key_parameters: prepare statement failed.")?;
2641
2642 let mut parameters: Vec<KeyParameter> = Vec::new();
2643
2644 let mut rows =
2645 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002646 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002647 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2648 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002649 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002650 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002651 .context("Failed to read KeyParameter.")?,
2652 );
2653 Ok(())
2654 })
2655 .context("In load_key_parameters.")?;
2656
2657 Ok(parameters)
2658 }
2659
Qi Wub9433b52020-12-01 14:52:46 +08002660 /// Decrements the usage count of a limited use key. This function first checks whether the
2661 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2662 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2663 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002664 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002665 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2666
Qi Wub9433b52020-12-01 14:52:46 +08002667 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2668 let limit: Option<i32> = tx
2669 .query_row(
2670 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2671 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2672 |row| row.get(0),
2673 )
2674 .optional()
2675 .context("Trying to load usage count")?;
2676
2677 let limit = limit
2678 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2679 .context("The Key no longer exists. Key is exhausted.")?;
2680
2681 tx.execute(
2682 "UPDATE persistent.keyparameter
2683 SET data = data - 1
2684 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2685 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2686 )
2687 .context("Failed to update key usage count.")?;
2688
2689 match limit {
2690 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002691 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002692 .context("Trying to mark limited use key for deletion."),
2693 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002694 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002695 }
2696 })
2697 .context("In check_and_update_key_usage_count.")
2698 }
2699
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002700 /// Load a key entry by the given key descriptor.
2701 /// It uses the `check_permission` callback to verify if the access is allowed
2702 /// given the key access tuple read from the database using `load_access_tuple`.
2703 /// With `load_bits` the caller may specify which blobs shall be loaded from
2704 /// the blob database.
2705 pub fn load_key_entry(
2706 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002707 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002708 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002709 load_bits: KeyEntryLoadBits,
2710 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002711 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2712 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002713 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2714
Janis Danisevskis66784c42021-01-27 08:40:25 -08002715 loop {
2716 match self.load_key_entry_internal(
2717 key,
2718 key_type,
2719 load_bits,
2720 caller_uid,
2721 &check_permission,
2722 ) {
2723 Ok(result) => break Ok(result),
2724 Err(e) => {
2725 if Self::is_locked_error(&e) {
2726 std::thread::sleep(std::time::Duration::from_micros(500));
2727 continue;
2728 } else {
2729 return Err(e).context("In load_key_entry.");
2730 }
2731 }
2732 }
2733 }
2734 }
2735
2736 fn load_key_entry_internal(
2737 &mut self,
2738 key: &KeyDescriptor,
2739 key_type: KeyType,
2740 load_bits: KeyEntryLoadBits,
2741 caller_uid: u32,
2742 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002743 ) -> Result<(KeyIdGuard, KeyEntry)> {
2744 // KEY ID LOCK 1/2
2745 // If we got a key descriptor with a key id we can get the lock right away.
2746 // Otherwise we have to defer it until we know the key id.
2747 let key_id_guard = match key.domain {
2748 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2749 _ => None,
2750 };
2751
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002752 let tx = self
2753 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002754 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002755 .context("In load_key_entry: Failed to initialize transaction.")?;
2756
2757 // Load the key_id and complete the access control tuple.
2758 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002759 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2760 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002761
2762 // Perform access control. It is vital that we return here if the permission is denied.
2763 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002764 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002765
Janis Danisevskisaec14592020-11-12 09:41:49 -08002766 // KEY ID LOCK 2/2
2767 // If we did not get a key id lock by now, it was because we got a key descriptor
2768 // without a key id. At this point we got the key id, so we can try and get a lock.
2769 // However, we cannot block here, because we are in the middle of the transaction.
2770 // So first we try to get the lock non blocking. If that fails, we roll back the
2771 // transaction and block until we get the lock. After we successfully got the lock,
2772 // we start a new transaction and load the access tuple again.
2773 //
2774 // We don't need to perform access control again, because we already established
2775 // that the caller had access to the given key. But we need to make sure that the
2776 // key id still exists. So we have to load the key entry by key id this time.
2777 let (key_id_guard, tx) = match key_id_guard {
2778 None => match KEY_ID_LOCK.try_get(key_id) {
2779 None => {
2780 // Roll back the transaction.
2781 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002782
Janis Danisevskisaec14592020-11-12 09:41:49 -08002783 // Block until we have a key id lock.
2784 let key_id_guard = KEY_ID_LOCK.get(key_id);
2785
2786 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002787 let tx = self
2788 .conn
2789 .unchecked_transaction()
2790 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002791
2792 Self::load_access_tuple(
2793 &tx,
2794 // This time we have to load the key by the retrieved key id, because the
2795 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002796 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002797 domain: Domain::KEY_ID,
2798 nspace: key_id,
2799 ..Default::default()
2800 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002801 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002802 caller_uid,
2803 )
2804 .context("In load_key_entry. (deferred key lock)")?;
2805 (key_id_guard, tx)
2806 }
2807 Some(l) => (l, tx),
2808 },
2809 Some(key_id_guard) => (key_id_guard, tx),
2810 };
2811
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002812 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2813 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002814
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002815 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2816
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002817 Ok((key_id_guard, key_entry))
2818 }
2819
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002820 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002821 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002822 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2823 .context("Trying to delete keyentry.")?;
2824 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2825 .context("Trying to delete keymetadata.")?;
2826 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2827 .context("Trying to delete keyparameters.")?;
2828 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2829 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002830 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002831 }
2832
2833 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002834 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002835 pub fn unbind_key(
2836 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002837 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002838 key_type: KeyType,
2839 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002840 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002841 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002842 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2843
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002844 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2845 let (key_id, access_key_descriptor, access_vector) =
2846 Self::load_access_tuple(tx, key, key_type, caller_uid)
2847 .context("Trying to get access tuple.")?;
2848
2849 // Perform access control. It is vital that we return here if the permission is denied.
2850 // So do not touch that '?' at the end.
2851 check_permission(&access_key_descriptor, access_vector)
2852 .context("While checking permission.")?;
2853
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002854 Self::mark_unreferenced(tx, key_id)
2855 .map(|need_gc| (need_gc, ()))
2856 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002857 })
2858 .context("In unbind_key.")
2859 }
2860
Max Bires8e93d2b2021-01-14 13:17:59 -08002861 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2862 tx.query_row(
2863 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2864 params![key_id],
2865 |row| row.get(0),
2866 )
2867 .context("In get_key_km_uuid.")
2868 }
2869
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002870 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2871 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2872 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002873 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2874
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002875 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2876 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2877 .context("In unbind_keys_for_namespace.");
2878 }
2879 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2880 tx.execute(
2881 "DELETE FROM persistent.keymetadata
2882 WHERE keyentryid IN (
2883 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002884 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002885 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002886 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002887 )
2888 .context("Trying to delete keymetadata.")?;
2889 tx.execute(
2890 "DELETE FROM persistent.keyparameter
2891 WHERE keyentryid IN (
2892 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002893 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002894 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002895 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002896 )
2897 .context("Trying to delete keyparameters.")?;
2898 tx.execute(
2899 "DELETE FROM persistent.grant
2900 WHERE keyentryid IN (
2901 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002902 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002903 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002904 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002905 )
2906 .context("Trying to delete grants.")?;
2907 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002908 "DELETE FROM persistent.keyentry
2909 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2910 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002911 )
2912 .context("Trying to delete keyentry.")?;
2913 Ok(()).need_gc()
2914 })
2915 .context("In unbind_keys_for_namespace")
2916 }
2917
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002918 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2919 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2920 {
2921 tx.execute(
2922 "DELETE FROM persistent.keymetadata
2923 WHERE keyentryid IN (
2924 SELECT id FROM persistent.keyentry
2925 WHERE state = ?
2926 );",
2927 params![KeyLifeCycle::Unreferenced],
2928 )
2929 .context("Trying to delete keymetadata.")?;
2930 tx.execute(
2931 "DELETE FROM persistent.keyparameter
2932 WHERE keyentryid IN (
2933 SELECT id FROM persistent.keyentry
2934 WHERE state = ?
2935 );",
2936 params![KeyLifeCycle::Unreferenced],
2937 )
2938 .context("Trying to delete keyparameters.")?;
2939 tx.execute(
2940 "DELETE FROM persistent.grant
2941 WHERE keyentryid IN (
2942 SELECT id FROM persistent.keyentry
2943 WHERE state = ?
2944 );",
2945 params![KeyLifeCycle::Unreferenced],
2946 )
2947 .context("Trying to delete grants.")?;
2948 tx.execute(
2949 "DELETE FROM persistent.keyentry
2950 WHERE state = ?;",
2951 params![KeyLifeCycle::Unreferenced],
2952 )
2953 .context("Trying to delete keyentry.")?;
2954 Result::<()>::Ok(())
2955 }
2956 .context("In cleanup_unreferenced")
2957 }
2958
Hasini Gunasingheda895552021-01-27 19:34:37 +00002959 /// Delete the keys created on behalf of the user, denoted by the user id.
2960 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2961 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2962 /// The caller of this function should notify the gc if the returned value is true.
2963 pub fn unbind_keys_for_user(
2964 &mut self,
2965 user_id: u32,
2966 keep_non_super_encrypted_keys: bool,
2967 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002968 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2969
Hasini Gunasingheda895552021-01-27 19:34:37 +00002970 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2971 let mut stmt = tx
2972 .prepare(&format!(
2973 "SELECT id from persistent.keyentry
2974 WHERE (
2975 key_type = ?
2976 AND domain = ?
2977 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2978 AND state = ?
2979 ) OR (
2980 key_type = ?
2981 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002982 AND state = ?
2983 );",
2984 aid_user_offset = AID_USER_OFFSET
2985 ))
2986 .context(concat!(
2987 "In unbind_keys_for_user. ",
2988 "Failed to prepare the query to find the keys created by apps."
2989 ))?;
2990
2991 let mut rows = stmt
2992 .query(params![
2993 // WHERE client key:
2994 KeyType::Client,
2995 Domain::APP.0 as u32,
2996 user_id,
2997 KeyLifeCycle::Live,
2998 // OR super key:
2999 KeyType::Super,
3000 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00003001 KeyLifeCycle::Live
3002 ])
3003 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
3004
3005 let mut key_ids: Vec<i64> = Vec::new();
3006 db_utils::with_rows_extract_all(&mut rows, |row| {
3007 key_ids
3008 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
3009 Ok(())
3010 })
3011 .context("In unbind_keys_for_user.")?;
3012
3013 let mut notify_gc = false;
3014 for key_id in key_ids {
3015 if keep_non_super_encrypted_keys {
3016 // Load metadata and filter out non-super-encrypted keys.
3017 if let (_, Some((_, blob_metadata)), _, _) =
3018 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
3019 .context("In unbind_keys_for_user: Trying to load blob info.")?
3020 {
3021 if blob_metadata.encrypted_by().is_none() {
3022 continue;
3023 }
3024 }
3025 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003026 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00003027 .context("In unbind_keys_for_user.")?
3028 || notify_gc;
3029 }
3030 Ok(()).do_gc(notify_gc)
3031 })
3032 .context("In unbind_keys_for_user.")
3033 }
3034
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003035 fn load_key_components(
3036 tx: &Transaction,
3037 load_bits: KeyEntryLoadBits,
3038 key_id: i64,
3039 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003040 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003041
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003042 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003043 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003044
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003045 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08003046 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003047
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003048 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08003049 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003050
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003051 Ok(KeyEntry {
3052 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003053 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003054 cert: cert_blob,
3055 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08003056 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003057 parameters,
3058 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003059 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003060 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003061 }
3062
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003063 /// Returns a list of KeyDescriptors in the selected domain/namespace.
3064 /// The key descriptors will have the domain, nspace, and alias field set.
3065 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07003066 pub fn list(
3067 &mut self,
3068 domain: Domain,
3069 namespace: i64,
3070 key_type: KeyType,
3071 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003072 let _wp = wd::watch_millis("KeystoreDB::list", 500);
3073
Janis Danisevskis66784c42021-01-27 08:40:25 -08003074 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3075 let mut stmt = tx
3076 .prepare(
3077 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07003078 WHERE domain = ?
3079 AND namespace = ?
3080 AND alias IS NOT NULL
3081 AND state = ?
3082 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003083 )
3084 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003085
Janis Danisevskis66784c42021-01-27 08:40:25 -08003086 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003087 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08003088 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003089
Janis Danisevskis66784c42021-01-27 08:40:25 -08003090 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3091 db_utils::with_rows_extract_all(&mut rows, |row| {
3092 descriptors.push(KeyDescriptor {
3093 domain,
3094 nspace: namespace,
3095 alias: Some(row.get(0).context("Trying to extract alias.")?),
3096 blob: None,
3097 });
3098 Ok(())
3099 })
3100 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003101 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003102 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003103 }
3104
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003105 /// Adds a grant to the grant table.
3106 /// Like `load_key_entry` this function loads the access tuple before
3107 /// it uses the callback for a permission check. Upon success,
3108 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3109 /// grant table. The new row will have a randomized id, which is used as
3110 /// grant id in the namespace field of the resulting KeyDescriptor.
3111 pub fn grant(
3112 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003113 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003114 caller_uid: u32,
3115 grantee_uid: u32,
3116 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003117 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003118 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003119 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3120
Janis Danisevskis66784c42021-01-27 08:40:25 -08003121 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3122 // Load the key_id and complete the access control tuple.
3123 // We ignore the access vector here because grants cannot be granted.
3124 // The access vector returned here expresses the permissions the
3125 // grantee has if key.domain == Domain::GRANT. But this vector
3126 // cannot include the grant permission by design, so there is no way the
3127 // subsequent permission check can pass.
3128 // We could check key.domain == Domain::GRANT and fail early.
3129 // But even if we load the access tuple by grant here, the permission
3130 // check denies the attempt to create a grant by grant descriptor.
3131 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003132 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003133 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003134
Janis Danisevskis66784c42021-01-27 08:40:25 -08003135 // Perform access control. It is vital that we return here if the permission
3136 // was denied. So do not touch that '?' at the end of the line.
3137 // This permission check checks if the caller has the grant permission
3138 // for the given key and in addition to all of the permissions
3139 // expressed in `access_vector`.
3140 check_permission(&access_key_descriptor, &access_vector)
3141 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003142
Janis Danisevskis66784c42021-01-27 08:40:25 -08003143 let grant_id = if let Some(grant_id) = tx
3144 .query_row(
3145 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003146 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003147 params![key_id, grantee_uid],
3148 |row| row.get(0),
3149 )
3150 .optional()
3151 .context("In grant: Failed get optional existing grant id.")?
3152 {
3153 tx.execute(
3154 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003155 SET access_vector = ?
3156 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003157 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003158 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003159 .context("In grant: Failed to update existing grant.")?;
3160 grant_id
3161 } else {
3162 Self::insert_with_retry(|id| {
3163 tx.execute(
3164 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3165 VALUES (?, ?, ?, ?);",
3166 params![id, grantee_uid, key_id, i32::from(access_vector)],
3167 )
3168 })
3169 .context("In grant")?
3170 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003171
Janis Danisevskis66784c42021-01-27 08:40:25 -08003172 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003173 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003174 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003175 }
3176
3177 /// This function checks permissions like `grant` and `load_key_entry`
3178 /// before removing a grant from the grant table.
3179 pub fn ungrant(
3180 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003181 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003182 caller_uid: u32,
3183 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003184 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003185 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003186 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3187
Janis Danisevskis66784c42021-01-27 08:40:25 -08003188 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3189 // Load the key_id and complete the access control tuple.
3190 // We ignore the access vector here because grants cannot be granted.
3191 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003192 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003193 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003194
Janis Danisevskis66784c42021-01-27 08:40:25 -08003195 // Perform access control. We must return here if the permission
3196 // was denied. So do not touch the '?' at the end of this line.
3197 check_permission(&access_key_descriptor)
3198 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003199
Janis Danisevskis66784c42021-01-27 08:40:25 -08003200 tx.execute(
3201 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003202 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003203 params![key_id, grantee_uid],
3204 )
3205 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003206
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003207 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003208 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003209 }
3210
Joel Galenson845f74b2020-09-09 14:11:55 -07003211 // Generates a random id and passes it to the given function, which will
3212 // try to insert it into a database. If that insertion fails, retry;
3213 // otherwise return the id.
3214 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3215 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003216 let newid: i64 = match random() {
3217 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3218 i => i,
3219 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003220 match inserter(newid) {
3221 // If the id already existed, try again.
3222 Err(rusqlite::Error::SqliteFailure(
3223 libsqlite3_sys::Error {
3224 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3225 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3226 },
3227 _,
3228 )) => (),
3229 Err(e) => {
3230 return Err(e).context("In insert_with_retry: failed to insert into database.")
3231 }
3232 _ => return Ok(newid),
3233 }
3234 }
3235 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003236
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003237 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3238 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3239 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3240 auth_token.clone(),
3241 MonotonicRawTime::now(),
3242 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003243 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003244
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003245 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003246 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003247 where
3248 F: Fn(&AuthTokenEntry) -> bool,
3249 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003250 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003251 }
3252
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003253 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003254 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3255 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003256 }
3257
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003258 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003259 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3260 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003261 }
3262
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003263 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003264 fn get_last_off_body(&self) -> MonotonicRawTime {
3265 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003266 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003267
3268 /// Load descriptor of a key by key id
3269 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3270 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3271
3272 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3273 tx.query_row(
3274 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3275 params![key_id],
3276 |row| {
3277 Ok(KeyDescriptor {
3278 domain: Domain(row.get(0)?),
3279 nspace: row.get(1)?,
3280 alias: row.get(2)?,
3281 blob: None,
3282 })
3283 },
3284 )
3285 .optional()
3286 .context("Trying to load key descriptor")
3287 .no_gc()
3288 })
3289 .context("In load_key_descriptor.")
3290 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003291}
3292
3293#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08003294pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07003295
3296 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003297 use crate::key_parameter::{
3298 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3299 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3300 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003301 use crate::key_perm_set;
3302 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08003303 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003304 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003305 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3306 HardwareAuthToken::HardwareAuthToken,
3307 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003308 };
3309 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003310 Timestamp::Timestamp,
3311 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003312 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003313 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003314 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003315 use std::collections::BTreeMap;
3316 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003317 use std::sync::atomic::{AtomicU8, Ordering};
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003318 use std::sync::{Arc, RwLock};
Janis Danisevskisaec14592020-11-12 09:41:49 -08003319 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003320 use std::time::{Duration, SystemTime};
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08003321 use crate::utils::AesGcm;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003322 #[cfg(disabled)]
3323 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003324
Seth Moore7ee79f92021-12-07 11:42:49 -08003325 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003326 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003327
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003328 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003329 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003330 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003331 })?;
3332 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003333 }
3334
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003335 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3336 where
3337 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3338 {
Janis Danisevskis0fd25a62022-01-04 19:53:37 -08003339 let super_key: Arc<RwLock<SuperKeyManager>> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003340
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003341 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003342 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003343
Janis Danisevskis3395f862021-05-06 10:54:17 -07003344 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003345 }
3346
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003347 fn rebind_alias(
3348 db: &mut KeystoreDB,
3349 newid: &KeyIdGuard,
3350 alias: &str,
3351 domain: Domain,
3352 namespace: i64,
3353 ) -> Result<bool> {
3354 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003355 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003356 })
3357 .context("In rebind_alias.")
3358 }
3359
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003360 #[test]
3361 fn datetime() -> Result<()> {
3362 let conn = Connection::open_in_memory()?;
3363 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3364 let now = SystemTime::now();
3365 let duration = Duration::from_secs(1000);
3366 let then = now.checked_sub(duration).unwrap();
3367 let soon = now.checked_add(duration).unwrap();
3368 conn.execute(
3369 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3370 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3371 )?;
3372 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3373 let mut rows = stmt.query(NO_PARAMS)?;
3374 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3375 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3376 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3377 assert!(rows.next()?.is_none());
3378 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3379 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3380 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3381 Ok(())
3382 }
3383
Joel Galenson0891bc12020-07-20 10:37:03 -07003384 // Ensure that we're using the "injected" random function, not the real one.
3385 #[test]
3386 fn test_mocked_random() {
3387 let rand1 = random();
3388 let rand2 = random();
3389 let rand3 = random();
3390 if rand1 == rand2 {
3391 assert_eq!(rand2 + 1, rand3);
3392 } else {
3393 assert_eq!(rand1 + 1, rand2);
3394 assert_eq!(rand2, rand3);
3395 }
3396 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003397
Joel Galenson26f4d012020-07-17 14:57:21 -07003398 // Test that we have the correct tables.
3399 #[test]
3400 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003401 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003402 let tables = db
3403 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003404 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003405 .query_map(params![], |row| row.get(0))?
3406 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003407 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003408 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003409 assert_eq!(tables[1], "blobmetadata");
3410 assert_eq!(tables[2], "grant");
3411 assert_eq!(tables[3], "keyentry");
3412 assert_eq!(tables[4], "keymetadata");
3413 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003414 Ok(())
3415 }
3416
3417 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003418 fn test_auth_token_table_invariant() -> Result<()> {
3419 let mut db = new_test_db()?;
3420 let auth_token1 = HardwareAuthToken {
3421 challenge: i64::MAX,
3422 userId: 200,
3423 authenticatorId: 200,
3424 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3425 timestamp: Timestamp { milliSeconds: 500 },
3426 mac: String::from("mac").into_bytes(),
3427 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003428 db.insert_auth_token(&auth_token1);
3429 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003430 assert_eq!(auth_tokens_returned.len(), 1);
3431
3432 // insert another auth token with the same values for the columns in the UNIQUE constraint
3433 // of the auth token table and different value for timestamp
3434 let auth_token2 = HardwareAuthToken {
3435 challenge: i64::MAX,
3436 userId: 200,
3437 authenticatorId: 200,
3438 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3439 timestamp: Timestamp { milliSeconds: 600 },
3440 mac: String::from("mac").into_bytes(),
3441 };
3442
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003443 db.insert_auth_token(&auth_token2);
3444 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003445 assert_eq!(auth_tokens_returned.len(), 1);
3446
3447 if let Some(auth_token) = auth_tokens_returned.pop() {
3448 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3449 }
3450
3451 // insert another auth token with the different values for the columns in the UNIQUE
3452 // constraint of the auth token table
3453 let auth_token3 = HardwareAuthToken {
3454 challenge: i64::MAX,
3455 userId: 201,
3456 authenticatorId: 200,
3457 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3458 timestamp: Timestamp { milliSeconds: 600 },
3459 mac: String::from("mac").into_bytes(),
3460 };
3461
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003462 db.insert_auth_token(&auth_token3);
3463 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003464 assert_eq!(auth_tokens_returned.len(), 2);
3465
3466 Ok(())
3467 }
3468
3469 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003470 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3471 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003472 }
3473
3474 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003475 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003476 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003477 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003478
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003479 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003480 let entries = get_keyentry(&db)?;
3481 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003482
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003483 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003484
3485 let entries_new = get_keyentry(&db)?;
3486 assert_eq!(entries, entries_new);
3487 Ok(())
3488 }
3489
3490 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003491 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003492 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3493 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003494 }
3495
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003496 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003497
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003498 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3499 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003500
3501 let entries = get_keyentry(&db)?;
3502 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003503 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3504 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003505
3506 // Test that we must pass in a valid Domain.
3507 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003508 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003509 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003510 );
3511 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003512 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003513 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003514 );
3515 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003516 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003517 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003518 );
3519
3520 Ok(())
3521 }
3522
Joel Galenson33c04ad2020-08-03 11:04:38 -07003523 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003524 fn test_add_unsigned_key() -> Result<()> {
3525 let mut db = new_test_db()?;
3526 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3527 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3528 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3529 db.create_attestation_key_entry(
3530 &public_key,
3531 &raw_public_key,
3532 &private_key,
3533 &KEYSTORE_UUID,
3534 )?;
3535 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3536 assert_eq!(keys.len(), 1);
3537 assert_eq!(keys[0], public_key);
3538 Ok(())
3539 }
3540
3541 #[test]
3542 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3543 let mut db = new_test_db()?;
3544 let expiration_date: i64 = 20;
3545 let namespace: i64 = 30;
3546 let base_byte: u8 = 1;
3547 let loaded_values =
3548 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3549 let chain =
3550 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Chris Wailes3877f292021-07-26 19:24:18 -07003551 assert!(chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003552 let (_, cert_chain) = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003553 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003554 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3555 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003556 Ok(())
3557 }
3558
3559 #[test]
3560 fn test_get_attestation_pool_status() -> Result<()> {
3561 let mut db = new_test_db()?;
3562 let namespace: i64 = 30;
3563 load_attestation_key_pool(
3564 &mut db, 10, /* expiration */
3565 namespace, 0x01, /* base_byte */
3566 )?;
3567 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3568 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3569 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3570 assert_eq!(status.expiring, 0);
3571 assert_eq!(status.attested, 3);
3572 assert_eq!(status.unassigned, 0);
3573 assert_eq!(status.total, 3);
3574 assert_eq!(
3575 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3576 1
3577 );
3578 assert_eq!(
3579 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3580 2
3581 );
3582 assert_eq!(
3583 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3584 3
3585 );
3586 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3587 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3588 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3589 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003590 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003591 db.create_attestation_key_entry(
3592 &public_key,
3593 &raw_public_key,
3594 &private_key,
3595 &KEYSTORE_UUID,
3596 )?;
3597 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3598 assert_eq!(status.attested, 3);
3599 assert_eq!(status.unassigned, 0);
3600 assert_eq!(status.total, 4);
3601 db.store_signed_attestation_certificate_chain(
3602 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003603 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003604 &cert_chain,
3605 20,
3606 &KEYSTORE_UUID,
3607 )?;
3608 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3609 assert_eq!(status.attested, 4);
3610 assert_eq!(status.unassigned, 1);
3611 assert_eq!(status.total, 4);
3612 Ok(())
3613 }
3614
3615 #[test]
3616 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003617 let temp_dir =
3618 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3619 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003620 let expiration_date: i64 =
3621 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3622 let namespace: i64 = 30;
3623 let namespace_del1: i64 = 45;
3624 let namespace_del2: i64 = 60;
3625 let entry_values = load_attestation_key_pool(
3626 &mut db,
3627 expiration_date,
3628 namespace,
3629 0x01, /* base_byte */
3630 )?;
3631 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3632 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003633
3634 let blob_entry_row_count: u32 = db
3635 .conn
3636 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3637 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003638 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3639 // one key, one certificate chain, and one certificate.
3640 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003641
Max Bires2b2e6562020-09-22 11:22:36 -07003642 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3643
3644 let mut cert_chain =
3645 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003646 assert!(cert_chain.is_some());
Max Bires55620ff2022-02-11 13:34:15 -08003647 let (_, value) = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003648 assert_eq!(entry_values.batch_cert, value.batch_cert);
3649 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003650 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003651
3652 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3653 Domain::APP,
3654 namespace_del1,
3655 &KEYSTORE_UUID,
3656 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003657 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003658 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3659 Domain::APP,
3660 namespace_del2,
3661 &KEYSTORE_UUID,
3662 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003663 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003664
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003665 // Give the garbage collector half a second to catch up.
3666 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003667
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003668 let blob_entry_row_count: u32 = db
3669 .conn
3670 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3671 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003672 // There shound be 3 blob entries left, because we deleted two of the attestation
3673 // key entries with three blobs each.
3674 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003675
Max Bires2b2e6562020-09-22 11:22:36 -07003676 Ok(())
3677 }
3678
3679 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003680 fn test_delete_all_attestation_keys() -> Result<()> {
3681 let mut db = new_test_db()?;
3682 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3683 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003684 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003685 let result = db.delete_all_attestation_keys()?;
3686
3687 // Give the garbage collector half a second to catch up.
3688 std::thread::sleep(Duration::from_millis(500));
3689
3690 // Attestation keys should be deleted, and the regular key should remain.
3691 assert_eq!(result, 2);
3692
3693 Ok(())
3694 }
3695
3696 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003697 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003698 fn extractor(
3699 ke: &KeyEntryRow,
3700 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3701 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003702 }
3703
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003704 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003705 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3706 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003707 let entries = get_keyentry(&db)?;
3708 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003709 assert_eq!(
3710 extractor(&entries[0]),
3711 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3712 );
3713 assert_eq!(
3714 extractor(&entries[1]),
3715 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3716 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003717
3718 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003719 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003720 let entries = get_keyentry(&db)?;
3721 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003722 assert_eq!(
3723 extractor(&entries[0]),
3724 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3725 );
3726 assert_eq!(
3727 extractor(&entries[1]),
3728 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3729 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003730
3731 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003732 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003733 let entries = get_keyentry(&db)?;
3734 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003735 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3736 assert_eq!(
3737 extractor(&entries[1]),
3738 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3739 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003740
3741 // Test that we must pass in a valid Domain.
3742 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003743 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003744 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003745 );
3746 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003747 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003748 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003749 );
3750 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003751 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003752 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003753 );
3754
3755 // Test that we correctly handle setting an alias for something that does not exist.
3756 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003757 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003758 "Expected to update a single entry but instead updated 0",
3759 );
3760 // Test that we correctly abort the transaction in this case.
3761 let entries = get_keyentry(&db)?;
3762 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003763 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3764 assert_eq!(
3765 extractor(&entries[1]),
3766 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3767 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003768
3769 Ok(())
3770 }
3771
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003772 #[test]
3773 fn test_grant_ungrant() -> Result<()> {
3774 const CALLER_UID: u32 = 15;
3775 const GRANTEE_UID: u32 = 12;
3776 const SELINUX_NAMESPACE: i64 = 7;
3777
3778 let mut db = new_test_db()?;
3779 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003780 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3781 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3782 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003783 )?;
3784 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003785 domain: super::Domain::APP,
3786 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003787 alias: Some("key".to_string()),
3788 blob: None,
3789 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003790 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3791 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003792
3793 // Reset totally predictable random number generator in case we
3794 // are not the first test running on this thread.
3795 reset_random();
3796 let next_random = 0i64;
3797
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003798 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003799 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003800 assert_eq!(*a, PVEC1);
3801 assert_eq!(
3802 *k,
3803 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003804 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003805 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003806 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003807 alias: Some("key".to_string()),
3808 blob: None,
3809 }
3810 );
3811 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003812 })
3813 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003814
3815 assert_eq!(
3816 app_granted_key,
3817 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003818 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003819 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003820 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003821 alias: None,
3822 blob: None,
3823 }
3824 );
3825
3826 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003827 domain: super::Domain::SELINUX,
3828 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003829 alias: Some("yek".to_string()),
3830 blob: None,
3831 };
3832
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003833 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003834 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003835 assert_eq!(*a, PVEC1);
3836 assert_eq!(
3837 *k,
3838 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003839 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003840 // namespace must be the supplied SELinux
3841 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003842 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003843 alias: Some("yek".to_string()),
3844 blob: None,
3845 }
3846 );
3847 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003848 })
3849 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003850
3851 assert_eq!(
3852 selinux_granted_key,
3853 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003854 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003855 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003856 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003857 alias: None,
3858 blob: None,
3859 }
3860 );
3861
3862 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003863 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003864 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003865 assert_eq!(*a, PVEC2);
3866 assert_eq!(
3867 *k,
3868 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003869 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003870 // namespace must be the supplied SELinux
3871 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003872 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003873 alias: Some("yek".to_string()),
3874 blob: None,
3875 }
3876 );
3877 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003878 })
3879 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003880
3881 assert_eq!(
3882 selinux_granted_key,
3883 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003884 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003885 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003886 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003887 alias: None,
3888 blob: None,
3889 }
3890 );
3891
3892 {
3893 // Limiting scope of stmt, because it borrows db.
3894 let mut stmt = db
3895 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003896 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003897 let mut rows =
3898 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3899 Ok((
3900 row.get(0)?,
3901 row.get(1)?,
3902 row.get(2)?,
3903 KeyPermSet::from(row.get::<_, i32>(3)?),
3904 ))
3905 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003906
3907 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003908 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003909 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003910 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003911 assert!(rows.next().is_none());
3912 }
3913
3914 debug_dump_keyentry_table(&mut db)?;
3915 println!("app_key {:?}", app_key);
3916 println!("selinux_key {:?}", selinux_key);
3917
Janis Danisevskis66784c42021-01-27 08:40:25 -08003918 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3919 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003920
3921 Ok(())
3922 }
3923
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003924 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003925 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3926 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3927
3928 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003929 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003930 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003931 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003932 let mut blob_metadata = BlobMetaData::new();
3933 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3934 db.set_blob(
3935 &key_id,
3936 SubComponentType::KEY_BLOB,
3937 Some(TEST_KEY_BLOB),
3938 Some(&blob_metadata),
3939 )?;
3940 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3941 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003942 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003943
3944 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003945 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003946 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003947 )?;
3948 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003949 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3950 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003951 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003952 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003953 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003954 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003955 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003956 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003957 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003958
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003959 drop(rows);
3960 drop(stmt);
3961
3962 assert_eq!(
3963 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3964 BlobMetaData::load_from_db(id, tx).no_gc()
3965 })
3966 .expect("Should find blob metadata."),
3967 blob_metadata
3968 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003969 Ok(())
3970 }
3971
3972 static TEST_ALIAS: &str = "my super duper key";
3973
3974 #[test]
3975 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3976 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003977 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003978 .context("test_insert_and_load_full_keyentry_domain_app")?
3979 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003980 let (_key_guard, key_entry) = db
3981 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003982 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003983 domain: Domain::APP,
3984 nspace: 0,
3985 alias: Some(TEST_ALIAS.to_string()),
3986 blob: None,
3987 },
3988 KeyType::Client,
3989 KeyEntryLoadBits::BOTH,
3990 1,
3991 |_k, _av| Ok(()),
3992 )
3993 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003994 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003995
3996 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003997 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003998 domain: Domain::APP,
3999 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004000 alias: Some(TEST_ALIAS.to_string()),
4001 blob: None,
4002 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004003 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004004 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004005 |_, _| Ok(()),
4006 )
4007 .unwrap();
4008
4009 assert_eq!(
4010 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4011 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004012 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004013 domain: Domain::APP,
4014 nspace: 0,
4015 alias: Some(TEST_ALIAS.to_string()),
4016 blob: None,
4017 },
4018 KeyType::Client,
4019 KeyEntryLoadBits::NONE,
4020 1,
4021 |_k, _av| Ok(()),
4022 )
4023 .unwrap_err()
4024 .root_cause()
4025 .downcast_ref::<KsError>()
4026 );
4027
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004028 Ok(())
4029 }
4030
4031 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08004032 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
4033 let mut db = new_test_db()?;
4034
4035 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004036 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004037 domain: Domain::APP,
4038 nspace: 1,
4039 alias: Some(TEST_ALIAS.to_string()),
4040 blob: None,
4041 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07004042 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004043 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08004044 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004045 )
4046 .expect("Trying to insert cert.");
4047
4048 let (_key_guard, mut key_entry) = db
4049 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004050 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004051 domain: Domain::APP,
4052 nspace: 1,
4053 alias: Some(TEST_ALIAS.to_string()),
4054 blob: None,
4055 },
4056 KeyType::Client,
4057 KeyEntryLoadBits::PUBLIC,
4058 1,
4059 |_k, _av| Ok(()),
4060 )
4061 .expect("Trying to read certificate entry.");
4062
4063 assert!(key_entry.pure_cert());
4064 assert!(key_entry.cert().is_none());
4065 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
4066
4067 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004068 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004069 domain: Domain::APP,
4070 nspace: 1,
4071 alias: Some(TEST_ALIAS.to_string()),
4072 blob: None,
4073 },
4074 KeyType::Client,
4075 1,
4076 |_, _| Ok(()),
4077 )
4078 .unwrap();
4079
4080 assert_eq!(
4081 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4082 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004083 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004084 domain: Domain::APP,
4085 nspace: 1,
4086 alias: Some(TEST_ALIAS.to_string()),
4087 blob: None,
4088 },
4089 KeyType::Client,
4090 KeyEntryLoadBits::NONE,
4091 1,
4092 |_k, _av| Ok(()),
4093 )
4094 .unwrap_err()
4095 .root_cause()
4096 .downcast_ref::<KsError>()
4097 );
4098
4099 Ok(())
4100 }
4101
4102 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004103 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4104 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004105 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004106 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4107 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004108 let (_key_guard, key_entry) = db
4109 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004110 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004111 domain: Domain::SELINUX,
4112 nspace: 1,
4113 alias: Some(TEST_ALIAS.to_string()),
4114 blob: None,
4115 },
4116 KeyType::Client,
4117 KeyEntryLoadBits::BOTH,
4118 1,
4119 |_k, _av| Ok(()),
4120 )
4121 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004122 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004123
4124 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004125 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004126 domain: Domain::SELINUX,
4127 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004128 alias: Some(TEST_ALIAS.to_string()),
4129 blob: None,
4130 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004131 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004132 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004133 |_, _| Ok(()),
4134 )
4135 .unwrap();
4136
4137 assert_eq!(
4138 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4139 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004140 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004141 domain: Domain::SELINUX,
4142 nspace: 1,
4143 alias: Some(TEST_ALIAS.to_string()),
4144 blob: None,
4145 },
4146 KeyType::Client,
4147 KeyEntryLoadBits::NONE,
4148 1,
4149 |_k, _av| Ok(()),
4150 )
4151 .unwrap_err()
4152 .root_cause()
4153 .downcast_ref::<KsError>()
4154 );
4155
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004156 Ok(())
4157 }
4158
4159 #[test]
4160 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4161 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004162 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004163 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4164 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004165 let (_, key_entry) = db
4166 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004167 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004168 KeyType::Client,
4169 KeyEntryLoadBits::BOTH,
4170 1,
4171 |_k, _av| Ok(()),
4172 )
4173 .unwrap();
4174
Qi Wub9433b52020-12-01 14:52:46 +08004175 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004176
4177 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004178 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004179 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004180 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004181 |_, _| Ok(()),
4182 )
4183 .unwrap();
4184
4185 assert_eq!(
4186 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4187 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004188 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004189 KeyType::Client,
4190 KeyEntryLoadBits::NONE,
4191 1,
4192 |_k, _av| Ok(()),
4193 )
4194 .unwrap_err()
4195 .root_cause()
4196 .downcast_ref::<KsError>()
4197 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004198
4199 Ok(())
4200 }
4201
4202 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004203 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4204 let mut db = new_test_db()?;
4205 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4206 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4207 .0;
4208 // Update the usage count of the limited use key.
4209 db.check_and_update_key_usage_count(key_id)?;
4210
4211 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004212 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004213 KeyType::Client,
4214 KeyEntryLoadBits::BOTH,
4215 1,
4216 |_k, _av| Ok(()),
4217 )?;
4218
4219 // The usage count is decremented now.
4220 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4221
4222 Ok(())
4223 }
4224
4225 #[test]
4226 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4227 let mut db = new_test_db()?;
4228 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4229 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4230 .0;
4231 // Update the usage count of the limited use key.
4232 db.check_and_update_key_usage_count(key_id).expect(concat!(
4233 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4234 "This should succeed."
4235 ));
4236
4237 // Try to update the exhausted limited use key.
4238 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4239 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4240 "This should fail."
4241 ));
4242 assert_eq!(
4243 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4244 e.root_cause().downcast_ref::<KsError>().unwrap()
4245 );
4246
4247 Ok(())
4248 }
4249
4250 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004251 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4252 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004253 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004254 .context("test_insert_and_load_full_keyentry_from_grant")?
4255 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004256
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004257 let granted_key = db
4258 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004259 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004260 domain: Domain::APP,
4261 nspace: 0,
4262 alias: Some(TEST_ALIAS.to_string()),
4263 blob: None,
4264 },
4265 1,
4266 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004267 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004268 |_k, _av| Ok(()),
4269 )
4270 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004271
4272 debug_dump_grant_table(&mut db)?;
4273
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004274 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004275 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4276 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004277 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08004278 Ok(())
4279 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004280 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004281
Qi Wub9433b52020-12-01 14:52:46 +08004282 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004283
Janis Danisevskis66784c42021-01-27 08:40:25 -08004284 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004285
4286 assert_eq!(
4287 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4288 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004289 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004290 KeyType::Client,
4291 KeyEntryLoadBits::NONE,
4292 2,
4293 |_k, _av| Ok(()),
4294 )
4295 .unwrap_err()
4296 .root_cause()
4297 .downcast_ref::<KsError>()
4298 );
4299
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004300 Ok(())
4301 }
4302
Janis Danisevskis45760022021-01-19 16:34:10 -08004303 // This test attempts to load a key by key id while the caller is not the owner
4304 // but a grant exists for the given key and the caller.
4305 #[test]
4306 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4307 let mut db = new_test_db()?;
4308 const OWNER_UID: u32 = 1u32;
4309 const GRANTEE_UID: u32 = 2u32;
4310 const SOMEONE_ELSE_UID: u32 = 3u32;
4311 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4312 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4313 .0;
4314
4315 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004316 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004317 domain: Domain::APP,
4318 nspace: 0,
4319 alias: Some(TEST_ALIAS.to_string()),
4320 blob: None,
4321 },
4322 OWNER_UID,
4323 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004324 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08004325 |_k, _av| Ok(()),
4326 )
4327 .unwrap();
4328
4329 debug_dump_grant_table(&mut db)?;
4330
4331 let id_descriptor =
4332 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4333
4334 let (_, key_entry) = db
4335 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004336 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004337 KeyType::Client,
4338 KeyEntryLoadBits::BOTH,
4339 GRANTEE_UID,
4340 |k, av| {
4341 assert_eq!(Domain::APP, k.domain);
4342 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004343 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08004344 Ok(())
4345 },
4346 )
4347 .unwrap();
4348
4349 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4350
4351 let (_, key_entry) = db
4352 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004353 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004354 KeyType::Client,
4355 KeyEntryLoadBits::BOTH,
4356 SOMEONE_ELSE_UID,
4357 |k, av| {
4358 assert_eq!(Domain::APP, k.domain);
4359 assert_eq!(OWNER_UID as i64, k.nspace);
4360 assert!(av.is_none());
4361 Ok(())
4362 },
4363 )
4364 .unwrap();
4365
4366 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4367
Janis Danisevskis66784c42021-01-27 08:40:25 -08004368 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004369
4370 assert_eq!(
4371 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4372 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004373 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004374 KeyType::Client,
4375 KeyEntryLoadBits::NONE,
4376 GRANTEE_UID,
4377 |_k, _av| Ok(()),
4378 )
4379 .unwrap_err()
4380 .root_cause()
4381 .downcast_ref::<KsError>()
4382 );
4383
4384 Ok(())
4385 }
4386
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004387 // Creates a key migrates it to a different location and then tries to access it by the old
4388 // and new location.
4389 #[test]
4390 fn test_migrate_key_app_to_app() -> Result<()> {
4391 let mut db = new_test_db()?;
4392 const SOURCE_UID: u32 = 1u32;
4393 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004394 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4395 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004396 let key_id_guard =
4397 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4398 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4399
4400 let source_descriptor: KeyDescriptor = KeyDescriptor {
4401 domain: Domain::APP,
4402 nspace: -1,
4403 alias: Some(SOURCE_ALIAS.to_string()),
4404 blob: None,
4405 };
4406
4407 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4408 domain: Domain::APP,
4409 nspace: -1,
4410 alias: Some(DESTINATION_ALIAS.to_string()),
4411 blob: None,
4412 };
4413
4414 let key_id = key_id_guard.id();
4415
4416 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4417 Ok(())
4418 })
4419 .unwrap();
4420
4421 let (_, key_entry) = db
4422 .load_key_entry(
4423 &destination_descriptor,
4424 KeyType::Client,
4425 KeyEntryLoadBits::BOTH,
4426 DESTINATION_UID,
4427 |k, av| {
4428 assert_eq!(Domain::APP, k.domain);
4429 assert_eq!(DESTINATION_UID as i64, k.nspace);
4430 assert!(av.is_none());
4431 Ok(())
4432 },
4433 )
4434 .unwrap();
4435
4436 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4437
4438 assert_eq!(
4439 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4440 db.load_key_entry(
4441 &source_descriptor,
4442 KeyType::Client,
4443 KeyEntryLoadBits::NONE,
4444 SOURCE_UID,
4445 |_k, _av| Ok(()),
4446 )
4447 .unwrap_err()
4448 .root_cause()
4449 .downcast_ref::<KsError>()
4450 );
4451
4452 Ok(())
4453 }
4454
4455 // Creates a key migrates it to a different location and then tries to access it by the old
4456 // and new location.
4457 #[test]
4458 fn test_migrate_key_app_to_selinux() -> Result<()> {
4459 let mut db = new_test_db()?;
4460 const SOURCE_UID: u32 = 1u32;
4461 const DESTINATION_UID: u32 = 2u32;
4462 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004463 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4464 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004465 let key_id_guard =
4466 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4467 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4468
4469 let source_descriptor: KeyDescriptor = KeyDescriptor {
4470 domain: Domain::APP,
4471 nspace: -1,
4472 alias: Some(SOURCE_ALIAS.to_string()),
4473 blob: None,
4474 };
4475
4476 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4477 domain: Domain::SELINUX,
4478 nspace: DESTINATION_NAMESPACE,
4479 alias: Some(DESTINATION_ALIAS.to_string()),
4480 blob: None,
4481 };
4482
4483 let key_id = key_id_guard.id();
4484
4485 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4486 Ok(())
4487 })
4488 .unwrap();
4489
4490 let (_, key_entry) = db
4491 .load_key_entry(
4492 &destination_descriptor,
4493 KeyType::Client,
4494 KeyEntryLoadBits::BOTH,
4495 DESTINATION_UID,
4496 |k, av| {
4497 assert_eq!(Domain::SELINUX, k.domain);
4498 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4499 assert!(av.is_none());
4500 Ok(())
4501 },
4502 )
4503 .unwrap();
4504
4505 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4506
4507 assert_eq!(
4508 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4509 db.load_key_entry(
4510 &source_descriptor,
4511 KeyType::Client,
4512 KeyEntryLoadBits::NONE,
4513 SOURCE_UID,
4514 |_k, _av| Ok(()),
4515 )
4516 .unwrap_err()
4517 .root_cause()
4518 .downcast_ref::<KsError>()
4519 );
4520
4521 Ok(())
4522 }
4523
4524 // Creates two keys and tries to migrate the first to the location of the second which
4525 // is expected to fail.
4526 #[test]
4527 fn test_migrate_key_destination_occupied() -> Result<()> {
4528 let mut db = new_test_db()?;
4529 const SOURCE_UID: u32 = 1u32;
4530 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004531 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4532 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004533 let key_id_guard =
4534 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4535 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4536 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4537 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4538
4539 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4540 domain: Domain::APP,
4541 nspace: -1,
4542 alias: Some(DESTINATION_ALIAS.to_string()),
4543 blob: None,
4544 };
4545
4546 assert_eq!(
4547 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4548 db.migrate_key_namespace(
4549 key_id_guard,
4550 &destination_descriptor,
4551 DESTINATION_UID,
4552 |_k| Ok(())
4553 )
4554 .unwrap_err()
4555 .root_cause()
4556 .downcast_ref::<KsError>()
4557 );
4558
4559 Ok(())
4560 }
4561
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004562 #[test]
4563 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004564 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4565 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4566 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004567 const UID: u32 = 33;
4568 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4569 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4570 let key_id_untouched1 =
4571 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4572 let key_id_untouched2 =
4573 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4574 let key_id_deleted =
4575 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4576
4577 let (_, key_entry) = db
4578 .load_key_entry(
4579 &KeyDescriptor {
4580 domain: Domain::APP,
4581 nspace: -1,
4582 alias: Some(ALIAS1.to_string()),
4583 blob: None,
4584 },
4585 KeyType::Client,
4586 KeyEntryLoadBits::BOTH,
4587 UID,
4588 |k, av| {
4589 assert_eq!(Domain::APP, k.domain);
4590 assert_eq!(UID as i64, k.nspace);
4591 assert!(av.is_none());
4592 Ok(())
4593 },
4594 )
4595 .unwrap();
4596 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4597 let (_, key_entry) = db
4598 .load_key_entry(
4599 &KeyDescriptor {
4600 domain: Domain::APP,
4601 nspace: -1,
4602 alias: Some(ALIAS2.to_string()),
4603 blob: None,
4604 },
4605 KeyType::Client,
4606 KeyEntryLoadBits::BOTH,
4607 UID,
4608 |k, av| {
4609 assert_eq!(Domain::APP, k.domain);
4610 assert_eq!(UID as i64, k.nspace);
4611 assert!(av.is_none());
4612 Ok(())
4613 },
4614 )
4615 .unwrap();
4616 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4617 let (_, key_entry) = db
4618 .load_key_entry(
4619 &KeyDescriptor {
4620 domain: Domain::APP,
4621 nspace: -1,
4622 alias: Some(ALIAS3.to_string()),
4623 blob: None,
4624 },
4625 KeyType::Client,
4626 KeyEntryLoadBits::BOTH,
4627 UID,
4628 |k, av| {
4629 assert_eq!(Domain::APP, k.domain);
4630 assert_eq!(UID as i64, k.nspace);
4631 assert!(av.is_none());
4632 Ok(())
4633 },
4634 )
4635 .unwrap();
4636 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4637
4638 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4639 KeystoreDB::from_0_to_1(tx).no_gc()
4640 })
4641 .unwrap();
4642
4643 let (_, key_entry) = db
4644 .load_key_entry(
4645 &KeyDescriptor {
4646 domain: Domain::APP,
4647 nspace: -1,
4648 alias: Some(ALIAS1.to_string()),
4649 blob: None,
4650 },
4651 KeyType::Client,
4652 KeyEntryLoadBits::BOTH,
4653 UID,
4654 |k, av| {
4655 assert_eq!(Domain::APP, k.domain);
4656 assert_eq!(UID as i64, k.nspace);
4657 assert!(av.is_none());
4658 Ok(())
4659 },
4660 )
4661 .unwrap();
4662 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4663 let (_, key_entry) = db
4664 .load_key_entry(
4665 &KeyDescriptor {
4666 domain: Domain::APP,
4667 nspace: -1,
4668 alias: Some(ALIAS2.to_string()),
4669 blob: None,
4670 },
4671 KeyType::Client,
4672 KeyEntryLoadBits::BOTH,
4673 UID,
4674 |k, av| {
4675 assert_eq!(Domain::APP, k.domain);
4676 assert_eq!(UID as i64, k.nspace);
4677 assert!(av.is_none());
4678 Ok(())
4679 },
4680 )
4681 .unwrap();
4682 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4683 assert_eq!(
4684 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4685 db.load_key_entry(
4686 &KeyDescriptor {
4687 domain: Domain::APP,
4688 nspace: -1,
4689 alias: Some(ALIAS3.to_string()),
4690 blob: None,
4691 },
4692 KeyType::Client,
4693 KeyEntryLoadBits::BOTH,
4694 UID,
4695 |k, av| {
4696 assert_eq!(Domain::APP, k.domain);
4697 assert_eq!(UID as i64, k.nspace);
4698 assert!(av.is_none());
4699 Ok(())
4700 },
4701 )
4702 .unwrap_err()
4703 .root_cause()
4704 .downcast_ref::<KsError>()
4705 );
4706 }
4707
Janis Danisevskisaec14592020-11-12 09:41:49 -08004708 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4709
Janis Danisevskisaec14592020-11-12 09:41:49 -08004710 #[test]
4711 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4712 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004713 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4714 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004715 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004716 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004717 .context("test_insert_and_load_full_keyentry_domain_app")?
4718 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004719 let (_key_guard, key_entry) = db
4720 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004721 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004722 domain: Domain::APP,
4723 nspace: 0,
4724 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4725 blob: None,
4726 },
4727 KeyType::Client,
4728 KeyEntryLoadBits::BOTH,
4729 33,
4730 |_k, _av| Ok(()),
4731 )
4732 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004733 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004734 let state = Arc::new(AtomicU8::new(1));
4735 let state2 = state.clone();
4736
4737 // Spawning a second thread that attempts to acquire the key id lock
4738 // for the same key as the primary thread. The primary thread then
4739 // waits, thereby forcing the secondary thread into the second stage
4740 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4741 // The test succeeds if the secondary thread observes the transition
4742 // of `state` from 1 to 2, despite having a whole second to overtake
4743 // the primary thread.
4744 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004745 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004746 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004747 assert!(db
4748 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004749 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004750 domain: Domain::APP,
4751 nspace: 0,
4752 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4753 blob: None,
4754 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004755 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004756 KeyEntryLoadBits::BOTH,
4757 33,
4758 |_k, _av| Ok(()),
4759 )
4760 .is_ok());
4761 // We should only see a 2 here because we can only return
4762 // from load_key_entry when the `_key_guard` expires,
4763 // which happens at the end of the scope.
4764 assert_eq!(2, state2.load(Ordering::Relaxed));
4765 });
4766
4767 thread::sleep(std::time::Duration::from_millis(1000));
4768
4769 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4770
4771 // Return the handle from this scope so we can join with the
4772 // secondary thread after the key id lock has expired.
4773 handle
4774 // This is where the `_key_guard` goes out of scope,
4775 // which is the reason for concurrent load_key_entry on the same key
4776 // to unblock.
4777 };
4778 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4779 // main test thread. We will not see failing asserts in secondary threads otherwise.
4780 handle.join().unwrap();
4781 Ok(())
4782 }
4783
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004784 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004785 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004786 let temp_dir =
4787 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4788
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004789 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4790 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004791
4792 let _tx1 = db1
4793 .conn
4794 .transaction_with_behavior(TransactionBehavior::Immediate)
4795 .expect("Failed to create first transaction.");
4796
4797 let error = db2
4798 .conn
4799 .transaction_with_behavior(TransactionBehavior::Immediate)
4800 .context("Transaction begin failed.")
4801 .expect_err("This should fail.");
4802 let root_cause = error.root_cause();
4803 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4804 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4805 {
4806 return;
4807 }
4808 panic!(
4809 "Unexpected error {:?} \n{:?} \n{:?}",
4810 error,
4811 root_cause,
4812 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4813 )
4814 }
4815
4816 #[cfg(disabled)]
4817 #[test]
4818 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4819 let temp_dir = Arc::new(
4820 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4821 .expect("Failed to create temp dir."),
4822 );
4823
4824 let test_begin = Instant::now();
4825
Janis Danisevskis66784c42021-01-27 08:40:25 -08004826 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004827 let mut db =
4828 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004829 const OPEN_DB_COUNT: u32 = 50u32;
4830
4831 let mut actual_key_count = KEY_COUNT;
4832 // First insert KEY_COUNT keys.
4833 for count in 0..KEY_COUNT {
4834 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4835 actual_key_count = count;
4836 break;
4837 }
4838 let alias = format!("test_alias_{}", count);
4839 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4840 .expect("Failed to make key entry.");
4841 }
4842
4843 // Insert more keys from a different thread and into a different namespace.
4844 let temp_dir1 = temp_dir.clone();
4845 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004846 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4847 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004848
4849 for count in 0..actual_key_count {
4850 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4851 return;
4852 }
4853 let alias = format!("test_alias_{}", count);
4854 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4855 .expect("Failed to make key entry.");
4856 }
4857
4858 // then unbind them again.
4859 for count in 0..actual_key_count {
4860 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4861 return;
4862 }
4863 let key = KeyDescriptor {
4864 domain: Domain::APP,
4865 nspace: -1,
4866 alias: Some(format!("test_alias_{}", count)),
4867 blob: None,
4868 };
4869 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4870 }
4871 });
4872
4873 // And start unbinding the first set of keys.
4874 let temp_dir2 = temp_dir.clone();
4875 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004876 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4877 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004878
4879 for count in 0..actual_key_count {
4880 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4881 return;
4882 }
4883 let key = KeyDescriptor {
4884 domain: Domain::APP,
4885 nspace: -1,
4886 alias: Some(format!("test_alias_{}", count)),
4887 blob: None,
4888 };
4889 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4890 }
4891 });
4892
Janis Danisevskis66784c42021-01-27 08:40:25 -08004893 // While a lot of inserting and deleting is going on we have to open database connections
4894 // successfully and use them.
4895 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4896 // out of scope.
4897 #[allow(clippy::redundant_clone)]
4898 let temp_dir4 = temp_dir.clone();
4899 let handle4 = thread::spawn(move || {
4900 for count in 0..OPEN_DB_COUNT {
4901 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4902 return;
4903 }
Seth Moore444b51a2021-06-11 09:49:49 -07004904 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4905 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004906
4907 let alias = format!("test_alias_{}", count);
4908 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4909 .expect("Failed to make key entry.");
4910 let key = KeyDescriptor {
4911 domain: Domain::APP,
4912 nspace: -1,
4913 alias: Some(alias),
4914 blob: None,
4915 };
4916 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4917 }
4918 });
4919
4920 handle1.join().expect("Thread 1 panicked.");
4921 handle2.join().expect("Thread 2 panicked.");
4922 handle4.join().expect("Thread 4 panicked.");
4923
Janis Danisevskis66784c42021-01-27 08:40:25 -08004924 Ok(())
4925 }
4926
4927 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004928 fn list() -> Result<()> {
4929 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004930 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004931 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4932 (Domain::APP, 1, "test1"),
4933 (Domain::APP, 1, "test2"),
4934 (Domain::APP, 1, "test3"),
4935 (Domain::APP, 1, "test4"),
4936 (Domain::APP, 1, "test5"),
4937 (Domain::APP, 1, "test6"),
4938 (Domain::APP, 1, "test7"),
4939 (Domain::APP, 2, "test1"),
4940 (Domain::APP, 2, "test2"),
4941 (Domain::APP, 2, "test3"),
4942 (Domain::APP, 2, "test4"),
4943 (Domain::APP, 2, "test5"),
4944 (Domain::APP, 2, "test6"),
4945 (Domain::APP, 2, "test8"),
4946 (Domain::SELINUX, 100, "test1"),
4947 (Domain::SELINUX, 100, "test2"),
4948 (Domain::SELINUX, 100, "test3"),
4949 (Domain::SELINUX, 100, "test4"),
4950 (Domain::SELINUX, 100, "test5"),
4951 (Domain::SELINUX, 100, "test6"),
4952 (Domain::SELINUX, 100, "test9"),
4953 ];
4954
4955 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4956 .iter()
4957 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004958 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4959 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004960 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4961 });
4962 (entry.id(), *ns)
4963 })
4964 .collect();
4965
4966 for (domain, namespace) in
4967 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4968 {
4969 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4970 .iter()
4971 .filter_map(|(domain, ns, alias)| match ns {
4972 ns if *ns == *namespace => Some(KeyDescriptor {
4973 domain: *domain,
4974 nspace: *ns,
4975 alias: Some(alias.to_string()),
4976 blob: None,
4977 }),
4978 _ => None,
4979 })
4980 .collect();
4981 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07004982 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004983 list_result.sort();
4984 assert_eq!(list_o_descriptors, list_result);
4985
4986 let mut list_o_ids: Vec<i64> = list_o_descriptors
4987 .into_iter()
4988 .map(|d| {
4989 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004990 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004991 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004992 KeyType::Client,
4993 KeyEntryLoadBits::NONE,
4994 *namespace as u32,
4995 |_, _| Ok(()),
4996 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004997 .unwrap();
4998 entry.id()
4999 })
5000 .collect();
5001 list_o_ids.sort_unstable();
5002 let mut loaded_entries: Vec<i64> = list_o_keys
5003 .iter()
5004 .filter_map(|(id, ns)| match ns {
5005 ns if *ns == *namespace => Some(*id),
5006 _ => None,
5007 })
5008 .collect();
5009 loaded_entries.sort_unstable();
5010 assert_eq!(list_o_ids, loaded_entries);
5011 }
Janis Danisevskis18313832021-05-17 13:30:32 -07005012 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08005013
5014 Ok(())
5015 }
5016
Joel Galenson0891bc12020-07-20 10:37:03 -07005017 // Helpers
5018
5019 // Checks that the given result is an error containing the given string.
5020 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
5021 let error_str = format!(
5022 "{:#?}",
5023 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
5024 );
5025 assert!(
5026 error_str.contains(target),
5027 "The string \"{}\" should contain \"{}\"",
5028 error_str,
5029 target
5030 );
5031 }
5032
Joel Galenson2aab4432020-07-22 15:27:57 -07005033 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07005034 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005035 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005036 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005037 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005038 namespace: Option<i64>,
5039 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005040 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08005041 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07005042 }
5043
5044 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
5045 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07005046 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07005047 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07005048 Ok(KeyEntryRow {
5049 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005050 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07005051 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07005052 namespace: row.get(3)?,
5053 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005054 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08005055 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07005056 })
5057 })?
5058 .map(|r| r.context("Could not read keyentry row."))
5059 .collect::<Result<Vec<_>>>()
5060 }
5061
Max Biresb2e1d032021-02-08 21:35:05 -08005062 struct RemoteProvValues {
5063 cert_chain: Vec<u8>,
5064 priv_key: Vec<u8>,
5065 batch_cert: Vec<u8>,
5066 }
5067
Max Bires2b2e6562020-09-22 11:22:36 -07005068 fn load_attestation_key_pool(
5069 db: &mut KeystoreDB,
5070 expiration_date: i64,
5071 namespace: i64,
5072 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08005073 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07005074 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
5075 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
5076 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5077 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005078 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005079 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5080 db.store_signed_attestation_certificate_chain(
5081 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005082 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005083 &cert_chain,
5084 expiration_date,
5085 &KEYSTORE_UUID,
5086 )?;
5087 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005088 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005089 }
5090
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005091 // Note: The parameters and SecurityLevel associations are nonsensical. This
5092 // collection is only used to check if the parameters are preserved as expected by the
5093 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005094 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5095 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005096 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5097 KeyParameter::new(
5098 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5099 SecurityLevel::TRUSTED_ENVIRONMENT,
5100 ),
5101 KeyParameter::new(
5102 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5103 SecurityLevel::TRUSTED_ENVIRONMENT,
5104 ),
5105 KeyParameter::new(
5106 KeyParameterValue::Algorithm(Algorithm::RSA),
5107 SecurityLevel::TRUSTED_ENVIRONMENT,
5108 ),
5109 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5110 KeyParameter::new(
5111 KeyParameterValue::BlockMode(BlockMode::ECB),
5112 SecurityLevel::TRUSTED_ENVIRONMENT,
5113 ),
5114 KeyParameter::new(
5115 KeyParameterValue::BlockMode(BlockMode::GCM),
5116 SecurityLevel::TRUSTED_ENVIRONMENT,
5117 ),
5118 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5119 KeyParameter::new(
5120 KeyParameterValue::Digest(Digest::MD5),
5121 SecurityLevel::TRUSTED_ENVIRONMENT,
5122 ),
5123 KeyParameter::new(
5124 KeyParameterValue::Digest(Digest::SHA_2_224),
5125 SecurityLevel::TRUSTED_ENVIRONMENT,
5126 ),
5127 KeyParameter::new(
5128 KeyParameterValue::Digest(Digest::SHA_2_256),
5129 SecurityLevel::STRONGBOX,
5130 ),
5131 KeyParameter::new(
5132 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5133 SecurityLevel::TRUSTED_ENVIRONMENT,
5134 ),
5135 KeyParameter::new(
5136 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5137 SecurityLevel::TRUSTED_ENVIRONMENT,
5138 ),
5139 KeyParameter::new(
5140 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5141 SecurityLevel::STRONGBOX,
5142 ),
5143 KeyParameter::new(
5144 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5145 SecurityLevel::TRUSTED_ENVIRONMENT,
5146 ),
5147 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5148 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5149 KeyParameter::new(
5150 KeyParameterValue::EcCurve(EcCurve::P_224),
5151 SecurityLevel::TRUSTED_ENVIRONMENT,
5152 ),
5153 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5154 KeyParameter::new(
5155 KeyParameterValue::EcCurve(EcCurve::P_384),
5156 SecurityLevel::TRUSTED_ENVIRONMENT,
5157 ),
5158 KeyParameter::new(
5159 KeyParameterValue::EcCurve(EcCurve::P_521),
5160 SecurityLevel::TRUSTED_ENVIRONMENT,
5161 ),
5162 KeyParameter::new(
5163 KeyParameterValue::RSAPublicExponent(3),
5164 SecurityLevel::TRUSTED_ENVIRONMENT,
5165 ),
5166 KeyParameter::new(
5167 KeyParameterValue::IncludeUniqueID,
5168 SecurityLevel::TRUSTED_ENVIRONMENT,
5169 ),
5170 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5171 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5172 KeyParameter::new(
5173 KeyParameterValue::ActiveDateTime(1234567890),
5174 SecurityLevel::STRONGBOX,
5175 ),
5176 KeyParameter::new(
5177 KeyParameterValue::OriginationExpireDateTime(1234567890),
5178 SecurityLevel::TRUSTED_ENVIRONMENT,
5179 ),
5180 KeyParameter::new(
5181 KeyParameterValue::UsageExpireDateTime(1234567890),
5182 SecurityLevel::TRUSTED_ENVIRONMENT,
5183 ),
5184 KeyParameter::new(
5185 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5186 SecurityLevel::TRUSTED_ENVIRONMENT,
5187 ),
5188 KeyParameter::new(
5189 KeyParameterValue::MaxUsesPerBoot(1234567890),
5190 SecurityLevel::TRUSTED_ENVIRONMENT,
5191 ),
5192 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5193 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5194 KeyParameter::new(
5195 KeyParameterValue::NoAuthRequired,
5196 SecurityLevel::TRUSTED_ENVIRONMENT,
5197 ),
5198 KeyParameter::new(
5199 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5200 SecurityLevel::TRUSTED_ENVIRONMENT,
5201 ),
5202 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5203 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5204 KeyParameter::new(
5205 KeyParameterValue::TrustedUserPresenceRequired,
5206 SecurityLevel::TRUSTED_ENVIRONMENT,
5207 ),
5208 KeyParameter::new(
5209 KeyParameterValue::TrustedConfirmationRequired,
5210 SecurityLevel::TRUSTED_ENVIRONMENT,
5211 ),
5212 KeyParameter::new(
5213 KeyParameterValue::UnlockedDeviceRequired,
5214 SecurityLevel::TRUSTED_ENVIRONMENT,
5215 ),
5216 KeyParameter::new(
5217 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5218 SecurityLevel::SOFTWARE,
5219 ),
5220 KeyParameter::new(
5221 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5222 SecurityLevel::SOFTWARE,
5223 ),
5224 KeyParameter::new(
5225 KeyParameterValue::CreationDateTime(12345677890),
5226 SecurityLevel::SOFTWARE,
5227 ),
5228 KeyParameter::new(
5229 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5230 SecurityLevel::TRUSTED_ENVIRONMENT,
5231 ),
5232 KeyParameter::new(
5233 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5234 SecurityLevel::TRUSTED_ENVIRONMENT,
5235 ),
5236 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5237 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5238 KeyParameter::new(
5239 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5240 SecurityLevel::SOFTWARE,
5241 ),
5242 KeyParameter::new(
5243 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5244 SecurityLevel::TRUSTED_ENVIRONMENT,
5245 ),
5246 KeyParameter::new(
5247 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5248 SecurityLevel::TRUSTED_ENVIRONMENT,
5249 ),
5250 KeyParameter::new(
5251 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5252 SecurityLevel::TRUSTED_ENVIRONMENT,
5253 ),
5254 KeyParameter::new(
5255 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5256 SecurityLevel::TRUSTED_ENVIRONMENT,
5257 ),
5258 KeyParameter::new(
5259 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5260 SecurityLevel::TRUSTED_ENVIRONMENT,
5261 ),
5262 KeyParameter::new(
5263 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5264 SecurityLevel::TRUSTED_ENVIRONMENT,
5265 ),
5266 KeyParameter::new(
5267 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5268 SecurityLevel::TRUSTED_ENVIRONMENT,
5269 ),
5270 KeyParameter::new(
5271 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5272 SecurityLevel::TRUSTED_ENVIRONMENT,
5273 ),
5274 KeyParameter::new(
5275 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5276 SecurityLevel::TRUSTED_ENVIRONMENT,
5277 ),
5278 KeyParameter::new(
5279 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5280 SecurityLevel::TRUSTED_ENVIRONMENT,
5281 ),
5282 KeyParameter::new(
5283 KeyParameterValue::VendorPatchLevel(3),
5284 SecurityLevel::TRUSTED_ENVIRONMENT,
5285 ),
5286 KeyParameter::new(
5287 KeyParameterValue::BootPatchLevel(4),
5288 SecurityLevel::TRUSTED_ENVIRONMENT,
5289 ),
5290 KeyParameter::new(
5291 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5292 SecurityLevel::TRUSTED_ENVIRONMENT,
5293 ),
5294 KeyParameter::new(
5295 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5296 SecurityLevel::TRUSTED_ENVIRONMENT,
5297 ),
5298 KeyParameter::new(
5299 KeyParameterValue::MacLength(256),
5300 SecurityLevel::TRUSTED_ENVIRONMENT,
5301 ),
5302 KeyParameter::new(
5303 KeyParameterValue::ResetSinceIdRotation,
5304 SecurityLevel::TRUSTED_ENVIRONMENT,
5305 ),
5306 KeyParameter::new(
5307 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5308 SecurityLevel::TRUSTED_ENVIRONMENT,
5309 ),
Qi Wub9433b52020-12-01 14:52:46 +08005310 ];
5311 if let Some(value) = max_usage_count {
5312 params.push(KeyParameter::new(
5313 KeyParameterValue::UsageCountLimit(value),
5314 SecurityLevel::SOFTWARE,
5315 ));
5316 }
5317 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005318 }
5319
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005320 fn make_test_key_entry(
5321 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005322 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005323 namespace: i64,
5324 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005325 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005326 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005327 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005328 let mut blob_metadata = BlobMetaData::new();
5329 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5330 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5331 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5332 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5333 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5334
5335 db.set_blob(
5336 &key_id,
5337 SubComponentType::KEY_BLOB,
5338 Some(TEST_KEY_BLOB),
5339 Some(&blob_metadata),
5340 )?;
5341 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5342 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005343
5344 let params = make_test_params(max_usage_count);
5345 db.insert_keyparameter(&key_id, &params)?;
5346
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005347 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005348 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005349 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005350 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005351 Ok(key_id)
5352 }
5353
Qi Wub9433b52020-12-01 14:52:46 +08005354 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5355 let params = make_test_params(max_usage_count);
5356
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005357 let mut blob_metadata = BlobMetaData::new();
5358 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5359 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5360 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5361 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5362 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5363
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005364 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005365 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005366
5367 KeyEntry {
5368 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005369 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005370 cert: Some(TEST_CERT_BLOB.to_vec()),
5371 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005372 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005373 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005374 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005375 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005376 }
5377 }
5378
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005379 fn make_bootlevel_key_entry(
5380 db: &mut KeystoreDB,
5381 domain: Domain,
5382 namespace: i64,
5383 alias: &str,
5384 logical_only: bool,
5385 ) -> Result<KeyIdGuard> {
5386 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5387 let mut blob_metadata = BlobMetaData::new();
5388 if !logical_only {
5389 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5390 }
5391 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5392
5393 db.set_blob(
5394 &key_id,
5395 SubComponentType::KEY_BLOB,
5396 Some(TEST_KEY_BLOB),
5397 Some(&blob_metadata),
5398 )?;
5399 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5400 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5401
5402 let mut params = make_test_params(None);
5403 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5404
5405 db.insert_keyparameter(&key_id, &params)?;
5406
5407 let mut metadata = KeyMetaData::new();
5408 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5409 db.insert_key_metadata(&key_id, &metadata)?;
5410 rebind_alias(db, &key_id, alias, domain, namespace)?;
5411 Ok(key_id)
5412 }
5413
5414 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5415 let mut params = make_test_params(None);
5416 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5417
5418 let mut blob_metadata = BlobMetaData::new();
5419 if !logical_only {
5420 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5421 }
5422 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5423
5424 let mut metadata = KeyMetaData::new();
5425 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5426
5427 KeyEntry {
5428 id: key_id,
5429 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5430 cert: Some(TEST_CERT_BLOB.to_vec()),
5431 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5432 km_uuid: KEYSTORE_UUID,
5433 parameters: params,
5434 metadata,
5435 pure_cert: false,
5436 }
5437 }
5438
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005439 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005440 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005441 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005442 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005443 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005444 NO_PARAMS,
5445 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005446 Ok((
5447 row.get(0)?,
5448 row.get(1)?,
5449 row.get(2)?,
5450 row.get(3)?,
5451 row.get(4)?,
5452 row.get(5)?,
5453 row.get(6)?,
5454 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005455 },
5456 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005457
5458 println!("Key entry table rows:");
5459 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005460 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005461 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005462 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5463 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005464 );
5465 }
5466 Ok(())
5467 }
5468
5469 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005470 let mut stmt = db
5471 .conn
5472 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005473 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5474 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5475 })?;
5476
5477 println!("Grant table rows:");
5478 for r in rows {
5479 let (id, gt, ki, av) = r.unwrap();
5480 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5481 }
5482 Ok(())
5483 }
5484
Joel Galenson0891bc12020-07-20 10:37:03 -07005485 // Use a custom random number generator that repeats each number once.
5486 // This allows us to test repeated elements.
5487
5488 thread_local! {
5489 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5490 }
5491
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005492 fn reset_random() {
5493 RANDOM_COUNTER.with(|counter| {
5494 *counter.borrow_mut() = 0;
5495 })
5496 }
5497
Joel Galenson0891bc12020-07-20 10:37:03 -07005498 pub fn random() -> i64 {
5499 RANDOM_COUNTER.with(|counter| {
5500 let result = *counter.borrow() / 2;
5501 *counter.borrow_mut() += 1;
5502 result
5503 })
5504 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005505
5506 #[test]
5507 fn test_last_off_body() -> Result<()> {
5508 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005509 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005510 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005511 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005512 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005513 let one_second = Duration::from_secs(1);
5514 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005515 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005516 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005517 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005518 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005519 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005520 Ok(())
5521 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005522
5523 #[test]
5524 fn test_unbind_keys_for_user() -> Result<()> {
5525 let mut db = new_test_db()?;
5526 db.unbind_keys_for_user(1, false)?;
5527
5528 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5529 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5530 db.unbind_keys_for_user(2, false)?;
5531
Janis Danisevskis18313832021-05-17 13:30:32 -07005532 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5533 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005534
5535 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005536 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005537
5538 Ok(())
5539 }
5540
5541 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005542 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5543 let mut db = new_test_db()?;
5544 let super_key = keystore2_crypto::generate_aes256_key()?;
5545 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5546 let (encrypted_super_key, metadata) =
5547 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5548
5549 let key_name_enc = SuperKeyType {
5550 alias: "test_super_key_1",
5551 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5552 };
5553
5554 let key_name_nonenc = SuperKeyType {
5555 alias: "test_super_key_2",
5556 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5557 };
5558
5559 // Install two super keys.
5560 db.store_super_key(
5561 1,
5562 &key_name_nonenc,
5563 &super_key,
5564 &BlobMetaData::new(),
5565 &KeyMetaData::new(),
5566 )?;
5567 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5568
5569 // Check that both can be found in the database.
5570 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5571 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5572
5573 // Install the same keys for a different user.
5574 db.store_super_key(
5575 2,
5576 &key_name_nonenc,
5577 &super_key,
5578 &BlobMetaData::new(),
5579 &KeyMetaData::new(),
5580 )?;
5581 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5582
5583 // Check that the second pair of keys can be found in the database.
5584 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5585 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5586
5587 // Delete only encrypted keys.
5588 db.unbind_keys_for_user(1, true)?;
5589
5590 // The encrypted superkey should be gone now.
5591 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5592 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5593
5594 // Reinsert the encrypted key.
5595 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5596
5597 // Check that both can be found in the database, again..
5598 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5599 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5600
5601 // Delete all even unencrypted keys.
5602 db.unbind_keys_for_user(1, false)?;
5603
5604 // Both should be gone now.
5605 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5606 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5607
5608 // Check that the second pair of keys was untouched.
5609 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5610 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5611
5612 Ok(())
5613 }
5614
5615 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005616 fn test_store_super_key() -> Result<()> {
5617 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005618 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005619 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005620 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005621 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005622 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005623
5624 let (encrypted_super_key, metadata) =
5625 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005626 db.store_super_key(
5627 1,
5628 &USER_SUPER_KEY,
5629 &encrypted_super_key,
5630 &metadata,
5631 &KeyMetaData::new(),
5632 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005633
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005634 // Check if super key exists.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005635 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005636
Paul Crowley7a658392021-03-18 17:08:20 -07005637 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005638 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5639 USER_SUPER_KEY.algorithm,
5640 key_entry,
5641 &pw,
5642 None,
5643 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005644
Janis Danisevskisf84d0b02022-01-26 14:11:14 -08005645 let decrypted_secret_bytes = loaded_super_key.decrypt(&encrypted_secret, &iv, &tag)?;
Paul Crowley7a658392021-03-18 17:08:20 -07005646 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005647
Hasini Gunasingheda895552021-01-27 19:34:37 +00005648 Ok(())
5649 }
Seth Moore78c091f2021-04-09 21:38:30 +00005650
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005651 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005652 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005653 MetricsStorage::KEY_ENTRY,
5654 MetricsStorage::KEY_ENTRY_ID_INDEX,
5655 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5656 MetricsStorage::BLOB_ENTRY,
5657 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5658 MetricsStorage::KEY_PARAMETER,
5659 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5660 MetricsStorage::KEY_METADATA,
5661 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5662 MetricsStorage::GRANT,
5663 MetricsStorage::AUTH_TOKEN,
5664 MetricsStorage::BLOB_METADATA,
5665 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005666 ]
5667 }
5668
5669 /// Perform a simple check to ensure that we can query all the storage types
5670 /// that are supported by the DB. Check for reasonable values.
5671 #[test]
5672 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005673 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005674
5675 let mut db = new_test_db()?;
5676
5677 for t in get_valid_statsd_storage_types() {
5678 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005679 // AuthToken can be less than a page since it's in a btree, not sqlite
5680 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005681 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005682 } else {
5683 assert!(stat.size >= PAGE_SIZE);
5684 }
Seth Moore78c091f2021-04-09 21:38:30 +00005685 assert!(stat.size >= stat.unused_size);
5686 }
5687
5688 Ok(())
5689 }
5690
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005691 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005692 get_valid_statsd_storage_types()
5693 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005694 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005695 .collect()
5696 }
5697
5698 fn assert_storage_increased(
5699 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005700 increased_storage_types: Vec<MetricsStorage>,
5701 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005702 ) {
5703 for storage in increased_storage_types {
5704 // Verify the expected storage increased.
5705 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005706 let storage = storage;
5707 let old = &baseline[&storage.0];
5708 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005709 assert!(
5710 new.unused_size <= old.unused_size,
5711 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005712 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005713 new.unused_size,
5714 old.unused_size
5715 );
5716
5717 // Update the baseline with the new value so that it succeeds in the
5718 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005719 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005720 }
5721
5722 // Get an updated map of the storage and verify there were no unexpected changes.
5723 let updated_stats = get_storage_stats_map(db);
5724 assert_eq!(updated_stats.len(), baseline.len());
5725
5726 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005727 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005728 let mut s = String::new();
5729 for &k in map.keys() {
5730 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5731 .expect("string concat failed");
5732 }
5733 s
5734 };
5735
5736 assert!(
5737 updated_stats[&k].size == baseline[&k].size
5738 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5739 "updated_stats:\n{}\nbaseline:\n{}",
5740 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005741 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005742 );
5743 }
5744 }
5745
5746 #[test]
5747 fn test_verify_key_table_size_reporting() -> Result<()> {
5748 let mut db = new_test_db()?;
5749 let mut working_stats = get_storage_stats_map(&mut db);
5750
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005751 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005752 assert_storage_increased(
5753 &mut db,
5754 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005755 MetricsStorage::KEY_ENTRY,
5756 MetricsStorage::KEY_ENTRY_ID_INDEX,
5757 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005758 ],
5759 &mut working_stats,
5760 );
5761
5762 let mut blob_metadata = BlobMetaData::new();
5763 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5764 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5765 assert_storage_increased(
5766 &mut db,
5767 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005768 MetricsStorage::BLOB_ENTRY,
5769 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5770 MetricsStorage::BLOB_METADATA,
5771 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005772 ],
5773 &mut working_stats,
5774 );
5775
5776 let params = make_test_params(None);
5777 db.insert_keyparameter(&key_id, &params)?;
5778 assert_storage_increased(
5779 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005780 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005781 &mut working_stats,
5782 );
5783
5784 let mut metadata = KeyMetaData::new();
5785 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5786 db.insert_key_metadata(&key_id, &metadata)?;
5787 assert_storage_increased(
5788 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005789 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005790 &mut working_stats,
5791 );
5792
5793 let mut sum = 0;
5794 for stat in working_stats.values() {
5795 sum += stat.size;
5796 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005797 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005798 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5799
5800 Ok(())
5801 }
5802
5803 #[test]
5804 fn test_verify_auth_table_size_reporting() -> Result<()> {
5805 let mut db = new_test_db()?;
5806 let mut working_stats = get_storage_stats_map(&mut db);
5807 db.insert_auth_token(&HardwareAuthToken {
5808 challenge: 123,
5809 userId: 456,
5810 authenticatorId: 789,
5811 authenticatorType: kmhw_authenticator_type::ANY,
5812 timestamp: Timestamp { milliSeconds: 10 },
5813 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005814 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005815 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005816 Ok(())
5817 }
5818
5819 #[test]
5820 fn test_verify_grant_table_size_reporting() -> Result<()> {
5821 const OWNER: i64 = 1;
5822 let mut db = new_test_db()?;
5823 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5824
5825 let mut working_stats = get_storage_stats_map(&mut db);
5826 db.grant(
5827 &KeyDescriptor {
5828 domain: Domain::APP,
5829 nspace: 0,
5830 alias: Some(TEST_ALIAS.to_string()),
5831 blob: None,
5832 },
5833 OWNER as u32,
5834 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005835 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005836 |_, _| Ok(()),
5837 )?;
5838
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005839 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005840
5841 Ok(())
5842 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005843
5844 #[test]
5845 fn find_auth_token_entry_returns_latest() -> Result<()> {
5846 let mut db = new_test_db()?;
5847 db.insert_auth_token(&HardwareAuthToken {
5848 challenge: 123,
5849 userId: 456,
5850 authenticatorId: 789,
5851 authenticatorType: kmhw_authenticator_type::ANY,
5852 timestamp: Timestamp { milliSeconds: 10 },
5853 mac: b"mac0".to_vec(),
5854 });
5855 std::thread::sleep(std::time::Duration::from_millis(1));
5856 db.insert_auth_token(&HardwareAuthToken {
5857 challenge: 123,
5858 userId: 457,
5859 authenticatorId: 789,
5860 authenticatorType: kmhw_authenticator_type::ANY,
5861 timestamp: Timestamp { milliSeconds: 12 },
5862 mac: b"mac1".to_vec(),
5863 });
5864 std::thread::sleep(std::time::Duration::from_millis(1));
5865 db.insert_auth_token(&HardwareAuthToken {
5866 challenge: 123,
5867 userId: 458,
5868 authenticatorId: 789,
5869 authenticatorType: kmhw_authenticator_type::ANY,
5870 timestamp: Timestamp { milliSeconds: 3 },
5871 mac: b"mac2".to_vec(),
5872 });
5873 // All three entries are in the database
5874 assert_eq!(db.perboot.auth_tokens_len(), 3);
5875 // It selected the most recent timestamp
5876 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5877 Ok(())
5878 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005879
5880 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005881 fn test_load_key_descriptor() -> Result<()> {
5882 let mut db = new_test_db()?;
5883 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5884
5885 let key = db.load_key_descriptor(key_id)?.unwrap();
5886
5887 assert_eq!(key.domain, Domain::APP);
5888 assert_eq!(key.nspace, 1);
5889 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5890
5891 // No such id
5892 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5893 Ok(())
5894 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005895}