blob: 133a926f68bdc2835e412bf614424fe2d5bfae94 [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
581impl CertificateInfo {
582 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
583 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
584 Self { cert, cert_chain }
585 }
586
587 /// Take the cert
588 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
589 self.cert.take()
590 }
591
592 /// Take the cert chain
593 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
594 self.cert_chain.take()
595 }
596}
597
Max Bires2b2e6562020-09-22 11:22:36 -0700598/// This type represents a certificate chain with a private key corresponding to the leaf
599/// 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 -0700600pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800601 /// A KM key blob
602 pub private_key: ZVec,
603 /// A batch cert for private_key
604 pub batch_cert: Vec<u8>,
605 /// A full certificate chain from root signing authority to private_key, including batch_cert
606 /// for convenience.
607 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700608}
609
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700610/// This type represents a Keystore 2.0 key entry.
611/// An entry has a unique `id` by which it can be found in the database.
612/// It has a security level field, key parameters, and three optional fields
613/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800614#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615pub struct KeyEntry {
616 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800617 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700618 cert: Option<Vec<u8>>,
619 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800620 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700621 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800622 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800623 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700624}
625
626impl KeyEntry {
627 /// Returns the unique id of the Key entry.
628 pub fn id(&self) -> i64 {
629 self.id
630 }
631 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
633 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700634 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800635 /// Extracts the Optional KeyMint blob including its metadata.
636 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
637 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700638 }
639 /// Exposes the optional public certificate.
640 pub fn cert(&self) -> &Option<Vec<u8>> {
641 &self.cert
642 }
643 /// Extracts the optional public certificate.
644 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
645 self.cert.take()
646 }
647 /// Exposes the optional public certificate chain.
648 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
649 &self.cert_chain
650 }
651 /// Extracts the optional public certificate_chain.
652 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
653 self.cert_chain.take()
654 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800655 /// Returns the uuid of the owning KeyMint instance.
656 pub fn km_uuid(&self) -> &Uuid {
657 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700658 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700659 /// Exposes the key parameters of this key entry.
660 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
661 &self.parameters
662 }
663 /// Consumes this key entry and extracts the keyparameters from it.
664 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
665 self.parameters
666 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800667 /// Exposes the key metadata of this key entry.
668 pub fn metadata(&self) -> &KeyMetaData {
669 &self.metadata
670 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800671 /// This returns true if the entry is a pure certificate entry with no
672 /// private key component.
673 pub fn pure_cert(&self) -> bool {
674 self.pure_cert
675 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000676 /// Consumes this key entry and extracts the keyparameters and metadata from it.
677 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
678 (self.parameters, self.metadata)
679 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700680}
681
682/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800683#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700684pub struct SubComponentType(u32);
685impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800686 /// Persistent identifier for a key blob.
687 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700688 /// Persistent identifier for a certificate blob.
689 pub const CERT: SubComponentType = Self(1);
690 /// Persistent identifier for a certificate chain blob.
691 pub const CERT_CHAIN: SubComponentType = Self(2);
692}
693
694impl ToSql for SubComponentType {
695 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
696 self.0.to_sql()
697 }
698}
699
700impl FromSql for SubComponentType {
701 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
702 Ok(Self(u32::column_result(value)?))
703 }
704}
705
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800706/// This trait is private to the database module. It is used to convey whether or not the garbage
707/// collector shall be invoked after a database access. All closures passed to
708/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
709/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
710/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
711/// `.need_gc()`.
712trait DoGc<T> {
713 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
714
715 fn no_gc(self) -> Result<(bool, T)>;
716
717 fn need_gc(self) -> Result<(bool, T)>;
718}
719
720impl<T> DoGc<T> for Result<T> {
721 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
722 self.map(|r| (need_gc, r))
723 }
724
725 fn no_gc(self) -> Result<(bool, T)> {
726 self.do_gc(false)
727 }
728
729 fn need_gc(self) -> Result<(bool, T)> {
730 self.do_gc(true)
731 }
732}
733
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700734/// KeystoreDB wraps a connection to an SQLite database and tracks its
735/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700736pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700737 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700738 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700739 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700740}
741
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000742/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000743/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000744#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
745pub struct MonotonicRawTime(i64);
746
747impl MonotonicRawTime {
748 /// Constructs a new MonotonicRawTime
749 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000750 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000751 }
752
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000753 /// Returns the value of MonotonicRawTime in milliseconds as i64
754 pub fn milliseconds(&self) -> i64 {
755 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000756 }
757
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000758 /// Returns the integer value of MonotonicRawTime as i64
759 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000760 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000761 }
762
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800763 /// Like i64::checked_sub.
764 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
765 self.0.checked_sub(other.0).map(Self)
766 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000767}
768
769impl ToSql for MonotonicRawTime {
770 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
771 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
772 }
773}
774
775impl FromSql for MonotonicRawTime {
776 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
777 Ok(Self(i64::column_result(value)?))
778 }
779}
780
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000781/// This struct encapsulates the information to be stored in the database about the auth tokens
782/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700783#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000784pub struct AuthTokenEntry {
785 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000786 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000787 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000788}
789
790impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000791 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000792 AuthTokenEntry { auth_token, time_received }
793 }
794
795 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800796 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800798 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
799 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 })
801 }
802
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000803 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800804 pub fn auth_token(&self) -> &HardwareAuthToken {
805 &self.auth_token
806 }
807
808 /// Returns the auth token wrapped by the AuthTokenEntry
809 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000810 self.auth_token
811 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800812
813 /// Returns the time that this auth token was received.
814 pub fn time_received(&self) -> MonotonicRawTime {
815 self.time_received
816 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000817
818 /// Returns the challenge value of the auth token.
819 pub fn challenge(&self) -> i64 {
820 self.auth_token.challenge
821 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000822}
823
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800824/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
825/// This object does not allow access to the database connection. But it keeps a database
826/// connection alive in order to keep the in memory per boot database alive.
827pub struct PerBootDbKeepAlive(Connection);
828
Joel Galenson26f4d012020-07-17 14:57:21 -0700829impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800830 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700831 const CURRENT_DB_VERSION: u32 = 1;
832 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800833
Seth Moore78c091f2021-04-09 21:38:30 +0000834 /// Name of the file that holds the cross-boot persistent database.
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700835 pub const PERSISTENT_DB_FILENAME: &'static str = "persistent.sqlite";
Seth Moore78c091f2021-04-09 21:38:30 +0000836
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700837 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800838 /// files persistent.sqlite and perboot.sqlite in the given directory.
839 /// It also attempts to initialize all of the tables.
840 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700841 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700842 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700843 let _wp = wd::watch_millis("KeystoreDB::new", 500);
844
Chris Wailesd5aaaef2021-07-27 16:04:33 -0700845 let persistent_path = Self::make_persistent_path(db_root)?;
Seth Moore472fcbb2021-05-12 10:07:51 -0700846 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800847
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700848 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800849 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700850 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
851 .context("In KeystoreDB::new: trying to upgrade database.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800852 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800853 })?;
854 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700855 }
856
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700857 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
858 // cryptographic binding to the boot level keys was implemented.
859 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
860 tx.execute(
861 "UPDATE persistent.keyentry SET state = ?
862 WHERE
863 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
864 AND
865 id NOT IN (
866 SELECT keyentryid FROM persistent.blobentry
867 WHERE id IN (
868 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
869 )
870 );",
871 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
872 )
873 .context("In from_0_to_1: Failed to delete logical boot level keys.")?;
874 Ok(1)
875 }
876
Janis Danisevskis66784c42021-01-27 08:40:25 -0800877 fn init_tables(tx: &Transaction) -> Result<()> {
878 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700879 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700880 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800881 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700882 domain INTEGER,
883 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800884 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800885 state INTEGER,
886 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700887 NO_PARAMS,
888 )
889 .context("Failed to initialize \"keyentry\" table.")?;
890
Janis Danisevskis66784c42021-01-27 08:40:25 -0800891 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800892 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
893 ON keyentry(id);",
894 NO_PARAMS,
895 )
896 .context("Failed to create index keyentry_id_index.")?;
897
898 tx.execute(
899 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
900 ON keyentry(domain, namespace, alias);",
901 NO_PARAMS,
902 )
903 .context("Failed to create index keyentry_domain_namespace_index.")?;
904
905 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700906 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
907 id INTEGER PRIMARY KEY,
908 subcomponent_type INTEGER,
909 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800910 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700911 NO_PARAMS,
912 )
913 .context("Failed to initialize \"blobentry\" table.")?;
914
Janis Danisevskis66784c42021-01-27 08:40:25 -0800915 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800916 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
917 ON blobentry(keyentryid);",
918 NO_PARAMS,
919 )
920 .context("Failed to create index blobentry_keyentryid_index.")?;
921
922 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800923 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
924 id INTEGER PRIMARY KEY,
925 blobentryid INTEGER,
926 tag INTEGER,
927 data ANY,
928 UNIQUE (blobentryid, tag));",
929 NO_PARAMS,
930 )
931 .context("Failed to initialize \"blobmetadata\" table.")?;
932
933 tx.execute(
934 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
935 ON blobmetadata(blobentryid);",
936 NO_PARAMS,
937 )
938 .context("Failed to create index blobmetadata_blobentryid_index.")?;
939
940 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700941 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000942 keyentryid INTEGER,
943 tag INTEGER,
944 data ANY,
945 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700946 NO_PARAMS,
947 )
948 .context("Failed to initialize \"keyparameter\" table.")?;
949
Janis Danisevskis66784c42021-01-27 08:40:25 -0800950 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800951 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
952 ON keyparameter(keyentryid);",
953 NO_PARAMS,
954 )
955 .context("Failed to create index keyparameter_keyentryid_index.")?;
956
957 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800958 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
959 keyentryid INTEGER,
960 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000961 data ANY,
962 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800963 NO_PARAMS,
964 )
965 .context("Failed to initialize \"keymetadata\" table.")?;
966
Janis Danisevskis66784c42021-01-27 08:40:25 -0800967 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800968 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
969 ON keymetadata(keyentryid);",
970 NO_PARAMS,
971 )
972 .context("Failed to create index keymetadata_keyentryid_index.")?;
973
974 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800975 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700976 id INTEGER UNIQUE,
977 grantee INTEGER,
978 keyentryid INTEGER,
979 access_vector INTEGER);",
980 NO_PARAMS,
981 )
982 .context("Failed to initialize \"grant\" table.")?;
983
Joel Galenson0891bc12020-07-20 10:37:03 -0700984 Ok(())
985 }
986
Seth Moore472fcbb2021-05-12 10:07:51 -0700987 fn make_persistent_path(db_root: &Path) -> Result<String> {
988 // Build the path to the sqlite file.
989 let mut persistent_path = db_root.to_path_buf();
990 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
991
992 // Now convert them to strings prefixed with "file:"
993 let mut persistent_path_str = "file:".to_owned();
994 persistent_path_str.push_str(&persistent_path.to_string_lossy());
995
996 Ok(persistent_path_str)
997 }
998
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700999 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001000 let conn =
1001 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
1002
Janis Danisevskis66784c42021-01-27 08:40:25 -08001003 loop {
1004 if let Err(e) = conn
1005 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1006 .context("Failed to attach database persistent.")
1007 {
1008 if Self::is_locked_error(&e) {
1009 std::thread::sleep(std::time::Duration::from_micros(500));
1010 continue;
1011 } else {
1012 return Err(e);
1013 }
1014 }
1015 break;
1016 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001017
Matthew Maurer4fb19112021-05-06 15:40:44 -07001018 // Drop the cache size from default (2M) to 0.5M
1019 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1020 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001021
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001022 Ok(conn)
1023 }
1024
Seth Moore78c091f2021-04-09 21:38:30 +00001025 fn do_table_size_query(
1026 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001027 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001028 query: &str,
1029 params: &[&str],
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001030 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001031 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001032 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001033 .with_context(|| {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001034 format!("get_storage_stat: Error size of storage type {}", storage_type.0)
Seth Moore78c091f2021-04-09 21:38:30 +00001035 })
1036 .no_gc()
1037 })?;
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001038 Ok(StorageStats { storage_type, size: total, unused_size: unused })
Seth Moore78c091f2021-04-09 21:38:30 +00001039 }
1040
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001041 fn get_total_size(&mut self) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001042 self.do_table_size_query(
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001043 MetricsStorage::DATABASE,
Seth Moore78c091f2021-04-09 21:38:30 +00001044 "SELECT page_count * page_size, freelist_count * page_size
1045 FROM pragma_page_count('persistent'),
1046 pragma_page_size('persistent'),
1047 persistent.pragma_freelist_count();",
1048 &[],
1049 )
1050 }
1051
1052 fn get_table_size(
1053 &mut self,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001054 storage_type: MetricsStorage,
Seth Moore78c091f2021-04-09 21:38:30 +00001055 schema: &str,
1056 table: &str,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001057 ) -> Result<StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00001058 self.do_table_size_query(
1059 storage_type,
1060 "SELECT pgsize,unused FROM dbstat(?1)
1061 WHERE name=?2 AND aggregate=TRUE;",
1062 &[schema, table],
1063 )
1064 }
1065
1066 /// Fetches a storage statisitics atom for a given storage type. For storage
1067 /// types that map to a table, information about the table's storage is
1068 /// returned. Requests for storage types that are not DB tables return None.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001069 pub fn get_storage_stat(&mut self, storage_type: MetricsStorage) -> Result<StorageStats> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001070 let _wp = wd::watch_millis("KeystoreDB::get_storage_stat", 500);
1071
Seth Moore78c091f2021-04-09 21:38:30 +00001072 match storage_type {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001073 MetricsStorage::DATABASE => self.get_total_size(),
1074 MetricsStorage::KEY_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001075 self.get_table_size(storage_type, "persistent", "keyentry")
1076 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001077 MetricsStorage::KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001078 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1079 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001080 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001081 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1082 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001083 MetricsStorage::BLOB_ENTRY => {
Seth Moore78c091f2021-04-09 21:38:30 +00001084 self.get_table_size(storage_type, "persistent", "blobentry")
1085 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001086 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001087 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1088 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001089 MetricsStorage::KEY_PARAMETER => {
Seth Moore78c091f2021-04-09 21:38:30 +00001090 self.get_table_size(storage_type, "persistent", "keyparameter")
1091 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001092 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001093 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1094 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001095 MetricsStorage::KEY_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001096 self.get_table_size(storage_type, "persistent", "keymetadata")
1097 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001098 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001099 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1100 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001101 MetricsStorage::GRANT => self.get_table_size(storage_type, "persistent", "grant"),
1102 MetricsStorage::AUTH_TOKEN => {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001103 // Since the table is actually a BTreeMap now, unused_size is not meaningfully
1104 // reportable
1105 // Size provided is only an approximation
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001106 Ok(StorageStats {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001107 storage_type,
1108 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001109 as i32,
Matthew Maurerd7815ca2021-05-06 21:58:45 -07001110 unused_size: 0,
1111 })
Seth Moore78c091f2021-04-09 21:38:30 +00001112 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001113 MetricsStorage::BLOB_METADATA => {
Seth Moore78c091f2021-04-09 21:38:30 +00001114 self.get_table_size(storage_type, "persistent", "blobmetadata")
1115 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001116 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX => {
Seth Moore78c091f2021-04-09 21:38:30 +00001117 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1118 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00001119 _ => Err(anyhow::Error::msg(format!("Unsupported storage type: {}", storage_type.0))),
Seth Moore78c091f2021-04-09 21:38:30 +00001120 }
1121 }
1122
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001123 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001124 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1125 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001126 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1127 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001128 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001129 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001130 blob_ids_to_delete: &[i64],
1131 max_blobs: usize,
1132 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001133 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001134 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001135 // Delete the given blobs.
1136 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001137 tx.execute(
1138 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001139 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001140 )
1141 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001142 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1143 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001144 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001145
1146 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1147
Janis Danisevskis3395f862021-05-06 10:54:17 -07001148 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1149 let result: Vec<(i64, Vec<u8>)> = {
1150 let mut stmt = tx
1151 .prepare(
1152 "SELECT id, blob FROM persistent.blobentry
1153 WHERE subcomponent_type = ?
1154 AND (
1155 id NOT IN (
1156 SELECT MAX(id) FROM persistent.blobentry
1157 WHERE subcomponent_type = ?
1158 GROUP BY keyentryid, subcomponent_type
1159 )
1160 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1161 ) LIMIT ?;",
1162 )
1163 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001164
Janis Danisevskis3395f862021-05-06 10:54:17 -07001165 let rows = stmt
1166 .query_map(
1167 params![
1168 SubComponentType::KEY_BLOB,
1169 SubComponentType::KEY_BLOB,
1170 max_blobs as i64,
1171 ],
1172 |row| Ok((row.get(0)?, row.get(1)?)),
1173 )
1174 .context("Trying to query superseded blob.")?;
1175
1176 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1177 .context("Trying to extract superseded blobs.")?
1178 };
1179
1180 let result = result
1181 .into_iter()
1182 .map(|(blob_id, blob)| {
1183 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1184 })
1185 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1186 .context("Trying to load blob metadata.")?;
1187 if !result.is_empty() {
1188 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001189 }
1190
1191 // We did not find any superseded key blob, so let's remove other superseded blob in
1192 // one transaction.
1193 tx.execute(
1194 "DELETE FROM persistent.blobentry
1195 WHERE NOT subcomponent_type = ?
1196 AND (
1197 id NOT IN (
1198 SELECT MAX(id) FROM persistent.blobentry
1199 WHERE NOT subcomponent_type = ?
1200 GROUP BY keyentryid, subcomponent_type
1201 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1202 );",
1203 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1204 )
1205 .context("Trying to purge superseded blobs.")?;
1206
Janis Danisevskis3395f862021-05-06 10:54:17 -07001207 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001208 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001209 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001210 }
1211
1212 /// This maintenance function should be called only once before the database is used for the
1213 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1214 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1215 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1216 /// Keystore crashed at some point during key generation. Callers may want to log such
1217 /// occurrences.
1218 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1219 /// it to `KeyLifeCycle::Live` may have grants.
1220 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001221 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1222
Janis Danisevskis66784c42021-01-27 08:40:25 -08001223 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1224 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001225 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1226 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1227 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001228 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001229 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001230 })
1231 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001232 }
1233
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001234 /// Checks if a key exists with given key type and key descriptor properties.
1235 pub fn key_exists(
1236 &mut self,
1237 domain: Domain,
1238 nspace: i64,
1239 alias: &str,
1240 key_type: KeyType,
1241 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001242 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1243
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001244 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1245 let key_descriptor =
1246 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001247 let result = Self::load_key_entry_id(tx, &key_descriptor, key_type);
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001248 match result {
1249 Ok(_) => Ok(true),
1250 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1251 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1252 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1253 },
1254 }
1255 .no_gc()
1256 })
1257 .context("In key_exists.")
1258 }
1259
Hasini Gunasingheda895552021-01-27 19:34:37 +00001260 /// Stores a super key in the database.
1261 pub fn store_super_key(
1262 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001263 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001264 key_type: &SuperKeyType,
1265 blob: &[u8],
1266 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001267 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001268 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001269 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1270
Hasini Gunasingheda895552021-01-27 19:34:37 +00001271 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1272 let key_id = Self::insert_with_retry(|id| {
1273 tx.execute(
1274 "INSERT into persistent.keyentry
1275 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001276 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001277 params![
1278 id,
1279 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001280 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001281 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001282 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001283 KeyLifeCycle::Live,
1284 &KEYSTORE_UUID,
1285 ],
1286 )
1287 })
1288 .context("Failed to insert into keyentry table.")?;
1289
Paul Crowley8d5b2532021-03-19 10:53:07 -07001290 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1291
Hasini Gunasingheda895552021-01-27 19:34:37 +00001292 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001293 tx,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001294 key_id,
1295 SubComponentType::KEY_BLOB,
1296 Some(blob),
1297 Some(blob_metadata),
1298 )
1299 .context("Failed to store key blob.")?;
1300
1301 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1302 .context("Trying to load key components.")
1303 .no_gc()
1304 })
1305 .context("In store_super_key.")
1306 }
1307
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001308 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001309 pub fn load_super_key(
1310 &mut self,
1311 key_type: &SuperKeyType,
1312 user_id: u32,
1313 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001314 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1315
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001316 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1317 let key_descriptor = KeyDescriptor {
1318 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001319 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001320 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001321 blob: None,
1322 };
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001323 let id = Self::load_key_entry_id(tx, &key_descriptor, KeyType::Super);
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001324 match id {
1325 Ok(id) => {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001326 let key_entry = Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001327 .context("In load_super_key. Failed to load key entry.")?;
1328 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1329 }
1330 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1331 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1332 _ => Err(error).context("In load_super_key."),
1333 },
1334 }
1335 .no_gc()
1336 })
1337 .context("In load_super_key.")
1338 }
1339
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001340 /// Atomically loads a key entry and associated metadata or creates it using the
1341 /// callback create_new_key callback. The callback is called during a database
1342 /// transaction. This means that implementers should be mindful about using
1343 /// blocking operations such as IPC or grabbing mutexes.
1344 pub fn get_or_create_key_with<F>(
1345 &mut self,
1346 domain: Domain,
1347 namespace: i64,
1348 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001349 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001350 create_new_key: F,
1351 ) -> Result<(KeyIdGuard, KeyEntry)>
1352 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001353 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001354 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001355 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1356
Janis Danisevskis66784c42021-01-27 08:40:25 -08001357 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1358 let id = {
1359 let mut stmt = tx
1360 .prepare(
1361 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001362 WHERE
1363 key_type = ?
1364 AND domain = ?
1365 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001366 AND alias = ?
1367 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001368 )
1369 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1370 let mut rows = stmt
1371 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1372 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001373
Janis Danisevskis66784c42021-01-27 08:40:25 -08001374 db_utils::with_rows_extract_one(&mut rows, |row| {
1375 Ok(match row {
1376 Some(r) => r.get(0).context("Failed to unpack id.")?,
1377 None => None,
1378 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001379 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001380 .context("In get_or_create_key_with.")?
1381 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001382
Janis Danisevskis66784c42021-01-27 08:40:25 -08001383 let (id, entry) = match id {
1384 Some(id) => (
1385 id,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001386 Self::load_key_components(tx, KeyEntryLoadBits::KM, id)
Janis Danisevskis66784c42021-01-27 08:40:25 -08001387 .context("In get_or_create_key_with.")?,
1388 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001389
Janis Danisevskis66784c42021-01-27 08:40:25 -08001390 None => {
1391 let id = Self::insert_with_retry(|id| {
1392 tx.execute(
1393 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001394 (id, key_type, domain, namespace, alias, state, km_uuid)
1395 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001396 params![
1397 id,
1398 KeyType::Super,
1399 domain.0,
1400 namespace,
1401 alias,
1402 KeyLifeCycle::Live,
1403 km_uuid,
1404 ],
1405 )
1406 })
1407 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001408
Janis Danisevskis66784c42021-01-27 08:40:25 -08001409 let (blob, metadata) =
1410 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001411 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001412 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001413 id,
1414 SubComponentType::KEY_BLOB,
1415 Some(&blob),
1416 Some(&metadata),
1417 )
Paul Crowley7a658392021-03-18 17:08:20 -07001418 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001419 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001420 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001421 KeyEntry {
1422 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001423 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001424 pure_cert: false,
1425 ..Default::default()
1426 },
1427 )
1428 }
1429 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001430 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001431 })
1432 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001433 }
1434
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001435 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001436 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1437 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001438 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1439 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001440 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001441 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001442 loop {
1443 match self
1444 .conn
1445 .transaction_with_behavior(behavior)
1446 .context("In with_transaction.")
1447 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1448 .and_then(|(result, tx)| {
1449 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1450 Ok(result)
1451 }) {
1452 Ok(result) => break Ok(result),
1453 Err(e) => {
1454 if Self::is_locked_error(&e) {
1455 std::thread::sleep(std::time::Duration::from_micros(500));
1456 continue;
1457 } else {
1458 return Err(e).context("In with_transaction.");
1459 }
1460 }
1461 }
1462 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001463 .map(|(need_gc, result)| {
1464 if need_gc {
1465 if let Some(ref gc) = self.gc {
1466 gc.notify_gc();
1467 }
1468 }
1469 result
1470 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001471 }
1472
1473 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001474 matches!(
1475 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1476 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1477 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1478 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001479 }
1480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001481 /// Creates a new key entry and allocates a new randomized id for the new key.
1482 /// The key id gets associated with a domain and namespace but not with an alias.
1483 /// To complete key generation `rebind_alias` should be called after all of the
1484 /// key artifacts, i.e., blobs and parameters have been associated with the new
1485 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1486 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001487 pub fn create_key_entry(
1488 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001489 domain: &Domain,
1490 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001491 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001492 km_uuid: &Uuid,
1493 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001494 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1495
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001496 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001497 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001498 })
1499 .context("In create_key_entry.")
1500 }
1501
1502 fn create_key_entry_internal(
1503 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001504 domain: &Domain,
1505 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001506 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001507 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001508 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001509 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001510 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001511 _ => {
1512 return Err(KsError::sys())
1513 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1514 }
1515 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001516 Ok(KEY_ID_LOCK.get(
1517 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001518 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001519 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001520 (id, key_type, domain, namespace, alias, state, km_uuid)
1521 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001522 params![
1523 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001524 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001526 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001527 KeyLifeCycle::Existing,
1528 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001529 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001530 )
1531 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001532 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001533 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001534 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001535
Max Bires2b2e6562020-09-22 11:22:36 -07001536 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1537 /// The key id gets associated with a domain and namespace later but not with an alias. The
1538 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1539 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1540 /// a key.
1541 pub fn create_attestation_key_entry(
1542 &mut self,
1543 maced_public_key: &[u8],
1544 raw_public_key: &[u8],
1545 private_key: &[u8],
1546 km_uuid: &Uuid,
1547 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001548 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1549
Max Bires2b2e6562020-09-22 11:22:36 -07001550 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1551 let key_id = KEY_ID_LOCK.get(
1552 Self::insert_with_retry(|id| {
1553 tx.execute(
1554 "INSERT into persistent.keyentry
1555 (id, key_type, domain, namespace, alias, state, km_uuid)
1556 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1557 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1558 )
1559 })
1560 .context("In create_key_entry")?,
1561 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001562 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001563 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001564 key_id.0,
1565 SubComponentType::KEY_BLOB,
1566 Some(private_key),
1567 None,
1568 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001569 let mut metadata = KeyMetaData::new();
1570 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1571 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001572 metadata.store_in_db(key_id.0, tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001573 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001574 })
1575 .context("In create_attestation_key_entry")
1576 }
1577
Janis Danisevskis377d1002021-01-27 19:07:48 -08001578 /// Set a new blob and associates it with the given key id. Each blob
1579 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001580 /// Each key can have one of each sub component type associated. If more
1581 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001582 /// will get garbage collected.
1583 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1584 /// removed by setting blob to None.
1585 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001586 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001587 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001588 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001589 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001590 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001591 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001592 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1593
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001594 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001595 Self::set_blob_internal(tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001596 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001597 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001598 }
1599
Janis Danisevskiseed69842021-02-18 20:04:10 -08001600 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1601 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1602 /// We use this to insert key blobs into the database which can then be garbage collected
1603 /// lazily by the key garbage collector.
1604 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001605 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1606
Janis Danisevskiseed69842021-02-18 20:04:10 -08001607 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1608 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001609 tx,
Janis Danisevskiseed69842021-02-18 20:04:10 -08001610 Self::UNASSIGNED_KEY_ID,
1611 SubComponentType::KEY_BLOB,
1612 Some(blob),
1613 Some(blob_metadata),
1614 )
1615 .need_gc()
1616 })
1617 .context("In set_deleted_blob.")
1618 }
1619
Janis Danisevskis377d1002021-01-27 19:07:48 -08001620 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001621 tx: &Transaction,
1622 key_id: i64,
1623 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001624 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001625 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001626 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001627 match (blob, sc_type) {
1628 (Some(blob), _) => {
1629 tx.execute(
1630 "INSERT INTO persistent.blobentry
1631 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1632 params![sc_type, key_id, blob],
1633 )
1634 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001635 if let Some(blob_metadata) = blob_metadata {
1636 let blob_id = tx
1637 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1638 row.get(0)
1639 })
1640 .context("In set_blob_internal: Failed to get new blob id.")?;
1641 blob_metadata
1642 .store_in_db(blob_id, tx)
1643 .context("In set_blob_internal: Trying to store blob metadata.")?;
1644 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001645 }
1646 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1647 tx.execute(
1648 "DELETE FROM persistent.blobentry
1649 WHERE subcomponent_type = ? AND keyentryid = ?;",
1650 params![sc_type, key_id],
1651 )
1652 .context("In set_blob_internal: Failed to delete blob.")?;
1653 }
1654 (None, _) => {
1655 return Err(KsError::sys())
1656 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1657 }
1658 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001659 Ok(())
1660 }
1661
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001662 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1663 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001664 #[cfg(test)]
1665 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001666 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001667 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001668 })
1669 .context("In insert_keyparameter.")
1670 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001671
Janis Danisevskis66784c42021-01-27 08:40:25 -08001672 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001673 tx: &Transaction,
1674 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001675 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001676 ) -> Result<()> {
1677 let mut stmt = tx
1678 .prepare(
1679 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1680 VALUES (?, ?, ?, ?);",
1681 )
1682 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1683
Janis Danisevskis66784c42021-01-27 08:40:25 -08001684 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001685 stmt.insert(params![
1686 key_id.0,
1687 p.get_tag().0,
1688 p.key_parameter_value(),
1689 p.security_level().0
1690 ])
1691 .with_context(|| {
1692 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1693 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001694 }
1695 Ok(())
1696 }
1697
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001698 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001699 #[cfg(test)]
1700 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001701 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001702 metadata.store_in_db(key_id.0, tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001703 })
1704 .context("In insert_key_metadata.")
1705 }
1706
Max Bires2b2e6562020-09-22 11:22:36 -07001707 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1708 /// on the public key.
1709 pub fn store_signed_attestation_certificate_chain(
1710 &mut self,
1711 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001712 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001713 cert_chain: &[u8],
1714 expiration_date: i64,
1715 km_uuid: &Uuid,
1716 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001717 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1718
Max Bires2b2e6562020-09-22 11:22:36 -07001719 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1720 let mut stmt = tx
1721 .prepare(
1722 "SELECT keyentryid
1723 FROM persistent.keymetadata
1724 WHERE tag = ? AND data = ? AND keyentryid IN
1725 (SELECT id
1726 FROM persistent.keyentry
1727 WHERE
1728 alias IS NULL AND
1729 domain IS NULL AND
1730 namespace IS NULL AND
1731 key_type = ? AND
1732 km_uuid = ?);",
1733 )
1734 .context("Failed to store attestation certificate chain.")?;
1735 let mut rows = stmt
1736 .query(params![
1737 KeyMetaData::AttestationRawPubKey,
1738 raw_public_key,
1739 KeyType::Attestation,
1740 km_uuid
1741 ])
1742 .context("Failed to fetch keyid")?;
1743 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1744 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1745 .get(0)
1746 .context("Failed to unpack id.")
1747 })
1748 .context("Failed to get key_id.")?;
1749 let num_updated = tx
1750 .execute(
1751 "UPDATE persistent.keyentry
1752 SET alias = ?
1753 WHERE id = ?;",
1754 params!["signed", key_id],
1755 )
1756 .context("Failed to update alias.")?;
1757 if num_updated != 1 {
1758 return Err(KsError::sys()).context("Alias not updated for the key.");
1759 }
1760 let mut metadata = KeyMetaData::new();
1761 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1762 expiration_date,
1763 )));
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001764 metadata.store_in_db(key_id, tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001765 Self::set_blob_internal(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001766 tx,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001767 key_id,
1768 SubComponentType::CERT_CHAIN,
1769 Some(cert_chain),
1770 None,
1771 )
1772 .context("Failed to insert cert chain")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001773 Self::set_blob_internal(tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
Max Biresb2e1d032021-02-08 21:35:05 -08001774 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001775 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001776 })
1777 .context("In store_signed_attestation_certificate_chain: ")
1778 }
1779
1780 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1781 /// currently have a key assigned to it.
1782 pub fn assign_attestation_key(
1783 &mut self,
1784 domain: Domain,
1785 namespace: i64,
1786 km_uuid: &Uuid,
1787 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001788 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1789
Max Bires2b2e6562020-09-22 11:22:36 -07001790 match domain {
1791 Domain::APP | Domain::SELINUX => {}
1792 _ => {
1793 return Err(KsError::sys()).context(format!(
1794 concat!(
1795 "In assign_attestation_key: Domain {:?} ",
1796 "must be either App or SELinux.",
1797 ),
1798 domain
1799 ));
1800 }
1801 }
1802 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1803 let result = tx
1804 .execute(
1805 "UPDATE persistent.keyentry
1806 SET domain=?1, namespace=?2
1807 WHERE
1808 id =
1809 (SELECT MIN(id)
1810 FROM persistent.keyentry
1811 WHERE ALIAS IS NOT NULL
1812 AND domain IS NULL
1813 AND key_type IS ?3
1814 AND state IS ?4
1815 AND km_uuid IS ?5)
1816 AND
1817 (SELECT COUNT(*)
1818 FROM persistent.keyentry
1819 WHERE domain=?1
1820 AND namespace=?2
1821 AND key_type IS ?3
1822 AND state IS ?4
1823 AND km_uuid IS ?5) = 0;",
1824 params![
1825 domain.0 as u32,
1826 namespace,
1827 KeyType::Attestation,
1828 KeyLifeCycle::Live,
1829 km_uuid,
1830 ],
1831 )
1832 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001833 if result == 0 {
Hasini Gunasinghe8af67ea2021-06-30 17:09:01 +00001834 log_rkp_error_stats(MetricsRkpError::OUT_OF_KEYS);
Max Bires01f8af22021-03-02 23:24:50 -08001835 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1836 } else if result > 1 {
1837 return Err(KsError::sys())
1838 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001839 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001840 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001841 })
1842 .context("In assign_attestation_key: ")
1843 }
1844
1845 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1846 /// provisioning server, or the maximum number available if there are not num_keys number of
1847 /// entries in the table.
1848 pub fn fetch_unsigned_attestation_keys(
1849 &mut self,
1850 num_keys: i32,
1851 km_uuid: &Uuid,
1852 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001853 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1854
Max Bires2b2e6562020-09-22 11:22:36 -07001855 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1856 let mut stmt = tx
1857 .prepare(
1858 "SELECT data
1859 FROM persistent.keymetadata
1860 WHERE tag = ? AND keyentryid IN
1861 (SELECT id
1862 FROM persistent.keyentry
1863 WHERE
1864 alias IS NULL AND
1865 domain IS NULL AND
1866 namespace IS NULL AND
1867 key_type = ? AND
1868 km_uuid = ?
1869 LIMIT ?);",
1870 )
1871 .context("Failed to prepare statement")?;
1872 let rows = stmt
1873 .query_map(
1874 params![
1875 KeyMetaData::AttestationMacedPublicKey,
1876 KeyType::Attestation,
1877 km_uuid,
1878 num_keys
1879 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001880 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001881 )?
1882 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1883 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001884 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001885 })
1886 .context("In fetch_unsigned_attestation_keys")
1887 }
1888
1889 /// Removes any keys that have expired as of the current time. Returns the number of keys
1890 /// marked unreferenced that are bound to be garbage collected.
1891 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001892 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1893
Max Bires2b2e6562020-09-22 11:22:36 -07001894 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1895 let mut stmt = tx
1896 .prepare(
1897 "SELECT keyentryid, data
1898 FROM persistent.keymetadata
1899 WHERE tag = ? AND keyentryid IN
1900 (SELECT id
1901 FROM persistent.keyentry
1902 WHERE key_type = ?);",
1903 )
1904 .context("Failed to prepare query")?;
1905 let key_ids_to_check = stmt
1906 .query_map(
1907 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1908 |row| Ok((row.get(0)?, row.get(1)?)),
1909 )?
1910 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1911 .context("Failed to get date metadata")?;
1912 let curr_time = DateTime::from_millis_epoch(
1913 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1914 );
1915 let mut num_deleted = 0;
1916 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 -07001917 if Self::mark_unreferenced(tx, id)? {
Max Bires2b2e6562020-09-22 11:22:36 -07001918 num_deleted += 1;
1919 }
1920 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001921 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001922 })
1923 .context("In delete_expired_attestation_keys: ")
1924 }
1925
Max Bires60d7ed12021-03-05 15:59:22 -08001926 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1927 /// they are in. This is useful primarily as a testing mechanism.
1928 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001929 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1930
Max Bires60d7ed12021-03-05 15:59:22 -08001931 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1932 let mut stmt = tx
1933 .prepare(
1934 "SELECT id FROM persistent.keyentry
1935 WHERE key_type IS ?;",
1936 )
1937 .context("Failed to prepare statement")?;
1938 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001939 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001940 .collect::<rusqlite::Result<Vec<i64>>>()
1941 .context("Failed to execute statement")?;
1942 let num_deleted = keys_to_delete
1943 .iter()
Chris Wailesd5aaaef2021-07-27 16:04:33 -07001944 .map(|id| Self::mark_unreferenced(tx, *id))
Max Bires60d7ed12021-03-05 15:59:22 -08001945 .collect::<Result<Vec<bool>>>()
1946 .context("Failed to execute mark_unreferenced on a keyid")?
1947 .into_iter()
1948 .filter(|result| *result)
1949 .count() as i64;
1950 Ok(num_deleted).do_gc(num_deleted != 0)
1951 })
1952 .context("In delete_all_attestation_keys: ")
1953 }
1954
Max Bires2b2e6562020-09-22 11:22:36 -07001955 /// Counts the number of keys that will expire by the provided epoch date and the number of
1956 /// keys not currently assigned to a domain.
1957 pub fn get_attestation_pool_status(
1958 &mut self,
1959 date: i64,
1960 km_uuid: &Uuid,
1961 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001962 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1963
Max Bires2b2e6562020-09-22 11:22:36 -07001964 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1965 let mut stmt = tx.prepare(
1966 "SELECT data
1967 FROM persistent.keymetadata
1968 WHERE tag = ? AND keyentryid IN
1969 (SELECT id
1970 FROM persistent.keyentry
1971 WHERE alias IS NOT NULL
1972 AND key_type = ?
1973 AND km_uuid = ?
1974 AND state = ?);",
1975 )?;
1976 let times = stmt
1977 .query_map(
1978 params![
1979 KeyMetaData::AttestationExpirationDate,
1980 KeyType::Attestation,
1981 km_uuid,
1982 KeyLifeCycle::Live
1983 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001984 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001985 )?
1986 .collect::<rusqlite::Result<Vec<DateTime>>>()
1987 .context("Failed to execute metadata statement")?;
1988 let expiring =
1989 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1990 as i32;
1991 stmt = tx.prepare(
1992 "SELECT alias, domain
1993 FROM persistent.keyentry
1994 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1995 )?;
1996 let rows = stmt
1997 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1998 Ok((row.get(0)?, row.get(1)?))
1999 })?
2000 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2001 .context("Failed to execute keyentry statement")?;
2002 let mut unassigned = 0i32;
2003 let mut attested = 0i32;
2004 let total = rows.len() as i32;
2005 for (alias, domain) in rows {
2006 match (alias, domain) {
2007 (Some(_alias), None) => {
2008 attested += 1;
2009 unassigned += 1;
2010 }
2011 (Some(_alias), Some(_domain)) => {
2012 attested += 1;
2013 }
2014 _ => {}
2015 }
2016 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002017 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002018 })
2019 .context("In get_attestation_pool_status: ")
2020 }
2021
2022 /// Fetches the private key and corresponding certificate chain assigned to a
2023 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2024 /// not assigned, or one CertificateChain.
2025 pub fn retrieve_attestation_key_and_cert_chain(
2026 &mut self,
2027 domain: Domain,
2028 namespace: i64,
2029 km_uuid: &Uuid,
2030 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002031 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2032
Max Bires2b2e6562020-09-22 11:22:36 -07002033 match domain {
2034 Domain::APP | Domain::SELINUX => {}
2035 _ => {
2036 return Err(KsError::sys())
2037 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2038 }
2039 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002040 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2041 let mut stmt = tx.prepare(
2042 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002043 FROM persistent.blobentry
2044 WHERE keyentryid IN
2045 (SELECT id
2046 FROM persistent.keyentry
2047 WHERE key_type = ?
2048 AND domain = ?
2049 AND namespace = ?
2050 AND state = ?
2051 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002052 )?;
2053 let rows = stmt
2054 .query_map(
2055 params![
2056 KeyType::Attestation,
2057 domain.0 as u32,
2058 namespace,
2059 KeyLifeCycle::Live,
2060 km_uuid
2061 ],
2062 |row| Ok((row.get(0)?, row.get(1)?)),
2063 )?
2064 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002065 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002066 if rows.is_empty() {
2067 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002068 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002069 return Err(KsError::sys()).context(format!(
2070 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002071 "Expected to get a single attestation",
2072 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2073 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002074 rows.len()
2075 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002076 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002077 let mut km_blob: Vec<u8> = Vec::new();
2078 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002079 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002080 for row in rows {
2081 let sub_type: SubComponentType = row.0;
2082 match sub_type {
2083 SubComponentType::KEY_BLOB => {
2084 km_blob = row.1;
2085 }
2086 SubComponentType::CERT_CHAIN => {
2087 cert_chain_blob = row.1;
2088 }
Max Biresb2e1d032021-02-08 21:35:05 -08002089 SubComponentType::CERT => {
2090 batch_cert_blob = row.1;
2091 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002092 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2093 }
2094 }
2095 Ok(Some(CertificateChain {
2096 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002097 batch_cert: batch_cert_blob,
2098 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002099 }))
2100 .no_gc()
2101 })
Max Biresb2e1d032021-02-08 21:35:05 -08002102 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002103 }
2104
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002105 /// Updates the alias column of the given key id `newid` with the given alias,
2106 /// and atomically, removes the alias, domain, and namespace from another row
2107 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002108 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2109 /// collector.
2110 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002111 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002112 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002113 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002114 domain: &Domain,
2115 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002116 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002117 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002118 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002119 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002120 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002121 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002122 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002123 domain
2124 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002125 }
2126 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002127 let updated = tx
2128 .execute(
2129 "UPDATE persistent.keyentry
2130 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002131 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2132 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002133 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002134 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002135 let result = tx
2136 .execute(
2137 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002138 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002139 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002140 params![
2141 alias,
2142 KeyLifeCycle::Live,
2143 newid.0,
2144 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002145 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002146 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002147 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002148 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002149 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002150 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002151 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002152 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002153 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002154 result
2155 ));
2156 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002157 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002158 }
2159
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002160 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2161 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2162 pub fn migrate_key_namespace(
2163 &mut self,
2164 key_id_guard: KeyIdGuard,
2165 destination: &KeyDescriptor,
2166 caller_uid: u32,
2167 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2168 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002169 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2170
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002171 let destination = match destination.domain {
2172 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2173 Domain::SELINUX => (*destination).clone(),
2174 domain => {
2175 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2176 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2177 }
2178 };
2179
2180 // Security critical: Must return immediately on failure. Do not remove the '?';
2181 check_permission(&destination)
2182 .context("In migrate_key_namespace: Trying to check permission.")?;
2183
2184 let alias = destination
2185 .alias
2186 .as_ref()
2187 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2188 .context("In migrate_key_namespace: Alias must be specified.")?;
2189
2190 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2191 // Query the destination location. If there is a key, the migration request fails.
2192 if tx
2193 .query_row(
2194 "SELECT id FROM persistent.keyentry
2195 WHERE alias = ? AND domain = ? AND namespace = ?;",
2196 params![alias, destination.domain.0, destination.nspace],
2197 |_| Ok(()),
2198 )
2199 .optional()
2200 .context("Failed to query destination.")?
2201 .is_some()
2202 {
2203 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2204 .context("Target already exists.");
2205 }
2206
2207 let updated = tx
2208 .execute(
2209 "UPDATE persistent.keyentry
2210 SET alias = ?, domain = ?, namespace = ?
2211 WHERE id = ?;",
2212 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2213 )
2214 .context("Failed to update key entry.")?;
2215
2216 if updated != 1 {
2217 return Err(KsError::sys())
2218 .context(format!("Update succeeded, but {} rows were updated.", updated));
2219 }
2220 Ok(()).no_gc()
2221 })
2222 .context("In migrate_key_namespace:")
2223 }
2224
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002225 /// Store a new key in a single transaction.
2226 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2227 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002228 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2229 /// is now unreferenced and needs to be collected.
Chris Wailes3877f292021-07-26 19:24:18 -07002230 #[allow(clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002231 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002232 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002233 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002234 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002235 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002236 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002237 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002238 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002239 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002240 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002241 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2242
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002243 let (alias, domain, namespace) = match key {
2244 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2245 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2246 (alias, key.domain, nspace)
2247 }
2248 _ => {
2249 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2250 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2251 }
2252 };
2253 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002254 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002255 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002256 let (blob, blob_metadata) = *blob_info;
2257 Self::set_blob_internal(
2258 tx,
2259 key_id.id(),
2260 SubComponentType::KEY_BLOB,
2261 Some(blob),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002262 Some(blob_metadata),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002263 )
2264 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002265 if let Some(cert) = &cert_info.cert {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002266 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002267 .context("Trying to insert the certificate.")?;
2268 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002269 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002270 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 tx,
2272 key_id.id(),
2273 SubComponentType::CERT_CHAIN,
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002274 Some(cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002275 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002276 )
2277 .context("Trying to insert the certificate chain.")?;
2278 }
2279 Self::insert_keyparameter_internal(tx, &key_id, params)
2280 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002281 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002282 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002283 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002284 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002285 })
2286 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002287 }
2288
Janis Danisevskis377d1002021-01-27 19:07:48 -08002289 /// Store a new certificate
2290 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2291 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002292 pub fn store_new_certificate(
2293 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002294 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002295 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002296 cert: &[u8],
2297 km_uuid: &Uuid,
2298 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002299 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2300
Janis Danisevskis377d1002021-01-27 19:07:48 -08002301 let (alias, domain, namespace) = match key {
2302 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2303 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2304 (alias, key.domain, nspace)
2305 }
2306 _ => {
2307 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2308 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2309 )
2310 }
2311 };
2312 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002313 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002314 .context("Trying to create new key entry.")?;
2315
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002316 Self::set_blob_internal(
2317 tx,
2318 key_id.id(),
2319 SubComponentType::CERT_CHAIN,
2320 Some(cert),
2321 None,
2322 )
2323 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002324
2325 let mut metadata = KeyMetaData::new();
2326 metadata.add(KeyMetaEntry::CreationDate(
2327 DateTime::now().context("Trying to make creation time.")?,
2328 ));
2329
2330 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2331
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002332 let need_gc = Self::rebind_alias(tx, &key_id, alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002333 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002334 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002335 })
2336 .context("In store_new_certificate.")
2337 }
2338
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002339 // Helper function loading the key_id given the key descriptor
2340 // tuple comprising domain, namespace, and alias.
2341 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002342 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002343 let alias = key
2344 .alias
2345 .as_ref()
2346 .map_or_else(|| Err(KsError::sys()), Ok)
2347 .context("In load_key_entry_id: Alias must be specified.")?;
2348 let mut stmt = tx
2349 .prepare(
2350 "SELECT id FROM persistent.keyentry
2351 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002352 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002353 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002354 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002355 AND alias = ?
2356 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002357 )
2358 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2359 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002360 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002361 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002362 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002363 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002364 .get(0)
2365 .context("Failed to unpack id.")
2366 })
2367 .context("In load_key_entry_id.")
2368 }
2369
2370 /// This helper function completes the access tuple of a key, which is required
2371 /// to perform access control. The strategy depends on the `domain` field in the
2372 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002373 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002374 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002375 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002376 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002377 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002378 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002379 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002380 /// `namespace`.
2381 /// In each case the information returned is sufficient to perform the access
2382 /// check and the key id can be used to load further key artifacts.
2383 fn load_access_tuple(
2384 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002385 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002386 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002387 caller_uid: u32,
2388 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2389 match key.domain {
2390 // Domain App or SELinux. In this case we load the key_id from
2391 // the keyentry database for further loading of key components.
2392 // We already have the full access tuple to perform access control.
2393 // The only distinction is that we use the caller_uid instead
2394 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002395 // Domain::APP.
2396 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002397 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002398 if access_key.domain == Domain::APP {
2399 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002400 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002401 let key_id = Self::load_key_entry_id(tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002402 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002403
2404 Ok((key_id, access_key, None))
2405 }
2406
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002407 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002408 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002409 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002410 let mut stmt = tx
2411 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002412 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002413 WHERE grantee = ? AND id = ? AND
2414 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002415 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002416 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002417 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002418 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419 .context("Domain:Grant: query failed.")?;
2420 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002421 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002422 let r =
2423 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002424 Ok((
2425 r.get(0).context("Failed to unpack key_id.")?,
2426 r.get(1).context("Failed to unpack access_vector.")?,
2427 ))
2428 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002429 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002430 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002431 }
2432
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002433 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002434 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002435 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002436 let (domain, namespace): (Domain, i64) = {
2437 let mut stmt = tx
2438 .prepare(
2439 "SELECT domain, namespace FROM persistent.keyentry
2440 WHERE
2441 id = ?
2442 AND state = ?;",
2443 )
2444 .context("Domain::KEY_ID: prepare statement failed")?;
2445 let mut rows = stmt
2446 .query(params![key.nspace, KeyLifeCycle::Live])
2447 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002448 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002449 let r =
2450 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002451 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002452 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002453 r.get(1).context("Failed to unpack namespace.")?,
2454 ))
2455 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002456 .context("Domain::KEY_ID.")?
2457 };
2458
2459 // We may use a key by id after loading it by grant.
2460 // In this case we have to check if the caller has a grant for this particular
2461 // key. We can skip this if we already know that the caller is the owner.
2462 // But we cannot know this if domain is anything but App. E.g. in the case
2463 // of Domain::SELINUX we have to speculatively check for grants because we have to
2464 // consult the SEPolicy before we know if the caller is the owner.
2465 let access_vector: Option<KeyPermSet> =
2466 if domain != Domain::APP || namespace != caller_uid as i64 {
2467 let access_vector: Option<i32> = tx
2468 .query_row(
2469 "SELECT access_vector FROM persistent.grant
2470 WHERE grantee = ? AND keyentryid = ?;",
2471 params![caller_uid as i64, key.nspace],
2472 |row| row.get(0),
2473 )
2474 .optional()
2475 .context("Domain::KEY_ID: query grant failed.")?;
2476 access_vector.map(|p| p.into())
2477 } else {
2478 None
2479 };
2480
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002481 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002482 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002483 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002484 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002485
Janis Danisevskis45760022021-01-19 16:34:10 -08002486 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002487 }
2488 _ => Err(anyhow!(KsError::sys())),
2489 }
2490 }
2491
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002492 fn load_blob_components(
2493 key_id: i64,
2494 load_bits: KeyEntryLoadBits,
2495 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002496 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002497 let mut stmt = tx
2498 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002499 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002500 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2501 )
2502 .context("In load_blob_components: prepare statement failed.")?;
2503
2504 let mut rows =
2505 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2506
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002507 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002508 let mut cert_blob: Option<Vec<u8>> = None;
2509 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002510 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002511 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002512 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002513 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002514 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002515 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2516 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002517 key_blob = Some((
2518 row.get(0).context("Failed to extract key blob id.")?,
2519 row.get(2).context("Failed to extract key blob.")?,
2520 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002521 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002522 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002523 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002524 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002525 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002526 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002527 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002528 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002529 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002530 (SubComponentType::CERT, _, _)
2531 | (SubComponentType::CERT_CHAIN, _, _)
2532 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002533 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2534 }
2535 Ok(())
2536 })
2537 .context("In load_blob_components.")?;
2538
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002539 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2540 Ok(Some((
2541 blob,
2542 BlobMetaData::load_from_db(blob_id, tx)
2543 .context("In load_blob_components: Trying to load blob_metadata.")?,
2544 )))
2545 })?;
2546
2547 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002548 }
2549
2550 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2551 let mut stmt = tx
2552 .prepare(
2553 "SELECT tag, data, security_level from persistent.keyparameter
2554 WHERE keyentryid = ?;",
2555 )
2556 .context("In load_key_parameters: prepare statement failed.")?;
2557
2558 let mut parameters: Vec<KeyParameter> = Vec::new();
2559
2560 let mut rows =
2561 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002562 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002563 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2564 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002565 parameters.push(
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002566 KeyParameter::new_from_sql(tag, &SqlField::new(1, row), sec_level)
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002567 .context("Failed to read KeyParameter.")?,
2568 );
2569 Ok(())
2570 })
2571 .context("In load_key_parameters.")?;
2572
2573 Ok(parameters)
2574 }
2575
Qi Wub9433b52020-12-01 14:52:46 +08002576 /// Decrements the usage count of a limited use key. This function first checks whether the
2577 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2578 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2579 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002580 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002581 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2582
Qi Wub9433b52020-12-01 14:52:46 +08002583 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2584 let limit: Option<i32> = tx
2585 .query_row(
2586 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2587 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2588 |row| row.get(0),
2589 )
2590 .optional()
2591 .context("Trying to load usage count")?;
2592
2593 let limit = limit
2594 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2595 .context("The Key no longer exists. Key is exhausted.")?;
2596
2597 tx.execute(
2598 "UPDATE persistent.keyparameter
2599 SET data = data - 1
2600 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2601 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2602 )
2603 .context("Failed to update key usage count.")?;
2604
2605 match limit {
2606 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002607 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002608 .context("Trying to mark limited use key for deletion."),
2609 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002610 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002611 }
2612 })
2613 .context("In check_and_update_key_usage_count.")
2614 }
2615
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002616 /// Load a key entry by the given key descriptor.
2617 /// It uses the `check_permission` callback to verify if the access is allowed
2618 /// given the key access tuple read from the database using `load_access_tuple`.
2619 /// With `load_bits` the caller may specify which blobs shall be loaded from
2620 /// the blob database.
2621 pub fn load_key_entry(
2622 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002623 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002624 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002625 load_bits: KeyEntryLoadBits,
2626 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002627 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2628 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002629 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2630
Janis Danisevskis66784c42021-01-27 08:40:25 -08002631 loop {
2632 match self.load_key_entry_internal(
2633 key,
2634 key_type,
2635 load_bits,
2636 caller_uid,
2637 &check_permission,
2638 ) {
2639 Ok(result) => break Ok(result),
2640 Err(e) => {
2641 if Self::is_locked_error(&e) {
2642 std::thread::sleep(std::time::Duration::from_micros(500));
2643 continue;
2644 } else {
2645 return Err(e).context("In load_key_entry.");
2646 }
2647 }
2648 }
2649 }
2650 }
2651
2652 fn load_key_entry_internal(
2653 &mut self,
2654 key: &KeyDescriptor,
2655 key_type: KeyType,
2656 load_bits: KeyEntryLoadBits,
2657 caller_uid: u32,
2658 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002659 ) -> Result<(KeyIdGuard, KeyEntry)> {
2660 // KEY ID LOCK 1/2
2661 // If we got a key descriptor with a key id we can get the lock right away.
2662 // Otherwise we have to defer it until we know the key id.
2663 let key_id_guard = match key.domain {
2664 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2665 _ => None,
2666 };
2667
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002668 let tx = self
2669 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002670 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002671 .context("In load_key_entry: Failed to initialize transaction.")?;
2672
2673 // Load the key_id and complete the access control tuple.
2674 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002675 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2676 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002677
2678 // Perform access control. It is vital that we return here if the permission is denied.
2679 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002680 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002681
Janis Danisevskisaec14592020-11-12 09:41:49 -08002682 // KEY ID LOCK 2/2
2683 // If we did not get a key id lock by now, it was because we got a key descriptor
2684 // without a key id. At this point we got the key id, so we can try and get a lock.
2685 // However, we cannot block here, because we are in the middle of the transaction.
2686 // So first we try to get the lock non blocking. If that fails, we roll back the
2687 // transaction and block until we get the lock. After we successfully got the lock,
2688 // we start a new transaction and load the access tuple again.
2689 //
2690 // We don't need to perform access control again, because we already established
2691 // that the caller had access to the given key. But we need to make sure that the
2692 // key id still exists. So we have to load the key entry by key id this time.
2693 let (key_id_guard, tx) = match key_id_guard {
2694 None => match KEY_ID_LOCK.try_get(key_id) {
2695 None => {
2696 // Roll back the transaction.
2697 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002698
Janis Danisevskisaec14592020-11-12 09:41:49 -08002699 // Block until we have a key id lock.
2700 let key_id_guard = KEY_ID_LOCK.get(key_id);
2701
2702 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002703 let tx = self
2704 .conn
2705 .unchecked_transaction()
2706 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002707
2708 Self::load_access_tuple(
2709 &tx,
2710 // This time we have to load the key by the retrieved key id, because the
2711 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002712 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002713 domain: Domain::KEY_ID,
2714 nspace: key_id,
2715 ..Default::default()
2716 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002717 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002718 caller_uid,
2719 )
2720 .context("In load_key_entry. (deferred key lock)")?;
2721 (key_id_guard, tx)
2722 }
2723 Some(l) => (l, tx),
2724 },
2725 Some(key_id_guard) => (key_id_guard, tx),
2726 };
2727
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002728 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2729 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002730
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002731 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2732
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002733 Ok((key_id_guard, key_entry))
2734 }
2735
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002736 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002737 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002738 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2739 .context("Trying to delete keyentry.")?;
2740 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2741 .context("Trying to delete keymetadata.")?;
2742 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2743 .context("Trying to delete keyparameters.")?;
2744 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2745 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002746 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002747 }
2748
2749 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002750 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002751 pub fn unbind_key(
2752 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002753 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002754 key_type: KeyType,
2755 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002756 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002757 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002758 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2759
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002760 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2761 let (key_id, access_key_descriptor, access_vector) =
2762 Self::load_access_tuple(tx, key, key_type, caller_uid)
2763 .context("Trying to get access tuple.")?;
2764
2765 // Perform access control. It is vital that we return here if the permission is denied.
2766 // So do not touch that '?' at the end.
2767 check_permission(&access_key_descriptor, access_vector)
2768 .context("While checking permission.")?;
2769
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002770 Self::mark_unreferenced(tx, key_id)
2771 .map(|need_gc| (need_gc, ()))
2772 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002773 })
2774 .context("In unbind_key.")
2775 }
2776
Max Bires8e93d2b2021-01-14 13:17:59 -08002777 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2778 tx.query_row(
2779 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2780 params![key_id],
2781 |row| row.get(0),
2782 )
2783 .context("In get_key_km_uuid.")
2784 }
2785
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002786 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2787 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2788 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002789 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2790
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002791 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2792 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2793 .context("In unbind_keys_for_namespace.");
2794 }
2795 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2796 tx.execute(
2797 "DELETE FROM persistent.keymetadata
2798 WHERE keyentryid IN (
2799 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002800 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002801 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002802 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002803 )
2804 .context("Trying to delete keymetadata.")?;
2805 tx.execute(
2806 "DELETE FROM persistent.keyparameter
2807 WHERE keyentryid IN (
2808 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002809 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002810 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002811 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002812 )
2813 .context("Trying to delete keyparameters.")?;
2814 tx.execute(
2815 "DELETE FROM persistent.grant
2816 WHERE keyentryid IN (
2817 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002818 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002819 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002820 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002821 )
2822 .context("Trying to delete grants.")?;
2823 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002824 "DELETE FROM persistent.keyentry
2825 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2826 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002827 )
2828 .context("Trying to delete keyentry.")?;
2829 Ok(()).need_gc()
2830 })
2831 .context("In unbind_keys_for_namespace")
2832 }
2833
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002834 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2835 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2836 {
2837 tx.execute(
2838 "DELETE FROM persistent.keymetadata
2839 WHERE keyentryid IN (
2840 SELECT id FROM persistent.keyentry
2841 WHERE state = ?
2842 );",
2843 params![KeyLifeCycle::Unreferenced],
2844 )
2845 .context("Trying to delete keymetadata.")?;
2846 tx.execute(
2847 "DELETE FROM persistent.keyparameter
2848 WHERE keyentryid IN (
2849 SELECT id FROM persistent.keyentry
2850 WHERE state = ?
2851 );",
2852 params![KeyLifeCycle::Unreferenced],
2853 )
2854 .context("Trying to delete keyparameters.")?;
2855 tx.execute(
2856 "DELETE FROM persistent.grant
2857 WHERE keyentryid IN (
2858 SELECT id FROM persistent.keyentry
2859 WHERE state = ?
2860 );",
2861 params![KeyLifeCycle::Unreferenced],
2862 )
2863 .context("Trying to delete grants.")?;
2864 tx.execute(
2865 "DELETE FROM persistent.keyentry
2866 WHERE state = ?;",
2867 params![KeyLifeCycle::Unreferenced],
2868 )
2869 .context("Trying to delete keyentry.")?;
2870 Result::<()>::Ok(())
2871 }
2872 .context("In cleanup_unreferenced")
2873 }
2874
Hasini Gunasingheda895552021-01-27 19:34:37 +00002875 /// Delete the keys created on behalf of the user, denoted by the user id.
2876 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2877 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2878 /// The caller of this function should notify the gc if the returned value is true.
2879 pub fn unbind_keys_for_user(
2880 &mut self,
2881 user_id: u32,
2882 keep_non_super_encrypted_keys: bool,
2883 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002884 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2885
Hasini Gunasingheda895552021-01-27 19:34:37 +00002886 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2887 let mut stmt = tx
2888 .prepare(&format!(
2889 "SELECT id from persistent.keyentry
2890 WHERE (
2891 key_type = ?
2892 AND domain = ?
2893 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2894 AND state = ?
2895 ) OR (
2896 key_type = ?
2897 AND namespace = ?
Hasini Gunasingheda895552021-01-27 19:34:37 +00002898 AND state = ?
2899 );",
2900 aid_user_offset = AID_USER_OFFSET
2901 ))
2902 .context(concat!(
2903 "In unbind_keys_for_user. ",
2904 "Failed to prepare the query to find the keys created by apps."
2905 ))?;
2906
2907 let mut rows = stmt
2908 .query(params![
2909 // WHERE client key:
2910 KeyType::Client,
2911 Domain::APP.0 as u32,
2912 user_id,
2913 KeyLifeCycle::Live,
2914 // OR super key:
2915 KeyType::Super,
2916 user_id,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002917 KeyLifeCycle::Live
2918 ])
2919 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2920
2921 let mut key_ids: Vec<i64> = Vec::new();
2922 db_utils::with_rows_extract_all(&mut rows, |row| {
2923 key_ids
2924 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2925 Ok(())
2926 })
2927 .context("In unbind_keys_for_user.")?;
2928
2929 let mut notify_gc = false;
2930 for key_id in key_ids {
2931 if keep_non_super_encrypted_keys {
2932 // Load metadata and filter out non-super-encrypted keys.
2933 if let (_, Some((_, blob_metadata)), _, _) =
2934 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2935 .context("In unbind_keys_for_user: Trying to load blob info.")?
2936 {
2937 if blob_metadata.encrypted_by().is_none() {
2938 continue;
2939 }
2940 }
2941 }
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002942 notify_gc = Self::mark_unreferenced(tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002943 .context("In unbind_keys_for_user.")?
2944 || notify_gc;
2945 }
2946 Ok(()).do_gc(notify_gc)
2947 })
2948 .context("In unbind_keys_for_user.")
2949 }
2950
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002951 fn load_key_components(
2952 tx: &Transaction,
2953 load_bits: KeyEntryLoadBits,
2954 key_id: i64,
2955 ) -> Result<KeyEntry> {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002956 let metadata = KeyMetaData::load_from_db(key_id, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002957
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002958 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002959 Self::load_blob_components(key_id, load_bits, tx).context("In load_key_components.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002960
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002961 let parameters = Self::load_key_parameters(key_id, tx)
Max Bires8e93d2b2021-01-14 13:17:59 -08002962 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002963
Chris Wailesd5aaaef2021-07-27 16:04:33 -07002964 let km_uuid = Self::get_key_km_uuid(tx, key_id)
Max Bires8e93d2b2021-01-14 13:17:59 -08002965 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002966
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002967 Ok(KeyEntry {
2968 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002969 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002970 cert: cert_blob,
2971 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002972 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002973 parameters,
2974 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002975 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002976 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002977 }
2978
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002979 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2980 /// The key descriptors will have the domain, nspace, and alias field set.
2981 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07002982 pub fn list(
2983 &mut self,
2984 domain: Domain,
2985 namespace: i64,
2986 key_type: KeyType,
2987 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002988 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2989
Janis Danisevskis66784c42021-01-27 08:40:25 -08002990 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2991 let mut stmt = tx
2992 .prepare(
2993 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002994 WHERE domain = ?
2995 AND namespace = ?
2996 AND alias IS NOT NULL
2997 AND state = ?
2998 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002999 )
3000 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003001
Janis Danisevskis66784c42021-01-27 08:40:25 -08003002 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003003 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08003004 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003005
Janis Danisevskis66784c42021-01-27 08:40:25 -08003006 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3007 db_utils::with_rows_extract_all(&mut rows, |row| {
3008 descriptors.push(KeyDescriptor {
3009 domain,
3010 nspace: namespace,
3011 alias: Some(row.get(0).context("Trying to extract alias.")?),
3012 blob: None,
3013 });
3014 Ok(())
3015 })
3016 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003017 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003018 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003019 }
3020
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003021 /// Adds a grant to the grant table.
3022 /// Like `load_key_entry` this function loads the access tuple before
3023 /// it uses the callback for a permission check. Upon success,
3024 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3025 /// grant table. The new row will have a randomized id, which is used as
3026 /// grant id in the namespace field of the resulting KeyDescriptor.
3027 pub fn grant(
3028 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003029 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003030 caller_uid: u32,
3031 grantee_uid: u32,
3032 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003033 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003034 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003035 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3036
Janis Danisevskis66784c42021-01-27 08:40:25 -08003037 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3038 // Load the key_id and complete the access control tuple.
3039 // We ignore the access vector here because grants cannot be granted.
3040 // The access vector returned here expresses the permissions the
3041 // grantee has if key.domain == Domain::GRANT. But this vector
3042 // cannot include the grant permission by design, so there is no way the
3043 // subsequent permission check can pass.
3044 // We could check key.domain == Domain::GRANT and fail early.
3045 // But even if we load the access tuple by grant here, the permission
3046 // check denies the attempt to create a grant by grant descriptor.
3047 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003048 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003049 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003050
Janis Danisevskis66784c42021-01-27 08:40:25 -08003051 // Perform access control. It is vital that we return here if the permission
3052 // was denied. So do not touch that '?' at the end of the line.
3053 // This permission check checks if the caller has the grant permission
3054 // for the given key and in addition to all of the permissions
3055 // expressed in `access_vector`.
3056 check_permission(&access_key_descriptor, &access_vector)
3057 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003058
Janis Danisevskis66784c42021-01-27 08:40:25 -08003059 let grant_id = if let Some(grant_id) = tx
3060 .query_row(
3061 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003062 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003063 params![key_id, grantee_uid],
3064 |row| row.get(0),
3065 )
3066 .optional()
3067 .context("In grant: Failed get optional existing grant id.")?
3068 {
3069 tx.execute(
3070 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003071 SET access_vector = ?
3072 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003073 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003074 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003075 .context("In grant: Failed to update existing grant.")?;
3076 grant_id
3077 } else {
3078 Self::insert_with_retry(|id| {
3079 tx.execute(
3080 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3081 VALUES (?, ?, ?, ?);",
3082 params![id, grantee_uid, key_id, i32::from(access_vector)],
3083 )
3084 })
3085 .context("In grant")?
3086 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003087
Janis Danisevskis66784c42021-01-27 08:40:25 -08003088 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003089 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003090 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003091 }
3092
3093 /// This function checks permissions like `grant` and `load_key_entry`
3094 /// before removing a grant from the grant table.
3095 pub fn ungrant(
3096 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003097 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003098 caller_uid: u32,
3099 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003100 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003101 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003102 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3103
Janis Danisevskis66784c42021-01-27 08:40:25 -08003104 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3105 // Load the key_id and complete the access control tuple.
3106 // We ignore the access vector here because grants cannot be granted.
3107 let (key_id, access_key_descriptor, _) =
Chris Wailesd5aaaef2021-07-27 16:04:33 -07003108 Self::load_access_tuple(tx, key, KeyType::Client, caller_uid)
Janis Danisevskis66784c42021-01-27 08:40:25 -08003109 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003110
Janis Danisevskis66784c42021-01-27 08:40:25 -08003111 // Perform access control. We must return here if the permission
3112 // was denied. So do not touch the '?' at the end of this line.
3113 check_permission(&access_key_descriptor)
3114 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003115
Janis Danisevskis66784c42021-01-27 08:40:25 -08003116 tx.execute(
3117 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003118 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003119 params![key_id, grantee_uid],
3120 )
3121 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003122
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003123 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003124 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003125 }
3126
Joel Galenson845f74b2020-09-09 14:11:55 -07003127 // Generates a random id and passes it to the given function, which will
3128 // try to insert it into a database. If that insertion fails, retry;
3129 // otherwise return the id.
3130 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3131 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003132 let newid: i64 = match random() {
3133 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3134 i => i,
3135 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003136 match inserter(newid) {
3137 // If the id already existed, try again.
3138 Err(rusqlite::Error::SqliteFailure(
3139 libsqlite3_sys::Error {
3140 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3141 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3142 },
3143 _,
3144 )) => (),
3145 Err(e) => {
3146 return Err(e).context("In insert_with_retry: failed to insert into database.")
3147 }
3148 _ => return Ok(newid),
3149 }
3150 }
3151 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003152
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003153 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3154 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3155 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3156 auth_token.clone(),
3157 MonotonicRawTime::now(),
3158 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003159 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003160
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003161 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003162 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003163 where
3164 F: Fn(&AuthTokenEntry) -> bool,
3165 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003166 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003167 }
3168
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003169 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003170 pub fn insert_last_off_body(&self, last_off_body: MonotonicRawTime) {
3171 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003172 }
3173
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003174 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003175 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3176 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003177 }
3178
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003179 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003180 fn get_last_off_body(&self) -> MonotonicRawTime {
3181 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003182 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003183
3184 /// Load descriptor of a key by key id
3185 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3186 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3187
3188 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3189 tx.query_row(
3190 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3191 params![key_id],
3192 |row| {
3193 Ok(KeyDescriptor {
3194 domain: Domain(row.get(0)?),
3195 nspace: row.get(1)?,
3196 alias: row.get(2)?,
3197 blob: None,
3198 })
3199 },
3200 )
3201 .optional()
3202 .context("Trying to load key descriptor")
3203 .no_gc()
3204 })
3205 .context("In load_key_descriptor.")
3206 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003207}
3208
3209#[cfg(test)]
Seth Moore7ee79f92021-12-07 11:42:49 -08003210pub mod tests {
Joel Galenson26f4d012020-07-17 14:57:21 -07003211
3212 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003213 use crate::key_parameter::{
3214 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3215 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3216 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003217 use crate::key_perm_set;
3218 use crate::permission::{KeyPerm, KeyPermSet};
Janis Danisevskis11bd2592022-01-04 19:59:26 -08003219 use crate::super_key::{SuperKeyManager, USER_SUPER_KEY, SuperEncryptionAlgorithm, SuperKeyType};
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003220 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003221 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3222 HardwareAuthToken::HardwareAuthToken,
3223 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003224 };
3225 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003226 Timestamp::Timestamp,
3227 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003228 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003229 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003230 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003231 use std::collections::BTreeMap;
3232 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003233 use std::sync::atomic::{AtomicU8, Ordering};
3234 use std::sync::Arc;
3235 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003236 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003237 #[cfg(disabled)]
3238 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003239
Seth Moore7ee79f92021-12-07 11:42:49 -08003240 pub fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003241 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003242
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003243 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003244 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003245 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003246 })?;
3247 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003248 }
3249
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003250 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3251 where
3252 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3253 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003254 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003255
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003256 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003257 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003258
Janis Danisevskis3395f862021-05-06 10:54:17 -07003259 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003260 }
3261
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003262 fn rebind_alias(
3263 db: &mut KeystoreDB,
3264 newid: &KeyIdGuard,
3265 alias: &str,
3266 domain: Domain,
3267 namespace: i64,
3268 ) -> Result<bool> {
3269 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003270 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003271 })
3272 .context("In rebind_alias.")
3273 }
3274
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003275 #[test]
3276 fn datetime() -> Result<()> {
3277 let conn = Connection::open_in_memory()?;
3278 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3279 let now = SystemTime::now();
3280 let duration = Duration::from_secs(1000);
3281 let then = now.checked_sub(duration).unwrap();
3282 let soon = now.checked_add(duration).unwrap();
3283 conn.execute(
3284 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3285 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3286 )?;
3287 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3288 let mut rows = stmt.query(NO_PARAMS)?;
3289 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3290 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3291 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3292 assert!(rows.next()?.is_none());
3293 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3294 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3295 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3296 Ok(())
3297 }
3298
Joel Galenson0891bc12020-07-20 10:37:03 -07003299 // Ensure that we're using the "injected" random function, not the real one.
3300 #[test]
3301 fn test_mocked_random() {
3302 let rand1 = random();
3303 let rand2 = random();
3304 let rand3 = random();
3305 if rand1 == rand2 {
3306 assert_eq!(rand2 + 1, rand3);
3307 } else {
3308 assert_eq!(rand1 + 1, rand2);
3309 assert_eq!(rand2, rand3);
3310 }
3311 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003312
Joel Galenson26f4d012020-07-17 14:57:21 -07003313 // Test that we have the correct tables.
3314 #[test]
3315 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003316 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003317 let tables = db
3318 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003319 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003320 .query_map(params![], |row| row.get(0))?
3321 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003322 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003323 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003324 assert_eq!(tables[1], "blobmetadata");
3325 assert_eq!(tables[2], "grant");
3326 assert_eq!(tables[3], "keyentry");
3327 assert_eq!(tables[4], "keymetadata");
3328 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003329 Ok(())
3330 }
3331
3332 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003333 fn test_auth_token_table_invariant() -> Result<()> {
3334 let mut db = new_test_db()?;
3335 let auth_token1 = HardwareAuthToken {
3336 challenge: i64::MAX,
3337 userId: 200,
3338 authenticatorId: 200,
3339 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3340 timestamp: Timestamp { milliSeconds: 500 },
3341 mac: String::from("mac").into_bytes(),
3342 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003343 db.insert_auth_token(&auth_token1);
3344 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003345 assert_eq!(auth_tokens_returned.len(), 1);
3346
3347 // insert another auth token with the same values for the columns in the UNIQUE constraint
3348 // of the auth token table and different value for timestamp
3349 let auth_token2 = HardwareAuthToken {
3350 challenge: i64::MAX,
3351 userId: 200,
3352 authenticatorId: 200,
3353 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3354 timestamp: Timestamp { milliSeconds: 600 },
3355 mac: String::from("mac").into_bytes(),
3356 };
3357
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003358 db.insert_auth_token(&auth_token2);
3359 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003360 assert_eq!(auth_tokens_returned.len(), 1);
3361
3362 if let Some(auth_token) = auth_tokens_returned.pop() {
3363 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3364 }
3365
3366 // insert another auth token with the different values for the columns in the UNIQUE
3367 // constraint of the auth token table
3368 let auth_token3 = HardwareAuthToken {
3369 challenge: i64::MAX,
3370 userId: 201,
3371 authenticatorId: 200,
3372 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3373 timestamp: Timestamp { milliSeconds: 600 },
3374 mac: String::from("mac").into_bytes(),
3375 };
3376
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003377 db.insert_auth_token(&auth_token3);
3378 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003379 assert_eq!(auth_tokens_returned.len(), 2);
3380
3381 Ok(())
3382 }
3383
3384 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003385 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3386 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003387 }
3388
3389 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003390 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003391 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003392 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003393
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003394 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003395 let entries = get_keyentry(&db)?;
3396 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003397
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003398 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003399
3400 let entries_new = get_keyentry(&db)?;
3401 assert_eq!(entries, entries_new);
3402 Ok(())
3403 }
3404
3405 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003406 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003407 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3408 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003409 }
3410
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003411 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003412
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003413 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3414 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003415
3416 let entries = get_keyentry(&db)?;
3417 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003418 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3419 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003420
3421 // Test that we must pass in a valid Domain.
3422 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003423 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003424 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003425 );
3426 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003427 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003428 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003429 );
3430 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003431 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003432 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003433 );
3434
3435 Ok(())
3436 }
3437
Joel Galenson33c04ad2020-08-03 11:04:38 -07003438 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003439 fn test_add_unsigned_key() -> Result<()> {
3440 let mut db = new_test_db()?;
3441 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3442 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3443 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3444 db.create_attestation_key_entry(
3445 &public_key,
3446 &raw_public_key,
3447 &private_key,
3448 &KEYSTORE_UUID,
3449 )?;
3450 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3451 assert_eq!(keys.len(), 1);
3452 assert_eq!(keys[0], public_key);
3453 Ok(())
3454 }
3455
3456 #[test]
3457 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3458 let mut db = new_test_db()?;
3459 let expiration_date: i64 = 20;
3460 let namespace: i64 = 30;
3461 let base_byte: u8 = 1;
3462 let loaded_values =
3463 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3464 let chain =
3465 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Chris Wailes3877f292021-07-26 19:24:18 -07003466 assert!(chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003467 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003468 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003469 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3470 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003471 Ok(())
3472 }
3473
3474 #[test]
3475 fn test_get_attestation_pool_status() -> Result<()> {
3476 let mut db = new_test_db()?;
3477 let namespace: i64 = 30;
3478 load_attestation_key_pool(
3479 &mut db, 10, /* expiration */
3480 namespace, 0x01, /* base_byte */
3481 )?;
3482 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3483 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3484 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3485 assert_eq!(status.expiring, 0);
3486 assert_eq!(status.attested, 3);
3487 assert_eq!(status.unassigned, 0);
3488 assert_eq!(status.total, 3);
3489 assert_eq!(
3490 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3491 1
3492 );
3493 assert_eq!(
3494 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3495 2
3496 );
3497 assert_eq!(
3498 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3499 3
3500 );
3501 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3502 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3503 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3504 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003505 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003506 db.create_attestation_key_entry(
3507 &public_key,
3508 &raw_public_key,
3509 &private_key,
3510 &KEYSTORE_UUID,
3511 )?;
3512 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3513 assert_eq!(status.attested, 3);
3514 assert_eq!(status.unassigned, 0);
3515 assert_eq!(status.total, 4);
3516 db.store_signed_attestation_certificate_chain(
3517 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003518 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003519 &cert_chain,
3520 20,
3521 &KEYSTORE_UUID,
3522 )?;
3523 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3524 assert_eq!(status.attested, 4);
3525 assert_eq!(status.unassigned, 1);
3526 assert_eq!(status.total, 4);
3527 Ok(())
3528 }
3529
3530 #[test]
3531 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003532 let temp_dir =
3533 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3534 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003535 let expiration_date: i64 =
3536 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3537 let namespace: i64 = 30;
3538 let namespace_del1: i64 = 45;
3539 let namespace_del2: i64 = 60;
3540 let entry_values = load_attestation_key_pool(
3541 &mut db,
3542 expiration_date,
3543 namespace,
3544 0x01, /* base_byte */
3545 )?;
3546 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3547 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003548
3549 let blob_entry_row_count: u32 = db
3550 .conn
3551 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3552 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003553 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3554 // one key, one certificate chain, and one certificate.
3555 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003556
Max Bires2b2e6562020-09-22 11:22:36 -07003557 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3558
3559 let mut cert_chain =
3560 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003561 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003562 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003563 assert_eq!(entry_values.batch_cert, value.batch_cert);
3564 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003565 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003566
3567 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3568 Domain::APP,
3569 namespace_del1,
3570 &KEYSTORE_UUID,
3571 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003572 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003573 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3574 Domain::APP,
3575 namespace_del2,
3576 &KEYSTORE_UUID,
3577 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003578 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003579
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003580 // Give the garbage collector half a second to catch up.
3581 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003582
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003583 let blob_entry_row_count: u32 = db
3584 .conn
3585 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3586 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003587 // There shound be 3 blob entries left, because we deleted two of the attestation
3588 // key entries with three blobs each.
3589 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003590
Max Bires2b2e6562020-09-22 11:22:36 -07003591 Ok(())
3592 }
3593
3594 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003595 fn test_delete_all_attestation_keys() -> Result<()> {
3596 let mut db = new_test_db()?;
3597 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3598 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003599 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003600 let result = db.delete_all_attestation_keys()?;
3601
3602 // Give the garbage collector half a second to catch up.
3603 std::thread::sleep(Duration::from_millis(500));
3604
3605 // Attestation keys should be deleted, and the regular key should remain.
3606 assert_eq!(result, 2);
3607
3608 Ok(())
3609 }
3610
3611 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003612 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003613 fn extractor(
3614 ke: &KeyEntryRow,
3615 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3616 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003617 }
3618
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003619 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003620 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3621 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003622 let entries = get_keyentry(&db)?;
3623 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003624 assert_eq!(
3625 extractor(&entries[0]),
3626 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3627 );
3628 assert_eq!(
3629 extractor(&entries[1]),
3630 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3631 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003632
3633 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003634 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003635 let entries = get_keyentry(&db)?;
3636 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003637 assert_eq!(
3638 extractor(&entries[0]),
3639 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3640 );
3641 assert_eq!(
3642 extractor(&entries[1]),
3643 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3644 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003645
3646 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003647 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003648 let entries = get_keyentry(&db)?;
3649 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003650 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3651 assert_eq!(
3652 extractor(&entries[1]),
3653 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3654 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003655
3656 // Test that we must pass in a valid Domain.
3657 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003658 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003659 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003660 );
3661 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003662 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003663 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003664 );
3665 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003666 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003667 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003668 );
3669
3670 // Test that we correctly handle setting an alias for something that does not exist.
3671 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003672 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003673 "Expected to update a single entry but instead updated 0",
3674 );
3675 // Test that we correctly abort the transaction in this case.
3676 let entries = get_keyentry(&db)?;
3677 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003678 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3679 assert_eq!(
3680 extractor(&entries[1]),
3681 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3682 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003683
3684 Ok(())
3685 }
3686
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003687 #[test]
3688 fn test_grant_ungrant() -> Result<()> {
3689 const CALLER_UID: u32 = 15;
3690 const GRANTEE_UID: u32 = 12;
3691 const SELINUX_NAMESPACE: i64 = 7;
3692
3693 let mut db = new_test_db()?;
3694 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003695 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3696 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3697 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003698 )?;
3699 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003700 domain: super::Domain::APP,
3701 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003702 alias: Some("key".to_string()),
3703 blob: None,
3704 };
Janis Danisevskis39d57e72021-10-19 16:56:20 -07003705 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::Use, KeyPerm::GetInfo];
3706 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::Use];
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003707
3708 // Reset totally predictable random number generator in case we
3709 // are not the first test running on this thread.
3710 reset_random();
3711 let next_random = 0i64;
3712
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003713 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003714 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003715 assert_eq!(*a, PVEC1);
3716 assert_eq!(
3717 *k,
3718 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003719 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003720 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003721 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003722 alias: Some("key".to_string()),
3723 blob: None,
3724 }
3725 );
3726 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003727 })
3728 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003729
3730 assert_eq!(
3731 app_granted_key,
3732 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003733 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003734 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003735 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003736 alias: None,
3737 blob: None,
3738 }
3739 );
3740
3741 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003742 domain: super::Domain::SELINUX,
3743 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003744 alias: Some("yek".to_string()),
3745 blob: None,
3746 };
3747
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003748 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003749 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003750 assert_eq!(*a, PVEC1);
3751 assert_eq!(
3752 *k,
3753 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003754 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755 // namespace must be the supplied SELinux
3756 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003757 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003758 alias: Some("yek".to_string()),
3759 blob: None,
3760 }
3761 );
3762 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003763 })
3764 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003765
3766 assert_eq!(
3767 selinux_granted_key,
3768 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003769 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003770 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003771 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003772 alias: None,
3773 blob: None,
3774 }
3775 );
3776
3777 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003778 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003779 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003780 assert_eq!(*a, PVEC2);
3781 assert_eq!(
3782 *k,
3783 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003784 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003785 // namespace must be the supplied SELinux
3786 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003787 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003788 alias: Some("yek".to_string()),
3789 blob: None,
3790 }
3791 );
3792 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003793 })
3794 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003795
3796 assert_eq!(
3797 selinux_granted_key,
3798 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003799 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003800 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003801 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003802 alias: None,
3803 blob: None,
3804 }
3805 );
3806
3807 {
3808 // Limiting scope of stmt, because it borrows db.
3809 let mut stmt = db
3810 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003811 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003812 let mut rows =
3813 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3814 Ok((
3815 row.get(0)?,
3816 row.get(1)?,
3817 row.get(2)?,
3818 KeyPermSet::from(row.get::<_, i32>(3)?),
3819 ))
3820 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003821
3822 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003823 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003824 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003825 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003826 assert!(rows.next().is_none());
3827 }
3828
3829 debug_dump_keyentry_table(&mut db)?;
3830 println!("app_key {:?}", app_key);
3831 println!("selinux_key {:?}", selinux_key);
3832
Janis Danisevskis66784c42021-01-27 08:40:25 -08003833 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3834 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003835
3836 Ok(())
3837 }
3838
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003839 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003840 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3841 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3842
3843 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003844 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003845 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003846 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003847 let mut blob_metadata = BlobMetaData::new();
3848 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3849 db.set_blob(
3850 &key_id,
3851 SubComponentType::KEY_BLOB,
3852 Some(TEST_KEY_BLOB),
3853 Some(&blob_metadata),
3854 )?;
3855 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3856 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003857 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003858
3859 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003860 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003861 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003862 )?;
3863 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003864 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3865 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003866 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003867 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003868 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003869 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003870 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003871 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003872 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003873
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003874 drop(rows);
3875 drop(stmt);
3876
3877 assert_eq!(
3878 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3879 BlobMetaData::load_from_db(id, tx).no_gc()
3880 })
3881 .expect("Should find blob metadata."),
3882 blob_metadata
3883 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003884 Ok(())
3885 }
3886
3887 static TEST_ALIAS: &str = "my super duper key";
3888
3889 #[test]
3890 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3891 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003892 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003893 .context("test_insert_and_load_full_keyentry_domain_app")?
3894 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003895 let (_key_guard, key_entry) = db
3896 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003897 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003898 domain: Domain::APP,
3899 nspace: 0,
3900 alias: Some(TEST_ALIAS.to_string()),
3901 blob: None,
3902 },
3903 KeyType::Client,
3904 KeyEntryLoadBits::BOTH,
3905 1,
3906 |_k, _av| Ok(()),
3907 )
3908 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003909 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003910
3911 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003912 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003913 domain: Domain::APP,
3914 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003915 alias: Some(TEST_ALIAS.to_string()),
3916 blob: None,
3917 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003918 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003919 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003920 |_, _| Ok(()),
3921 )
3922 .unwrap();
3923
3924 assert_eq!(
3925 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3926 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003927 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003928 domain: Domain::APP,
3929 nspace: 0,
3930 alias: Some(TEST_ALIAS.to_string()),
3931 blob: None,
3932 },
3933 KeyType::Client,
3934 KeyEntryLoadBits::NONE,
3935 1,
3936 |_k, _av| Ok(()),
3937 )
3938 .unwrap_err()
3939 .root_cause()
3940 .downcast_ref::<KsError>()
3941 );
3942
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003943 Ok(())
3944 }
3945
3946 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003947 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3948 let mut db = new_test_db()?;
3949
3950 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003951 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003952 domain: Domain::APP,
3953 nspace: 1,
3954 alias: Some(TEST_ALIAS.to_string()),
3955 blob: None,
3956 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003957 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003958 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003959 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003960 )
3961 .expect("Trying to insert cert.");
3962
3963 let (_key_guard, mut key_entry) = db
3964 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003965 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003966 domain: Domain::APP,
3967 nspace: 1,
3968 alias: Some(TEST_ALIAS.to_string()),
3969 blob: None,
3970 },
3971 KeyType::Client,
3972 KeyEntryLoadBits::PUBLIC,
3973 1,
3974 |_k, _av| Ok(()),
3975 )
3976 .expect("Trying to read certificate entry.");
3977
3978 assert!(key_entry.pure_cert());
3979 assert!(key_entry.cert().is_none());
3980 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3981
3982 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003983 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003984 domain: Domain::APP,
3985 nspace: 1,
3986 alias: Some(TEST_ALIAS.to_string()),
3987 blob: None,
3988 },
3989 KeyType::Client,
3990 1,
3991 |_, _| Ok(()),
3992 )
3993 .unwrap();
3994
3995 assert_eq!(
3996 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3997 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003998 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003999 domain: Domain::APP,
4000 nspace: 1,
4001 alias: Some(TEST_ALIAS.to_string()),
4002 blob: None,
4003 },
4004 KeyType::Client,
4005 KeyEntryLoadBits::NONE,
4006 1,
4007 |_k, _av| Ok(()),
4008 )
4009 .unwrap_err()
4010 .root_cause()
4011 .downcast_ref::<KsError>()
4012 );
4013
4014 Ok(())
4015 }
4016
4017 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004018 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4019 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004020 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004021 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4022 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004023 let (_key_guard, key_entry) = db
4024 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004025 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004026 domain: Domain::SELINUX,
4027 nspace: 1,
4028 alias: Some(TEST_ALIAS.to_string()),
4029 blob: None,
4030 },
4031 KeyType::Client,
4032 KeyEntryLoadBits::BOTH,
4033 1,
4034 |_k, _av| Ok(()),
4035 )
4036 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004037 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004038
4039 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004040 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004041 domain: Domain::SELINUX,
4042 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004043 alias: Some(TEST_ALIAS.to_string()),
4044 blob: None,
4045 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004046 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004047 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004048 |_, _| Ok(()),
4049 )
4050 .unwrap();
4051
4052 assert_eq!(
4053 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4054 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004055 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004056 domain: Domain::SELINUX,
4057 nspace: 1,
4058 alias: Some(TEST_ALIAS.to_string()),
4059 blob: None,
4060 },
4061 KeyType::Client,
4062 KeyEntryLoadBits::NONE,
4063 1,
4064 |_k, _av| Ok(()),
4065 )
4066 .unwrap_err()
4067 .root_cause()
4068 .downcast_ref::<KsError>()
4069 );
4070
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004071 Ok(())
4072 }
4073
4074 #[test]
4075 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4076 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004077 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004078 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4079 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004080 let (_, key_entry) = db
4081 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004082 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004083 KeyType::Client,
4084 KeyEntryLoadBits::BOTH,
4085 1,
4086 |_k, _av| Ok(()),
4087 )
4088 .unwrap();
4089
Qi Wub9433b52020-12-01 14:52:46 +08004090 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004091
4092 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004093 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004094 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004095 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004096 |_, _| Ok(()),
4097 )
4098 .unwrap();
4099
4100 assert_eq!(
4101 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4102 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004103 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004104 KeyType::Client,
4105 KeyEntryLoadBits::NONE,
4106 1,
4107 |_k, _av| Ok(()),
4108 )
4109 .unwrap_err()
4110 .root_cause()
4111 .downcast_ref::<KsError>()
4112 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004113
4114 Ok(())
4115 }
4116
4117 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004118 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4119 let mut db = new_test_db()?;
4120 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4121 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4122 .0;
4123 // Update the usage count of the limited use key.
4124 db.check_and_update_key_usage_count(key_id)?;
4125
4126 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004127 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004128 KeyType::Client,
4129 KeyEntryLoadBits::BOTH,
4130 1,
4131 |_k, _av| Ok(()),
4132 )?;
4133
4134 // The usage count is decremented now.
4135 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4136
4137 Ok(())
4138 }
4139
4140 #[test]
4141 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4142 let mut db = new_test_db()?;
4143 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4144 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4145 .0;
4146 // Update the usage count of the limited use key.
4147 db.check_and_update_key_usage_count(key_id).expect(concat!(
4148 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4149 "This should succeed."
4150 ));
4151
4152 // Try to update the exhausted limited use key.
4153 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4154 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4155 "This should fail."
4156 ));
4157 assert_eq!(
4158 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4159 e.root_cause().downcast_ref::<KsError>().unwrap()
4160 );
4161
4162 Ok(())
4163 }
4164
4165 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004166 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4167 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004168 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004169 .context("test_insert_and_load_full_keyentry_from_grant")?
4170 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004171
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004172 let granted_key = db
4173 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004174 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004175 domain: Domain::APP,
4176 nspace: 0,
4177 alias: Some(TEST_ALIAS.to_string()),
4178 blob: None,
4179 },
4180 1,
4181 2,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004182 key_perm_set![KeyPerm::Use],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004183 |_k, _av| Ok(()),
4184 )
4185 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004186
4187 debug_dump_grant_table(&mut db)?;
4188
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004189 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004190 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4191 assert_eq!(Domain::GRANT, k.domain);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004192 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis66784c42021-01-27 08:40:25 -08004193 Ok(())
4194 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004195 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004196
Qi Wub9433b52020-12-01 14:52:46 +08004197 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004198
Janis Danisevskis66784c42021-01-27 08:40:25 -08004199 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004200
4201 assert_eq!(
4202 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4203 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004204 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004205 KeyType::Client,
4206 KeyEntryLoadBits::NONE,
4207 2,
4208 |_k, _av| Ok(()),
4209 )
4210 .unwrap_err()
4211 .root_cause()
4212 .downcast_ref::<KsError>()
4213 );
4214
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004215 Ok(())
4216 }
4217
Janis Danisevskis45760022021-01-19 16:34:10 -08004218 // This test attempts to load a key by key id while the caller is not the owner
4219 // but a grant exists for the given key and the caller.
4220 #[test]
4221 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4222 let mut db = new_test_db()?;
4223 const OWNER_UID: u32 = 1u32;
4224 const GRANTEE_UID: u32 = 2u32;
4225 const SOMEONE_ELSE_UID: u32 = 3u32;
4226 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4227 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4228 .0;
4229
4230 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004231 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004232 domain: Domain::APP,
4233 nspace: 0,
4234 alias: Some(TEST_ALIAS.to_string()),
4235 blob: None,
4236 },
4237 OWNER_UID,
4238 GRANTEE_UID,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004239 key_perm_set![KeyPerm::Use],
Janis Danisevskis45760022021-01-19 16:34:10 -08004240 |_k, _av| Ok(()),
4241 )
4242 .unwrap();
4243
4244 debug_dump_grant_table(&mut db)?;
4245
4246 let id_descriptor =
4247 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4248
4249 let (_, key_entry) = db
4250 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004251 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004252 KeyType::Client,
4253 KeyEntryLoadBits::BOTH,
4254 GRANTEE_UID,
4255 |k, av| {
4256 assert_eq!(Domain::APP, k.domain);
4257 assert_eq!(OWNER_UID as i64, k.nspace);
Janis Danisevskis39d57e72021-10-19 16:56:20 -07004258 assert!(av.unwrap().includes(KeyPerm::Use));
Janis Danisevskis45760022021-01-19 16:34:10 -08004259 Ok(())
4260 },
4261 )
4262 .unwrap();
4263
4264 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4265
4266 let (_, key_entry) = db
4267 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004268 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004269 KeyType::Client,
4270 KeyEntryLoadBits::BOTH,
4271 SOMEONE_ELSE_UID,
4272 |k, av| {
4273 assert_eq!(Domain::APP, k.domain);
4274 assert_eq!(OWNER_UID as i64, k.nspace);
4275 assert!(av.is_none());
4276 Ok(())
4277 },
4278 )
4279 .unwrap();
4280
4281 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4282
Janis Danisevskis66784c42021-01-27 08:40:25 -08004283 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004284
4285 assert_eq!(
4286 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4287 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004288 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004289 KeyType::Client,
4290 KeyEntryLoadBits::NONE,
4291 GRANTEE_UID,
4292 |_k, _av| Ok(()),
4293 )
4294 .unwrap_err()
4295 .root_cause()
4296 .downcast_ref::<KsError>()
4297 );
4298
4299 Ok(())
4300 }
4301
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004302 // Creates a key migrates it to a different location and then tries to access it by the old
4303 // and new location.
4304 #[test]
4305 fn test_migrate_key_app_to_app() -> Result<()> {
4306 let mut db = new_test_db()?;
4307 const SOURCE_UID: u32 = 1u32;
4308 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004309 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4310 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004311 let key_id_guard =
4312 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4313 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4314
4315 let source_descriptor: KeyDescriptor = KeyDescriptor {
4316 domain: Domain::APP,
4317 nspace: -1,
4318 alias: Some(SOURCE_ALIAS.to_string()),
4319 blob: None,
4320 };
4321
4322 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4323 domain: Domain::APP,
4324 nspace: -1,
4325 alias: Some(DESTINATION_ALIAS.to_string()),
4326 blob: None,
4327 };
4328
4329 let key_id = key_id_guard.id();
4330
4331 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4332 Ok(())
4333 })
4334 .unwrap();
4335
4336 let (_, key_entry) = db
4337 .load_key_entry(
4338 &destination_descriptor,
4339 KeyType::Client,
4340 KeyEntryLoadBits::BOTH,
4341 DESTINATION_UID,
4342 |k, av| {
4343 assert_eq!(Domain::APP, k.domain);
4344 assert_eq!(DESTINATION_UID as i64, k.nspace);
4345 assert!(av.is_none());
4346 Ok(())
4347 },
4348 )
4349 .unwrap();
4350
4351 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4352
4353 assert_eq!(
4354 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4355 db.load_key_entry(
4356 &source_descriptor,
4357 KeyType::Client,
4358 KeyEntryLoadBits::NONE,
4359 SOURCE_UID,
4360 |_k, _av| Ok(()),
4361 )
4362 .unwrap_err()
4363 .root_cause()
4364 .downcast_ref::<KsError>()
4365 );
4366
4367 Ok(())
4368 }
4369
4370 // Creates a key migrates it to a different location and then tries to access it by the old
4371 // and new location.
4372 #[test]
4373 fn test_migrate_key_app_to_selinux() -> Result<()> {
4374 let mut db = new_test_db()?;
4375 const SOURCE_UID: u32 = 1u32;
4376 const DESTINATION_UID: u32 = 2u32;
4377 const DESTINATION_NAMESPACE: i64 = 1000i64;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004378 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4379 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004380 let key_id_guard =
4381 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4382 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4383
4384 let source_descriptor: KeyDescriptor = KeyDescriptor {
4385 domain: Domain::APP,
4386 nspace: -1,
4387 alias: Some(SOURCE_ALIAS.to_string()),
4388 blob: None,
4389 };
4390
4391 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4392 domain: Domain::SELINUX,
4393 nspace: DESTINATION_NAMESPACE,
4394 alias: Some(DESTINATION_ALIAS.to_string()),
4395 blob: None,
4396 };
4397
4398 let key_id = key_id_guard.id();
4399
4400 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4401 Ok(())
4402 })
4403 .unwrap();
4404
4405 let (_, key_entry) = db
4406 .load_key_entry(
4407 &destination_descriptor,
4408 KeyType::Client,
4409 KeyEntryLoadBits::BOTH,
4410 DESTINATION_UID,
4411 |k, av| {
4412 assert_eq!(Domain::SELINUX, k.domain);
4413 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4414 assert!(av.is_none());
4415 Ok(())
4416 },
4417 )
4418 .unwrap();
4419
4420 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4421
4422 assert_eq!(
4423 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4424 db.load_key_entry(
4425 &source_descriptor,
4426 KeyType::Client,
4427 KeyEntryLoadBits::NONE,
4428 SOURCE_UID,
4429 |_k, _av| Ok(()),
4430 )
4431 .unwrap_err()
4432 .root_cause()
4433 .downcast_ref::<KsError>()
4434 );
4435
4436 Ok(())
4437 }
4438
4439 // Creates two keys and tries to migrate the first to the location of the second which
4440 // is expected to fail.
4441 #[test]
4442 fn test_migrate_key_destination_occupied() -> Result<()> {
4443 let mut db = new_test_db()?;
4444 const SOURCE_UID: u32 = 1u32;
4445 const DESTINATION_UID: u32 = 2u32;
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004446 static SOURCE_ALIAS: &str = "SOURCE_ALIAS";
4447 static DESTINATION_ALIAS: &str = "DESTINATION_ALIAS";
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004448 let key_id_guard =
4449 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4450 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4451 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4452 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4453
4454 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4455 domain: Domain::APP,
4456 nspace: -1,
4457 alias: Some(DESTINATION_ALIAS.to_string()),
4458 blob: None,
4459 };
4460
4461 assert_eq!(
4462 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4463 db.migrate_key_namespace(
4464 key_id_guard,
4465 &destination_descriptor,
4466 DESTINATION_UID,
4467 |_k| Ok(())
4468 )
4469 .unwrap_err()
4470 .root_cause()
4471 .downcast_ref::<KsError>()
4472 );
4473
4474 Ok(())
4475 }
4476
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004477 #[test]
4478 fn test_upgrade_0_to_1() {
Chris Wailesd5aaaef2021-07-27 16:04:33 -07004479 const ALIAS1: &str = "test_upgrade_0_to_1_1";
4480 const ALIAS2: &str = "test_upgrade_0_to_1_2";
4481 const ALIAS3: &str = "test_upgrade_0_to_1_3";
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004482 const UID: u32 = 33;
4483 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4484 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4485 let key_id_untouched1 =
4486 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4487 let key_id_untouched2 =
4488 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4489 let key_id_deleted =
4490 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4491
4492 let (_, key_entry) = db
4493 .load_key_entry(
4494 &KeyDescriptor {
4495 domain: Domain::APP,
4496 nspace: -1,
4497 alias: Some(ALIAS1.to_string()),
4498 blob: None,
4499 },
4500 KeyType::Client,
4501 KeyEntryLoadBits::BOTH,
4502 UID,
4503 |k, av| {
4504 assert_eq!(Domain::APP, k.domain);
4505 assert_eq!(UID as i64, k.nspace);
4506 assert!(av.is_none());
4507 Ok(())
4508 },
4509 )
4510 .unwrap();
4511 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4512 let (_, key_entry) = db
4513 .load_key_entry(
4514 &KeyDescriptor {
4515 domain: Domain::APP,
4516 nspace: -1,
4517 alias: Some(ALIAS2.to_string()),
4518 blob: None,
4519 },
4520 KeyType::Client,
4521 KeyEntryLoadBits::BOTH,
4522 UID,
4523 |k, av| {
4524 assert_eq!(Domain::APP, k.domain);
4525 assert_eq!(UID as i64, k.nspace);
4526 assert!(av.is_none());
4527 Ok(())
4528 },
4529 )
4530 .unwrap();
4531 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4532 let (_, key_entry) = db
4533 .load_key_entry(
4534 &KeyDescriptor {
4535 domain: Domain::APP,
4536 nspace: -1,
4537 alias: Some(ALIAS3.to_string()),
4538 blob: None,
4539 },
4540 KeyType::Client,
4541 KeyEntryLoadBits::BOTH,
4542 UID,
4543 |k, av| {
4544 assert_eq!(Domain::APP, k.domain);
4545 assert_eq!(UID as i64, k.nspace);
4546 assert!(av.is_none());
4547 Ok(())
4548 },
4549 )
4550 .unwrap();
4551 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4552
4553 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4554 KeystoreDB::from_0_to_1(tx).no_gc()
4555 })
4556 .unwrap();
4557
4558 let (_, key_entry) = db
4559 .load_key_entry(
4560 &KeyDescriptor {
4561 domain: Domain::APP,
4562 nspace: -1,
4563 alias: Some(ALIAS1.to_string()),
4564 blob: None,
4565 },
4566 KeyType::Client,
4567 KeyEntryLoadBits::BOTH,
4568 UID,
4569 |k, av| {
4570 assert_eq!(Domain::APP, k.domain);
4571 assert_eq!(UID as i64, k.nspace);
4572 assert!(av.is_none());
4573 Ok(())
4574 },
4575 )
4576 .unwrap();
4577 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4578 let (_, key_entry) = db
4579 .load_key_entry(
4580 &KeyDescriptor {
4581 domain: Domain::APP,
4582 nspace: -1,
4583 alias: Some(ALIAS2.to_string()),
4584 blob: None,
4585 },
4586 KeyType::Client,
4587 KeyEntryLoadBits::BOTH,
4588 UID,
4589 |k, av| {
4590 assert_eq!(Domain::APP, k.domain);
4591 assert_eq!(UID as i64, k.nspace);
4592 assert!(av.is_none());
4593 Ok(())
4594 },
4595 )
4596 .unwrap();
4597 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4598 assert_eq!(
4599 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4600 db.load_key_entry(
4601 &KeyDescriptor {
4602 domain: Domain::APP,
4603 nspace: -1,
4604 alias: Some(ALIAS3.to_string()),
4605 blob: None,
4606 },
4607 KeyType::Client,
4608 KeyEntryLoadBits::BOTH,
4609 UID,
4610 |k, av| {
4611 assert_eq!(Domain::APP, k.domain);
4612 assert_eq!(UID as i64, k.nspace);
4613 assert!(av.is_none());
4614 Ok(())
4615 },
4616 )
4617 .unwrap_err()
4618 .root_cause()
4619 .downcast_ref::<KsError>()
4620 );
4621 }
4622
Janis Danisevskisaec14592020-11-12 09:41:49 -08004623 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4624
Janis Danisevskisaec14592020-11-12 09:41:49 -08004625 #[test]
4626 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4627 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004628 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4629 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004630 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004631 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004632 .context("test_insert_and_load_full_keyentry_domain_app")?
4633 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004634 let (_key_guard, key_entry) = db
4635 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004636 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004637 domain: Domain::APP,
4638 nspace: 0,
4639 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4640 blob: None,
4641 },
4642 KeyType::Client,
4643 KeyEntryLoadBits::BOTH,
4644 33,
4645 |_k, _av| Ok(()),
4646 )
4647 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004648 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004649 let state = Arc::new(AtomicU8::new(1));
4650 let state2 = state.clone();
4651
4652 // Spawning a second thread that attempts to acquire the key id lock
4653 // for the same key as the primary thread. The primary thread then
4654 // waits, thereby forcing the secondary thread into the second stage
4655 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4656 // The test succeeds if the secondary thread observes the transition
4657 // of `state` from 1 to 2, despite having a whole second to overtake
4658 // the primary thread.
4659 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004660 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004661 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004662 assert!(db
4663 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004664 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004665 domain: Domain::APP,
4666 nspace: 0,
4667 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4668 blob: None,
4669 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004670 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004671 KeyEntryLoadBits::BOTH,
4672 33,
4673 |_k, _av| Ok(()),
4674 )
4675 .is_ok());
4676 // We should only see a 2 here because we can only return
4677 // from load_key_entry when the `_key_guard` expires,
4678 // which happens at the end of the scope.
4679 assert_eq!(2, state2.load(Ordering::Relaxed));
4680 });
4681
4682 thread::sleep(std::time::Duration::from_millis(1000));
4683
4684 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4685
4686 // Return the handle from this scope so we can join with the
4687 // secondary thread after the key id lock has expired.
4688 handle
4689 // This is where the `_key_guard` goes out of scope,
4690 // which is the reason for concurrent load_key_entry on the same key
4691 // to unblock.
4692 };
4693 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4694 // main test thread. We will not see failing asserts in secondary threads otherwise.
4695 handle.join().unwrap();
4696 Ok(())
4697 }
4698
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004699 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004700 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004701 let temp_dir =
4702 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4703
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004704 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4705 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004706
4707 let _tx1 = db1
4708 .conn
4709 .transaction_with_behavior(TransactionBehavior::Immediate)
4710 .expect("Failed to create first transaction.");
4711
4712 let error = db2
4713 .conn
4714 .transaction_with_behavior(TransactionBehavior::Immediate)
4715 .context("Transaction begin failed.")
4716 .expect_err("This should fail.");
4717 let root_cause = error.root_cause();
4718 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4719 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4720 {
4721 return;
4722 }
4723 panic!(
4724 "Unexpected error {:?} \n{:?} \n{:?}",
4725 error,
4726 root_cause,
4727 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4728 )
4729 }
4730
4731 #[cfg(disabled)]
4732 #[test]
4733 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4734 let temp_dir = Arc::new(
4735 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4736 .expect("Failed to create temp dir."),
4737 );
4738
4739 let test_begin = Instant::now();
4740
Janis Danisevskis66784c42021-01-27 08:40:25 -08004741 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004742 let mut db =
4743 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004744 const OPEN_DB_COUNT: u32 = 50u32;
4745
4746 let mut actual_key_count = KEY_COUNT;
4747 // First insert KEY_COUNT keys.
4748 for count in 0..KEY_COUNT {
4749 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4750 actual_key_count = count;
4751 break;
4752 }
4753 let alias = format!("test_alias_{}", count);
4754 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4755 .expect("Failed to make key entry.");
4756 }
4757
4758 // Insert more keys from a different thread and into a different namespace.
4759 let temp_dir1 = temp_dir.clone();
4760 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004761 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4762 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004763
4764 for count in 0..actual_key_count {
4765 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4766 return;
4767 }
4768 let alias = format!("test_alias_{}", count);
4769 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4770 .expect("Failed to make key entry.");
4771 }
4772
4773 // then unbind them again.
4774 for count in 0..actual_key_count {
4775 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4776 return;
4777 }
4778 let key = KeyDescriptor {
4779 domain: Domain::APP,
4780 nspace: -1,
4781 alias: Some(format!("test_alias_{}", count)),
4782 blob: None,
4783 };
4784 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4785 }
4786 });
4787
4788 // And start unbinding the first set of keys.
4789 let temp_dir2 = temp_dir.clone();
4790 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004791 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4792 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004793
4794 for count in 0..actual_key_count {
4795 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4796 return;
4797 }
4798 let key = KeyDescriptor {
4799 domain: Domain::APP,
4800 nspace: -1,
4801 alias: Some(format!("test_alias_{}", count)),
4802 blob: None,
4803 };
4804 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4805 }
4806 });
4807
Janis Danisevskis66784c42021-01-27 08:40:25 -08004808 // While a lot of inserting and deleting is going on we have to open database connections
4809 // successfully and use them.
4810 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4811 // out of scope.
4812 #[allow(clippy::redundant_clone)]
4813 let temp_dir4 = temp_dir.clone();
4814 let handle4 = thread::spawn(move || {
4815 for count in 0..OPEN_DB_COUNT {
4816 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4817 return;
4818 }
Seth Moore444b51a2021-06-11 09:49:49 -07004819 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4820 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004821
4822 let alias = format!("test_alias_{}", count);
4823 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4824 .expect("Failed to make key entry.");
4825 let key = KeyDescriptor {
4826 domain: Domain::APP,
4827 nspace: -1,
4828 alias: Some(alias),
4829 blob: None,
4830 };
4831 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4832 }
4833 });
4834
4835 handle1.join().expect("Thread 1 panicked.");
4836 handle2.join().expect("Thread 2 panicked.");
4837 handle4.join().expect("Thread 4 panicked.");
4838
Janis Danisevskis66784c42021-01-27 08:40:25 -08004839 Ok(())
4840 }
4841
4842 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004843 fn list() -> Result<()> {
4844 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004845 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004846 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4847 (Domain::APP, 1, "test1"),
4848 (Domain::APP, 1, "test2"),
4849 (Domain::APP, 1, "test3"),
4850 (Domain::APP, 1, "test4"),
4851 (Domain::APP, 1, "test5"),
4852 (Domain::APP, 1, "test6"),
4853 (Domain::APP, 1, "test7"),
4854 (Domain::APP, 2, "test1"),
4855 (Domain::APP, 2, "test2"),
4856 (Domain::APP, 2, "test3"),
4857 (Domain::APP, 2, "test4"),
4858 (Domain::APP, 2, "test5"),
4859 (Domain::APP, 2, "test6"),
4860 (Domain::APP, 2, "test8"),
4861 (Domain::SELINUX, 100, "test1"),
4862 (Domain::SELINUX, 100, "test2"),
4863 (Domain::SELINUX, 100, "test3"),
4864 (Domain::SELINUX, 100, "test4"),
4865 (Domain::SELINUX, 100, "test5"),
4866 (Domain::SELINUX, 100, "test6"),
4867 (Domain::SELINUX, 100, "test9"),
4868 ];
4869
4870 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4871 .iter()
4872 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004873 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4874 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004875 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4876 });
4877 (entry.id(), *ns)
4878 })
4879 .collect();
4880
4881 for (domain, namespace) in
4882 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4883 {
4884 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4885 .iter()
4886 .filter_map(|(domain, ns, alias)| match ns {
4887 ns if *ns == *namespace => Some(KeyDescriptor {
4888 domain: *domain,
4889 nspace: *ns,
4890 alias: Some(alias.to_string()),
4891 blob: None,
4892 }),
4893 _ => None,
4894 })
4895 .collect();
4896 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07004897 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004898 list_result.sort();
4899 assert_eq!(list_o_descriptors, list_result);
4900
4901 let mut list_o_ids: Vec<i64> = list_o_descriptors
4902 .into_iter()
4903 .map(|d| {
4904 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004905 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004906 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004907 KeyType::Client,
4908 KeyEntryLoadBits::NONE,
4909 *namespace as u32,
4910 |_, _| Ok(()),
4911 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004912 .unwrap();
4913 entry.id()
4914 })
4915 .collect();
4916 list_o_ids.sort_unstable();
4917 let mut loaded_entries: Vec<i64> = list_o_keys
4918 .iter()
4919 .filter_map(|(id, ns)| match ns {
4920 ns if *ns == *namespace => Some(*id),
4921 _ => None,
4922 })
4923 .collect();
4924 loaded_entries.sort_unstable();
4925 assert_eq!(list_o_ids, loaded_entries);
4926 }
Janis Danisevskis18313832021-05-17 13:30:32 -07004927 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004928
4929 Ok(())
4930 }
4931
Joel Galenson0891bc12020-07-20 10:37:03 -07004932 // Helpers
4933
4934 // Checks that the given result is an error containing the given string.
4935 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4936 let error_str = format!(
4937 "{:#?}",
4938 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4939 );
4940 assert!(
4941 error_str.contains(target),
4942 "The string \"{}\" should contain \"{}\"",
4943 error_str,
4944 target
4945 );
4946 }
4947
Joel Galenson2aab4432020-07-22 15:27:57 -07004948 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004949 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004950 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004951 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004952 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004953 namespace: Option<i64>,
4954 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004955 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004956 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004957 }
4958
4959 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4960 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004961 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004962 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004963 Ok(KeyEntryRow {
4964 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004965 key_type: row.get(1)?,
Chris Wailes3583a512021-07-22 16:22:51 -07004966 domain: row.get::<_, Option<_>>(2)?.map(Domain),
Joel Galenson0891bc12020-07-20 10:37:03 -07004967 namespace: row.get(3)?,
4968 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004969 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004970 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004971 })
4972 })?
4973 .map(|r| r.context("Could not read keyentry row."))
4974 .collect::<Result<Vec<_>>>()
4975 }
4976
Max Biresb2e1d032021-02-08 21:35:05 -08004977 struct RemoteProvValues {
4978 cert_chain: Vec<u8>,
4979 priv_key: Vec<u8>,
4980 batch_cert: Vec<u8>,
4981 }
4982
Max Bires2b2e6562020-09-22 11:22:36 -07004983 fn load_attestation_key_pool(
4984 db: &mut KeystoreDB,
4985 expiration_date: i64,
4986 namespace: i64,
4987 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004988 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004989 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4990 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4991 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4992 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004993 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004994 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4995 db.store_signed_attestation_certificate_chain(
4996 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004997 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004998 &cert_chain,
4999 expiration_date,
5000 &KEYSTORE_UUID,
5001 )?;
5002 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005003 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005004 }
5005
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005006 // Note: The parameters and SecurityLevel associations are nonsensical. This
5007 // collection is only used to check if the parameters are preserved as expected by the
5008 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005009 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5010 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005011 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5012 KeyParameter::new(
5013 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5014 SecurityLevel::TRUSTED_ENVIRONMENT,
5015 ),
5016 KeyParameter::new(
5017 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5018 SecurityLevel::TRUSTED_ENVIRONMENT,
5019 ),
5020 KeyParameter::new(
5021 KeyParameterValue::Algorithm(Algorithm::RSA),
5022 SecurityLevel::TRUSTED_ENVIRONMENT,
5023 ),
5024 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5025 KeyParameter::new(
5026 KeyParameterValue::BlockMode(BlockMode::ECB),
5027 SecurityLevel::TRUSTED_ENVIRONMENT,
5028 ),
5029 KeyParameter::new(
5030 KeyParameterValue::BlockMode(BlockMode::GCM),
5031 SecurityLevel::TRUSTED_ENVIRONMENT,
5032 ),
5033 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5034 KeyParameter::new(
5035 KeyParameterValue::Digest(Digest::MD5),
5036 SecurityLevel::TRUSTED_ENVIRONMENT,
5037 ),
5038 KeyParameter::new(
5039 KeyParameterValue::Digest(Digest::SHA_2_224),
5040 SecurityLevel::TRUSTED_ENVIRONMENT,
5041 ),
5042 KeyParameter::new(
5043 KeyParameterValue::Digest(Digest::SHA_2_256),
5044 SecurityLevel::STRONGBOX,
5045 ),
5046 KeyParameter::new(
5047 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5048 SecurityLevel::TRUSTED_ENVIRONMENT,
5049 ),
5050 KeyParameter::new(
5051 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5052 SecurityLevel::TRUSTED_ENVIRONMENT,
5053 ),
5054 KeyParameter::new(
5055 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5056 SecurityLevel::STRONGBOX,
5057 ),
5058 KeyParameter::new(
5059 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5060 SecurityLevel::TRUSTED_ENVIRONMENT,
5061 ),
5062 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5063 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5064 KeyParameter::new(
5065 KeyParameterValue::EcCurve(EcCurve::P_224),
5066 SecurityLevel::TRUSTED_ENVIRONMENT,
5067 ),
5068 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5069 KeyParameter::new(
5070 KeyParameterValue::EcCurve(EcCurve::P_384),
5071 SecurityLevel::TRUSTED_ENVIRONMENT,
5072 ),
5073 KeyParameter::new(
5074 KeyParameterValue::EcCurve(EcCurve::P_521),
5075 SecurityLevel::TRUSTED_ENVIRONMENT,
5076 ),
5077 KeyParameter::new(
5078 KeyParameterValue::RSAPublicExponent(3),
5079 SecurityLevel::TRUSTED_ENVIRONMENT,
5080 ),
5081 KeyParameter::new(
5082 KeyParameterValue::IncludeUniqueID,
5083 SecurityLevel::TRUSTED_ENVIRONMENT,
5084 ),
5085 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5086 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5087 KeyParameter::new(
5088 KeyParameterValue::ActiveDateTime(1234567890),
5089 SecurityLevel::STRONGBOX,
5090 ),
5091 KeyParameter::new(
5092 KeyParameterValue::OriginationExpireDateTime(1234567890),
5093 SecurityLevel::TRUSTED_ENVIRONMENT,
5094 ),
5095 KeyParameter::new(
5096 KeyParameterValue::UsageExpireDateTime(1234567890),
5097 SecurityLevel::TRUSTED_ENVIRONMENT,
5098 ),
5099 KeyParameter::new(
5100 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5101 SecurityLevel::TRUSTED_ENVIRONMENT,
5102 ),
5103 KeyParameter::new(
5104 KeyParameterValue::MaxUsesPerBoot(1234567890),
5105 SecurityLevel::TRUSTED_ENVIRONMENT,
5106 ),
5107 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5108 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5109 KeyParameter::new(
5110 KeyParameterValue::NoAuthRequired,
5111 SecurityLevel::TRUSTED_ENVIRONMENT,
5112 ),
5113 KeyParameter::new(
5114 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5115 SecurityLevel::TRUSTED_ENVIRONMENT,
5116 ),
5117 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5118 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5119 KeyParameter::new(
5120 KeyParameterValue::TrustedUserPresenceRequired,
5121 SecurityLevel::TRUSTED_ENVIRONMENT,
5122 ),
5123 KeyParameter::new(
5124 KeyParameterValue::TrustedConfirmationRequired,
5125 SecurityLevel::TRUSTED_ENVIRONMENT,
5126 ),
5127 KeyParameter::new(
5128 KeyParameterValue::UnlockedDeviceRequired,
5129 SecurityLevel::TRUSTED_ENVIRONMENT,
5130 ),
5131 KeyParameter::new(
5132 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5133 SecurityLevel::SOFTWARE,
5134 ),
5135 KeyParameter::new(
5136 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5137 SecurityLevel::SOFTWARE,
5138 ),
5139 KeyParameter::new(
5140 KeyParameterValue::CreationDateTime(12345677890),
5141 SecurityLevel::SOFTWARE,
5142 ),
5143 KeyParameter::new(
5144 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5145 SecurityLevel::TRUSTED_ENVIRONMENT,
5146 ),
5147 KeyParameter::new(
5148 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5149 SecurityLevel::TRUSTED_ENVIRONMENT,
5150 ),
5151 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5152 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5153 KeyParameter::new(
5154 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5155 SecurityLevel::SOFTWARE,
5156 ),
5157 KeyParameter::new(
5158 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5159 SecurityLevel::TRUSTED_ENVIRONMENT,
5160 ),
5161 KeyParameter::new(
5162 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5163 SecurityLevel::TRUSTED_ENVIRONMENT,
5164 ),
5165 KeyParameter::new(
5166 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5167 SecurityLevel::TRUSTED_ENVIRONMENT,
5168 ),
5169 KeyParameter::new(
5170 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5171 SecurityLevel::TRUSTED_ENVIRONMENT,
5172 ),
5173 KeyParameter::new(
5174 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5175 SecurityLevel::TRUSTED_ENVIRONMENT,
5176 ),
5177 KeyParameter::new(
5178 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5179 SecurityLevel::TRUSTED_ENVIRONMENT,
5180 ),
5181 KeyParameter::new(
5182 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5183 SecurityLevel::TRUSTED_ENVIRONMENT,
5184 ),
5185 KeyParameter::new(
5186 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5187 SecurityLevel::TRUSTED_ENVIRONMENT,
5188 ),
5189 KeyParameter::new(
5190 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5191 SecurityLevel::TRUSTED_ENVIRONMENT,
5192 ),
5193 KeyParameter::new(
5194 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5195 SecurityLevel::TRUSTED_ENVIRONMENT,
5196 ),
5197 KeyParameter::new(
5198 KeyParameterValue::VendorPatchLevel(3),
5199 SecurityLevel::TRUSTED_ENVIRONMENT,
5200 ),
5201 KeyParameter::new(
5202 KeyParameterValue::BootPatchLevel(4),
5203 SecurityLevel::TRUSTED_ENVIRONMENT,
5204 ),
5205 KeyParameter::new(
5206 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5207 SecurityLevel::TRUSTED_ENVIRONMENT,
5208 ),
5209 KeyParameter::new(
5210 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5211 SecurityLevel::TRUSTED_ENVIRONMENT,
5212 ),
5213 KeyParameter::new(
5214 KeyParameterValue::MacLength(256),
5215 SecurityLevel::TRUSTED_ENVIRONMENT,
5216 ),
5217 KeyParameter::new(
5218 KeyParameterValue::ResetSinceIdRotation,
5219 SecurityLevel::TRUSTED_ENVIRONMENT,
5220 ),
5221 KeyParameter::new(
5222 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5223 SecurityLevel::TRUSTED_ENVIRONMENT,
5224 ),
Qi Wub9433b52020-12-01 14:52:46 +08005225 ];
5226 if let Some(value) = max_usage_count {
5227 params.push(KeyParameter::new(
5228 KeyParameterValue::UsageCountLimit(value),
5229 SecurityLevel::SOFTWARE,
5230 ));
5231 }
5232 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005233 }
5234
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005235 fn make_test_key_entry(
5236 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005237 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005238 namespace: i64,
5239 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005240 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005241 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005242 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005243 let mut blob_metadata = BlobMetaData::new();
5244 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5245 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5246 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5247 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5248 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5249
5250 db.set_blob(
5251 &key_id,
5252 SubComponentType::KEY_BLOB,
5253 Some(TEST_KEY_BLOB),
5254 Some(&blob_metadata),
5255 )?;
5256 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5257 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005258
5259 let params = make_test_params(max_usage_count);
5260 db.insert_keyparameter(&key_id, &params)?;
5261
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005262 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005263 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005264 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005265 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005266 Ok(key_id)
5267 }
5268
Qi Wub9433b52020-12-01 14:52:46 +08005269 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5270 let params = make_test_params(max_usage_count);
5271
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005272 let mut blob_metadata = BlobMetaData::new();
5273 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5274 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5275 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5276 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5277 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5278
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005279 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005280 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005281
5282 KeyEntry {
5283 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005284 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005285 cert: Some(TEST_CERT_BLOB.to_vec()),
5286 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005287 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005288 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005289 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005290 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005291 }
5292 }
5293
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005294 fn make_bootlevel_key_entry(
5295 db: &mut KeystoreDB,
5296 domain: Domain,
5297 namespace: i64,
5298 alias: &str,
5299 logical_only: bool,
5300 ) -> Result<KeyIdGuard> {
5301 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5302 let mut blob_metadata = BlobMetaData::new();
5303 if !logical_only {
5304 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5305 }
5306 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5307
5308 db.set_blob(
5309 &key_id,
5310 SubComponentType::KEY_BLOB,
5311 Some(TEST_KEY_BLOB),
5312 Some(&blob_metadata),
5313 )?;
5314 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5315 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5316
5317 let mut params = make_test_params(None);
5318 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5319
5320 db.insert_keyparameter(&key_id, &params)?;
5321
5322 let mut metadata = KeyMetaData::new();
5323 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5324 db.insert_key_metadata(&key_id, &metadata)?;
5325 rebind_alias(db, &key_id, alias, domain, namespace)?;
5326 Ok(key_id)
5327 }
5328
5329 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5330 let mut params = make_test_params(None);
5331 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5332
5333 let mut blob_metadata = BlobMetaData::new();
5334 if !logical_only {
5335 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5336 }
5337 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5338
5339 let mut metadata = KeyMetaData::new();
5340 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5341
5342 KeyEntry {
5343 id: key_id,
5344 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5345 cert: Some(TEST_CERT_BLOB.to_vec()),
5346 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5347 km_uuid: KEYSTORE_UUID,
5348 parameters: params,
5349 metadata,
5350 pure_cert: false,
5351 }
5352 }
5353
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005354 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005355 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005356 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005357 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005358 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005359 NO_PARAMS,
5360 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005361 Ok((
5362 row.get(0)?,
5363 row.get(1)?,
5364 row.get(2)?,
5365 row.get(3)?,
5366 row.get(4)?,
5367 row.get(5)?,
5368 row.get(6)?,
5369 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005370 },
5371 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005372
5373 println!("Key entry table rows:");
5374 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005375 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005376 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005377 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5378 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005379 );
5380 }
5381 Ok(())
5382 }
5383
5384 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005385 let mut stmt = db
5386 .conn
5387 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005388 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5389 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5390 })?;
5391
5392 println!("Grant table rows:");
5393 for r in rows {
5394 let (id, gt, ki, av) = r.unwrap();
5395 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5396 }
5397 Ok(())
5398 }
5399
Joel Galenson0891bc12020-07-20 10:37:03 -07005400 // Use a custom random number generator that repeats each number once.
5401 // This allows us to test repeated elements.
5402
5403 thread_local! {
5404 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5405 }
5406
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005407 fn reset_random() {
5408 RANDOM_COUNTER.with(|counter| {
5409 *counter.borrow_mut() = 0;
5410 })
5411 }
5412
Joel Galenson0891bc12020-07-20 10:37:03 -07005413 pub fn random() -> i64 {
5414 RANDOM_COUNTER.with(|counter| {
5415 let result = *counter.borrow() / 2;
5416 *counter.borrow_mut() += 1;
5417 result
5418 })
5419 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005420
5421 #[test]
5422 fn test_last_off_body() -> Result<()> {
5423 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005424 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005425 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005426 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005427 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005428 let one_second = Duration::from_secs(1);
5429 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005430 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005431 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005432 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005433 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005434 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005435 Ok(())
5436 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005437
5438 #[test]
5439 fn test_unbind_keys_for_user() -> Result<()> {
5440 let mut db = new_test_db()?;
5441 db.unbind_keys_for_user(1, false)?;
5442
5443 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5444 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5445 db.unbind_keys_for_user(2, false)?;
5446
Janis Danisevskis18313832021-05-17 13:30:32 -07005447 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5448 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005449
5450 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005451 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005452
5453 Ok(())
5454 }
5455
5456 #[test]
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005457 fn test_unbind_keys_for_user_removes_superkeys() -> Result<()> {
5458 let mut db = new_test_db()?;
5459 let super_key = keystore2_crypto::generate_aes256_key()?;
5460 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
5461 let (encrypted_super_key, metadata) =
5462 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
5463
5464 let key_name_enc = SuperKeyType {
5465 alias: "test_super_key_1",
5466 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5467 };
5468
5469 let key_name_nonenc = SuperKeyType {
5470 alias: "test_super_key_2",
5471 algorithm: SuperEncryptionAlgorithm::Aes256Gcm,
5472 };
5473
5474 // Install two super keys.
5475 db.store_super_key(
5476 1,
5477 &key_name_nonenc,
5478 &super_key,
5479 &BlobMetaData::new(),
5480 &KeyMetaData::new(),
5481 )?;
5482 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5483
5484 // Check that both can be found in the database.
5485 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5486 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5487
5488 // Install the same keys for a different user.
5489 db.store_super_key(
5490 2,
5491 &key_name_nonenc,
5492 &super_key,
5493 &BlobMetaData::new(),
5494 &KeyMetaData::new(),
5495 )?;
5496 db.store_super_key(2, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5497
5498 // Check that the second pair of keys can be found in the database.
5499 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5500 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5501
5502 // Delete only encrypted keys.
5503 db.unbind_keys_for_user(1, true)?;
5504
5505 // The encrypted superkey should be gone now.
5506 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5507 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5508
5509 // Reinsert the encrypted key.
5510 db.store_super_key(1, &key_name_enc, &encrypted_super_key, &metadata, &KeyMetaData::new())?;
5511
5512 // Check that both can be found in the database, again..
5513 assert!(db.load_super_key(&key_name_enc, 1)?.is_some());
5514 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_some());
5515
5516 // Delete all even unencrypted keys.
5517 db.unbind_keys_for_user(1, false)?;
5518
5519 // Both should be gone now.
5520 assert!(db.load_super_key(&key_name_enc, 1)?.is_none());
5521 assert!(db.load_super_key(&key_name_nonenc, 1)?.is_none());
5522
5523 // Check that the second pair of keys was untouched.
5524 assert!(db.load_super_key(&key_name_enc, 2)?.is_some());
5525 assert!(db.load_super_key(&key_name_nonenc, 2)?.is_some());
5526
5527 Ok(())
5528 }
5529
5530 #[test]
Hasini Gunasingheda895552021-01-27 19:34:37 +00005531 fn test_store_super_key() -> Result<()> {
5532 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005533 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005534 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005535 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005536 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005537 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005538
5539 let (encrypted_super_key, metadata) =
5540 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005541 db.store_super_key(
5542 1,
5543 &USER_SUPER_KEY,
5544 &encrypted_super_key,
5545 &metadata,
5546 &KeyMetaData::new(),
5547 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005548
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005549 // Check if super key exists.
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005550 assert!(db.key_exists(Domain::APP, 1, USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005551
Paul Crowley7a658392021-03-18 17:08:20 -07005552 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005553 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5554 USER_SUPER_KEY.algorithm,
5555 key_entry,
5556 &pw,
5557 None,
5558 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005559
Paul Crowley7a658392021-03-18 17:08:20 -07005560 let decrypted_secret_bytes =
5561 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5562 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Janis Danisevskis11bd2592022-01-04 19:59:26 -08005563
Hasini Gunasingheda895552021-01-27 19:34:37 +00005564 Ok(())
5565 }
Seth Moore78c091f2021-04-09 21:38:30 +00005566
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005567 fn get_valid_statsd_storage_types() -> Vec<MetricsStorage> {
Seth Moore78c091f2021-04-09 21:38:30 +00005568 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005569 MetricsStorage::KEY_ENTRY,
5570 MetricsStorage::KEY_ENTRY_ID_INDEX,
5571 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
5572 MetricsStorage::BLOB_ENTRY,
5573 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5574 MetricsStorage::KEY_PARAMETER,
5575 MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX,
5576 MetricsStorage::KEY_METADATA,
5577 MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX,
5578 MetricsStorage::GRANT,
5579 MetricsStorage::AUTH_TOKEN,
5580 MetricsStorage::BLOB_METADATA,
5581 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005582 ]
5583 }
5584
5585 /// Perform a simple check to ensure that we can query all the storage types
5586 /// that are supported by the DB. Check for reasonable values.
5587 #[test]
5588 fn test_query_all_valid_table_sizes() -> Result<()> {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005589 const PAGE_SIZE: i32 = 4096;
Seth Moore78c091f2021-04-09 21:38:30 +00005590
5591 let mut db = new_test_db()?;
5592
5593 for t in get_valid_statsd_storage_types() {
5594 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005595 // AuthToken can be less than a page since it's in a btree, not sqlite
5596 // TODO(b/187474736) stop using if-let here
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005597 if let MetricsStorage::AUTH_TOKEN = t {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005598 } else {
5599 assert!(stat.size >= PAGE_SIZE);
5600 }
Seth Moore78c091f2021-04-09 21:38:30 +00005601 assert!(stat.size >= stat.unused_size);
5602 }
5603
5604 Ok(())
5605 }
5606
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005607 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, StorageStats> {
Seth Moore78c091f2021-04-09 21:38:30 +00005608 get_valid_statsd_storage_types()
5609 .into_iter()
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005610 .map(|t| (t.0, db.get_storage_stat(t).unwrap()))
Seth Moore78c091f2021-04-09 21:38:30 +00005611 .collect()
5612 }
5613
5614 fn assert_storage_increased(
5615 db: &mut KeystoreDB,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005616 increased_storage_types: Vec<MetricsStorage>,
5617 baseline: &mut BTreeMap<i32, StorageStats>,
Seth Moore78c091f2021-04-09 21:38:30 +00005618 ) {
5619 for storage in increased_storage_types {
5620 // Verify the expected storage increased.
5621 let new = db.get_storage_stat(storage).unwrap();
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005622 let storage = storage;
5623 let old = &baseline[&storage.0];
5624 assert!(new.size >= old.size, "{}: {} >= {}", storage.0, new.size, old.size);
Seth Moore78c091f2021-04-09 21:38:30 +00005625 assert!(
5626 new.unused_size <= old.unused_size,
5627 "{}: {} <= {}",
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005628 storage.0,
Seth Moore78c091f2021-04-09 21:38:30 +00005629 new.unused_size,
5630 old.unused_size
5631 );
5632
5633 // Update the baseline with the new value so that it succeeds in the
5634 // later comparison.
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005635 baseline.insert(storage.0, new);
Seth Moore78c091f2021-04-09 21:38:30 +00005636 }
5637
5638 // Get an updated map of the storage and verify there were no unexpected changes.
5639 let updated_stats = get_storage_stats_map(db);
5640 assert_eq!(updated_stats.len(), baseline.len());
5641
5642 for &k in baseline.keys() {
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005643 let stringify = |map: &BTreeMap<i32, StorageStats>| -> String {
Seth Moore78c091f2021-04-09 21:38:30 +00005644 let mut s = String::new();
5645 for &k in map.keys() {
5646 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5647 .expect("string concat failed");
5648 }
5649 s
5650 };
5651
5652 assert!(
5653 updated_stats[&k].size == baseline[&k].size
5654 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5655 "updated_stats:\n{}\nbaseline:\n{}",
5656 stringify(&updated_stats),
Chris Wailesd5aaaef2021-07-27 16:04:33 -07005657 stringify(baseline)
Seth Moore78c091f2021-04-09 21:38:30 +00005658 );
5659 }
5660 }
5661
5662 #[test]
5663 fn test_verify_key_table_size_reporting() -> Result<()> {
5664 let mut db = new_test_db()?;
5665 let mut working_stats = get_storage_stats_map(&mut db);
5666
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005667 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005668 assert_storage_increased(
5669 &mut db,
5670 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005671 MetricsStorage::KEY_ENTRY,
5672 MetricsStorage::KEY_ENTRY_ID_INDEX,
5673 MetricsStorage::KEY_ENTRY_DOMAIN_NAMESPACE_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005674 ],
5675 &mut working_stats,
5676 );
5677
5678 let mut blob_metadata = BlobMetaData::new();
5679 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5680 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5681 assert_storage_increased(
5682 &mut db,
5683 vec![
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005684 MetricsStorage::BLOB_ENTRY,
5685 MetricsStorage::BLOB_ENTRY_KEY_ENTRY_ID_INDEX,
5686 MetricsStorage::BLOB_METADATA,
5687 MetricsStorage::BLOB_METADATA_BLOB_ENTRY_ID_INDEX,
Seth Moore78c091f2021-04-09 21:38:30 +00005688 ],
5689 &mut working_stats,
5690 );
5691
5692 let params = make_test_params(None);
5693 db.insert_keyparameter(&key_id, &params)?;
5694 assert_storage_increased(
5695 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005696 vec![MetricsStorage::KEY_PARAMETER, MetricsStorage::KEY_PARAMETER_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005697 &mut working_stats,
5698 );
5699
5700 let mut metadata = KeyMetaData::new();
5701 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5702 db.insert_key_metadata(&key_id, &metadata)?;
5703 assert_storage_increased(
5704 &mut db,
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005705 vec![MetricsStorage::KEY_METADATA, MetricsStorage::KEY_METADATA_KEY_ENTRY_ID_INDEX],
Seth Moore78c091f2021-04-09 21:38:30 +00005706 &mut working_stats,
5707 );
5708
5709 let mut sum = 0;
5710 for stat in working_stats.values() {
5711 sum += stat.size;
5712 }
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005713 let total = db.get_storage_stat(MetricsStorage::DATABASE)?.size;
Seth Moore78c091f2021-04-09 21:38:30 +00005714 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5715
5716 Ok(())
5717 }
5718
5719 #[test]
5720 fn test_verify_auth_table_size_reporting() -> Result<()> {
5721 let mut db = new_test_db()?;
5722 let mut working_stats = get_storage_stats_map(&mut db);
5723 db.insert_auth_token(&HardwareAuthToken {
5724 challenge: 123,
5725 userId: 456,
5726 authenticatorId: 789,
5727 authenticatorType: kmhw_authenticator_type::ANY,
5728 timestamp: Timestamp { milliSeconds: 10 },
5729 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005730 });
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005731 assert_storage_increased(&mut db, vec![MetricsStorage::AUTH_TOKEN], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005732 Ok(())
5733 }
5734
5735 #[test]
5736 fn test_verify_grant_table_size_reporting() -> Result<()> {
5737 const OWNER: i64 = 1;
5738 let mut db = new_test_db()?;
5739 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5740
5741 let mut working_stats = get_storage_stats_map(&mut db);
5742 db.grant(
5743 &KeyDescriptor {
5744 domain: Domain::APP,
5745 nspace: 0,
5746 alias: Some(TEST_ALIAS.to_string()),
5747 blob: None,
5748 },
5749 OWNER as u32,
5750 123,
Janis Danisevskis39d57e72021-10-19 16:56:20 -07005751 key_perm_set![KeyPerm::Use],
Seth Moore78c091f2021-04-09 21:38:30 +00005752 |_, _| Ok(()),
5753 )?;
5754
Hasini Gunasinghe15891e62021-06-10 16:23:27 +00005755 assert_storage_increased(&mut db, vec![MetricsStorage::GRANT], &mut working_stats);
Seth Moore78c091f2021-04-09 21:38:30 +00005756
5757 Ok(())
5758 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005759
5760 #[test]
5761 fn find_auth_token_entry_returns_latest() -> Result<()> {
5762 let mut db = new_test_db()?;
5763 db.insert_auth_token(&HardwareAuthToken {
5764 challenge: 123,
5765 userId: 456,
5766 authenticatorId: 789,
5767 authenticatorType: kmhw_authenticator_type::ANY,
5768 timestamp: Timestamp { milliSeconds: 10 },
5769 mac: b"mac0".to_vec(),
5770 });
5771 std::thread::sleep(std::time::Duration::from_millis(1));
5772 db.insert_auth_token(&HardwareAuthToken {
5773 challenge: 123,
5774 userId: 457,
5775 authenticatorId: 789,
5776 authenticatorType: kmhw_authenticator_type::ANY,
5777 timestamp: Timestamp { milliSeconds: 12 },
5778 mac: b"mac1".to_vec(),
5779 });
5780 std::thread::sleep(std::time::Duration::from_millis(1));
5781 db.insert_auth_token(&HardwareAuthToken {
5782 challenge: 123,
5783 userId: 458,
5784 authenticatorId: 789,
5785 authenticatorType: kmhw_authenticator_type::ANY,
5786 timestamp: Timestamp { milliSeconds: 3 },
5787 mac: b"mac2".to_vec(),
5788 });
5789 // All three entries are in the database
5790 assert_eq!(db.perboot.auth_tokens_len(), 3);
5791 // It selected the most recent timestamp
5792 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5793 Ok(())
5794 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005795
5796 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005797 fn test_load_key_descriptor() -> Result<()> {
5798 let mut db = new_test_db()?;
5799 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5800
5801 let key = db.load_key_descriptor(key_id)?.unwrap();
5802
5803 assert_eq!(key.domain, Domain::APP);
5804 assert_eq!(key.nspace, 1);
5805 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5806
5807 // No such id
5808 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5809 Ok(())
5810 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005811}