blob: 36c722a1943e6a484028aca5b2b7a5fa3cfa7e77 [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 Danisevskisb42fc182020-12-15 08:41:27 -080048use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080049use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070050use crate::permission::KeyPermSet;
Hasini Gunasinghe66a24602021-05-12 19:03:12 +000051use crate::utils::{get_current_time_in_milliseconds, watchdog as wd, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080052use crate::{
Paul Crowley7a658392021-03-18 17:08:20 -070053 error::{Error as KsError, ErrorCode, ResponseCode},
54 super_key::SuperKeyType,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080055};
Janis Danisevskis030ba022021-05-26 11:15:30 -070056use crate::{gc::Gc, super_key::USER_SUPER_KEY};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080057use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080058use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis030ba022021-05-26 11:15:30 -070059use utils as db_utils;
60use utils::SqlField;
Janis Danisevskis60400fe2020-08-26 15:24:42 -070061
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080063 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000064 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080065};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070066use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070067 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070068};
Max Bires2b2e6562020-09-22 11:22:36 -070069use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
70 AttestationPoolStatus::AttestationPoolStatus,
71};
Seth Moore78c091f2021-04-09 21:38:30 +000072use statslog_rust::keystore2_storage_stats::{
73 Keystore2StorageStats, StorageType as StatsdStorageType,
74};
Max Bires2b2e6562020-09-22 11:22:36 -070075
76use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080077use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000078use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070079#[cfg(not(test))]
80use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070081use rusqlite::{
Joel Galensonff79e362021-05-25 16:30:17 -070082 params, params_from_iter,
Janis Danisevskisb42fc182020-12-15 08:41:27 -080083 types::FromSql,
84 types::FromSqlResult,
85 types::ToSqlOutput,
86 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080087 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070088};
Max Bires2b2e6562020-09-22 11:22:36 -070089
Janis Danisevskisaec14592020-11-12 09:41:49 -080090use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080091 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080092 path::Path,
Janis Danisevskis3395f862021-05-06 10:54:17 -070093 sync::{Arc, Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080095};
Max Bires2b2e6562020-09-22 11:22:36 -070096
Joel Galenson0891bc12020-07-20 10:37:03 -070097#[cfg(test)]
98use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070099
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800100impl_metadata!(
101 /// A set of metadata for key entries.
102 #[derive(Debug, Default, Eq, PartialEq)]
103 pub struct KeyMetaData;
104 /// A metadata entry for key entries.
105 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
106 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800107 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800108 CreationDate(DateTime) with accessor creation_date,
109 /// Expiration date for attestation keys.
110 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700111 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
112 /// provisioning
113 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
114 /// Vector representing the raw public key so results from the server can be matched
115 /// to the right entry
116 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700117 /// SEC1 public key for ECDH encryption
118 Sec1PublicKey(Vec<u8>) with accessor sec1_public_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800119 // --- ADD NEW META DATA FIELDS HERE ---
120 // For backwards compatibility add new entries only to
121 // end of this list and above this comment.
122 };
123);
124
125impl KeyMetaData {
126 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
127 let mut stmt = tx
128 .prepare(
129 "SELECT tag, data from persistent.keymetadata
130 WHERE keyentryid = ?;",
131 )
132 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
133
134 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
135
136 let mut rows =
137 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
138 db_utils::with_rows_extract_all(&mut rows, |row| {
139 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
140 metadata.insert(
141 db_tag,
142 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
143 .context("Failed to read KeyMetaEntry.")?,
144 );
145 Ok(())
146 })
147 .context("In KeyMetaData::load_from_db.")?;
148
149 Ok(Self { data: metadata })
150 }
151
152 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
153 let mut stmt = tx
154 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000155 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800156 VALUES (?, ?, ?);",
157 )
158 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
159
160 let iter = self.data.iter();
161 for (tag, entry) in iter {
162 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
163 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
164 })?;
165 }
166 Ok(())
167 }
168}
169
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800170impl_metadata!(
171 /// A set of metadata for key blobs.
172 #[derive(Debug, Default, Eq, PartialEq)]
173 pub struct BlobMetaData;
174 /// A metadata entry for key blobs.
175 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
176 pub enum BlobMetaEntry {
177 /// If present, indicates that the blob is encrypted with another key or a key derived
178 /// from a password.
179 EncryptedBy(EncryptedBy) with accessor encrypted_by,
180 /// If the blob is password encrypted this field is set to the
181 /// salt used for the key derivation.
182 Salt(Vec<u8>) with accessor salt,
183 /// If the blob is encrypted, this field is set to the initialization vector.
184 Iv(Vec<u8>) with accessor iv,
185 /// If the blob is encrypted, this field holds the AEAD TAG.
186 AeadTag(Vec<u8>) with accessor aead_tag,
187 /// The uuid of the owning KeyMint instance.
188 KmUuid(Uuid) with accessor km_uuid,
Paul Crowley8d5b2532021-03-19 10:53:07 -0700189 /// If the key is ECDH encrypted, this is the ephemeral public key
190 PublicKey(Vec<u8>) with accessor public_key,
Paul Crowley44c02da2021-04-08 17:04:43 +0000191 /// If the key is encrypted with a MaxBootLevel key, this is the boot level
192 /// of that key
193 MaxBootLevel(i32) with accessor max_boot_level,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800194 // --- ADD NEW META DATA FIELDS HERE ---
195 // For backwards compatibility add new entries only to
196 // end of this list and above this comment.
197 };
198);
199
200impl BlobMetaData {
201 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
202 let mut stmt = tx
203 .prepare(
204 "SELECT tag, data from persistent.blobmetadata
205 WHERE blobentryid = ?;",
206 )
207 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
208
209 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
210
211 let mut rows =
212 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
213 db_utils::with_rows_extract_all(&mut rows, |row| {
214 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
215 metadata.insert(
216 db_tag,
217 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
218 .context("Failed to read BlobMetaEntry.")?,
219 );
220 Ok(())
221 })
222 .context("In BlobMetaData::load_from_db.")?;
223
224 Ok(Self { data: metadata })
225 }
226
227 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
228 let mut stmt = tx
229 .prepare(
230 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
231 VALUES (?, ?, ?);",
232 )
233 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
234
235 let iter = self.data.iter();
236 for (tag, entry) in iter {
237 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
238 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
239 })?;
240 }
241 Ok(())
242 }
243}
244
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800245/// Indicates the type of the keyentry.
246#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
247pub enum KeyType {
248 /// This is a client key type. These keys are created or imported through the Keystore 2.0
249 /// AIDL interface android.system.keystore2.
250 Client,
251 /// This is a super key type. These keys are created by keystore itself and used to encrypt
252 /// other key blobs to provide LSKF binding.
253 Super,
254 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
255 Attestation,
256}
257
258impl ToSql for KeyType {
259 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
260 Ok(ToSqlOutput::Owned(Value::Integer(match self {
261 KeyType::Client => 0,
262 KeyType::Super => 1,
263 KeyType::Attestation => 2,
264 })))
265 }
266}
267
268impl FromSql for KeyType {
269 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
270 match i64::column_result(value)? {
271 0 => Ok(KeyType::Client),
272 1 => Ok(KeyType::Super),
273 2 => Ok(KeyType::Attestation),
274 v => Err(FromSqlError::OutOfRange(v)),
275 }
276 }
277}
278
Max Bires8e93d2b2021-01-14 13:17:59 -0800279/// Uuid representation that can be stored in the database.
280/// Right now it can only be initialized from SecurityLevel.
281/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
282#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
283pub struct Uuid([u8; 16]);
284
285impl Deref for Uuid {
286 type Target = [u8; 16];
287
288 fn deref(&self) -> &Self::Target {
289 &self.0
290 }
291}
292
293impl From<SecurityLevel> for Uuid {
294 fn from(sec_level: SecurityLevel) -> Self {
295 Self((sec_level.0 as u128).to_be_bytes())
296 }
297}
298
299impl ToSql for Uuid {
300 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
301 self.0.to_sql()
302 }
303}
304
305impl FromSql for Uuid {
306 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
307 let blob = Vec::<u8>::column_result(value)?;
308 if blob.len() != 16 {
309 return Err(FromSqlError::OutOfRange(blob.len() as i64));
310 }
311 let mut arr = [0u8; 16];
312 arr.copy_from_slice(&blob);
313 Ok(Self(arr))
314 }
315}
316
317/// Key entries that are not associated with any KeyMint instance, such as pure certificate
318/// entries are associated with this UUID.
319pub static KEYSTORE_UUID: Uuid = Uuid([
320 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
321]);
322
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800323/// Indicates how the sensitive part of this key blob is encrypted.
324#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
325pub enum EncryptedBy {
326 /// The keyblob is encrypted by a user password.
327 /// In the database this variant is represented as NULL.
328 Password,
329 /// The keyblob is encrypted by another key with wrapped key id.
330 /// In the database this variant is represented as non NULL value
331 /// that is convertible to i64, typically NUMERIC.
332 KeyId(i64),
333}
334
335impl ToSql for EncryptedBy {
336 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
337 match self {
338 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
339 Self::KeyId(id) => id.to_sql(),
340 }
341 }
342}
343
344impl FromSql for EncryptedBy {
345 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
346 match value {
347 ValueRef::Null => Ok(Self::Password),
348 _ => Ok(Self::KeyId(i64::column_result(value)?)),
349 }
350 }
351}
352
353/// A database representation of wall clock time. DateTime stores unix epoch time as
354/// i64 in milliseconds.
355#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
356pub struct DateTime(i64);
357
358/// Error type returned when creating DateTime or converting it from and to
359/// SystemTime.
360#[derive(thiserror::Error, Debug)]
361pub enum DateTimeError {
362 /// This is returned when SystemTime and Duration computations fail.
363 #[error(transparent)]
364 SystemTimeError(#[from] SystemTimeError),
365
366 /// This is returned when type conversions fail.
367 #[error(transparent)]
368 TypeConversion(#[from] std::num::TryFromIntError),
369
370 /// This is returned when checked time arithmetic failed.
371 #[error("Time arithmetic failed.")]
372 TimeArithmetic,
373}
374
375impl DateTime {
376 /// Constructs a new DateTime object denoting the current time. This may fail during
377 /// conversion to unix epoch time and during conversion to the internal i64 representation.
378 pub fn now() -> Result<Self, DateTimeError> {
379 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
380 }
381
382 /// Constructs a new DateTime object from milliseconds.
383 pub fn from_millis_epoch(millis: i64) -> Self {
384 Self(millis)
385 }
386
387 /// Returns unix epoch time in milliseconds.
388 pub fn to_millis_epoch(&self) -> i64 {
389 self.0
390 }
391
392 /// Returns unix epoch time in seconds.
393 pub fn to_secs_epoch(&self) -> i64 {
394 self.0 / 1000
395 }
396}
397
398impl ToSql for DateTime {
399 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
400 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
401 }
402}
403
404impl FromSql for DateTime {
405 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
406 Ok(Self(i64::column_result(value)?))
407 }
408}
409
410impl TryInto<SystemTime> for DateTime {
411 type Error = DateTimeError;
412
413 fn try_into(self) -> Result<SystemTime, Self::Error> {
414 // We want to construct a SystemTime representation equivalent to self, denoting
415 // a point in time THEN, but we cannot set the time directly. We can only construct
416 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
417 // and between EPOCH and THEN. With this common reference we can construct the
418 // duration between NOW and THEN which we can add to our SystemTime representation
419 // of NOW to get a SystemTime representation of THEN.
420 // Durations can only be positive, thus the if statement below.
421 let now = SystemTime::now();
422 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
423 let then_epoch = Duration::from_millis(self.0.try_into()?);
424 Ok(if now_epoch > then_epoch {
425 // then = now - (now_epoch - then_epoch)
426 now_epoch
427 .checked_sub(then_epoch)
428 .and_then(|d| now.checked_sub(d))
429 .ok_or(DateTimeError::TimeArithmetic)?
430 } else {
431 // then = now + (then_epoch - now_epoch)
432 then_epoch
433 .checked_sub(now_epoch)
434 .and_then(|d| now.checked_add(d))
435 .ok_or(DateTimeError::TimeArithmetic)?
436 })
437 }
438}
439
440impl TryFrom<SystemTime> for DateTime {
441 type Error = DateTimeError;
442
443 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
444 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
445 }
446}
447
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800448#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
449enum KeyLifeCycle {
450 /// Existing keys have a key ID but are not fully populated yet.
451 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
452 /// them to Unreferenced for garbage collection.
453 Existing,
454 /// A live key is fully populated and usable by clients.
455 Live,
456 /// An unreferenced key is scheduled for garbage collection.
457 Unreferenced,
458}
459
460impl ToSql for KeyLifeCycle {
461 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
462 match self {
463 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
464 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
465 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
466 }
467 }
468}
469
470impl FromSql for KeyLifeCycle {
471 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
472 match i64::column_result(value)? {
473 0 => Ok(KeyLifeCycle::Existing),
474 1 => Ok(KeyLifeCycle::Live),
475 2 => Ok(KeyLifeCycle::Unreferenced),
476 v => Err(FromSqlError::OutOfRange(v)),
477 }
478 }
479}
480
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700481/// Keys have a KeyMint blob component and optional public certificate and
482/// certificate chain components.
483/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
484/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800485#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700486pub struct KeyEntryLoadBits(u32);
487
488impl KeyEntryLoadBits {
489 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
490 pub const NONE: KeyEntryLoadBits = Self(0);
491 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
492 pub const KM: KeyEntryLoadBits = Self(1);
493 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
494 pub const PUBLIC: KeyEntryLoadBits = Self(2);
495 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
496 pub const BOTH: KeyEntryLoadBits = Self(3);
497
498 /// Returns true if this object indicates that the public components shall be loaded.
499 pub const fn load_public(&self) -> bool {
500 self.0 & Self::PUBLIC.0 != 0
501 }
502
503 /// Returns true if the object indicates that the KeyMint component shall be loaded.
504 pub const fn load_km(&self) -> bool {
505 self.0 & Self::KM.0 != 0
506 }
507}
508
Janis Danisevskisaec14592020-11-12 09:41:49 -0800509lazy_static! {
510 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
511}
512
513struct KeyIdLockDb {
514 locked_keys: Mutex<HashSet<i64>>,
515 cond_var: Condvar,
516}
517
518/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
519/// from the database a second time. Most functions manipulating the key blob database
520/// require a KeyIdGuard.
521#[derive(Debug)]
522pub struct KeyIdGuard(i64);
523
524impl KeyIdLockDb {
525 fn new() -> Self {
526 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
527 }
528
529 /// This function blocks until an exclusive lock for the given key entry id can
530 /// be acquired. It returns a guard object, that represents the lifecycle of the
531 /// acquired lock.
532 pub fn get(&self, key_id: i64) -> KeyIdGuard {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 while locked_keys.contains(&key_id) {
535 locked_keys = self.cond_var.wait(locked_keys).unwrap();
536 }
537 locked_keys.insert(key_id);
538 KeyIdGuard(key_id)
539 }
540
541 /// This function attempts to acquire an exclusive lock on a given key id. If the
542 /// given key id is already taken the function returns None immediately. If a lock
543 /// can be acquired this function returns a guard object, that represents the
544 /// lifecycle of the acquired lock.
545 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
546 let mut locked_keys = self.locked_keys.lock().unwrap();
547 if locked_keys.insert(key_id) {
548 Some(KeyIdGuard(key_id))
549 } else {
550 None
551 }
552 }
553}
554
555impl KeyIdGuard {
556 /// Get the numeric key id of the locked key.
557 pub fn id(&self) -> i64 {
558 self.0
559 }
560}
561
562impl Drop for KeyIdGuard {
563 fn drop(&mut self) {
564 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
565 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800566 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800567 KEY_ID_LOCK.cond_var.notify_all();
568 }
569}
570
Max Bires8e93d2b2021-01-14 13:17:59 -0800571/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700572#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800573pub struct CertificateInfo {
574 cert: Option<Vec<u8>>,
575 cert_chain: Option<Vec<u8>>,
576}
577
578impl CertificateInfo {
579 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
580 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
581 Self { cert, cert_chain }
582 }
583
584 /// Take the cert
585 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
586 self.cert.take()
587 }
588
589 /// Take the cert chain
590 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
591 self.cert_chain.take()
592 }
593}
594
Max Bires2b2e6562020-09-22 11:22:36 -0700595/// This type represents a certificate chain with a private key corresponding to the leaf
596/// 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 -0700597pub struct CertificateChain {
Max Bires97f96812021-02-23 23:44:57 -0800598 /// A KM key blob
599 pub private_key: ZVec,
600 /// A batch cert for private_key
601 pub batch_cert: Vec<u8>,
602 /// A full certificate chain from root signing authority to private_key, including batch_cert
603 /// for convenience.
604 pub cert_chain: Vec<u8>,
Max Bires2b2e6562020-09-22 11:22:36 -0700605}
606
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700607/// This type represents a Keystore 2.0 key entry.
608/// An entry has a unique `id` by which it can be found in the database.
609/// It has a security level field, key parameters, and three optional fields
610/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800611#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700612pub struct KeyEntry {
613 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800614 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615 cert: Option<Vec<u8>>,
616 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800617 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700618 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800619 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800620 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700621}
622
623impl KeyEntry {
624 /// Returns the unique id of the Key entry.
625 pub fn id(&self) -> i64 {
626 self.id
627 }
628 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800629 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
630 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700631 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800632 /// Extracts the Optional KeyMint blob including its metadata.
633 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
634 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700635 }
636 /// Exposes the optional public certificate.
637 pub fn cert(&self) -> &Option<Vec<u8>> {
638 &self.cert
639 }
640 /// Extracts the optional public certificate.
641 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
642 self.cert.take()
643 }
644 /// Exposes the optional public certificate chain.
645 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
646 &self.cert_chain
647 }
648 /// Extracts the optional public certificate_chain.
649 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
650 self.cert_chain.take()
651 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800652 /// Returns the uuid of the owning KeyMint instance.
653 pub fn km_uuid(&self) -> &Uuid {
654 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700655 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700656 /// Exposes the key parameters of this key entry.
657 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
658 &self.parameters
659 }
660 /// Consumes this key entry and extracts the keyparameters from it.
661 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
662 self.parameters
663 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800664 /// Exposes the key metadata of this key entry.
665 pub fn metadata(&self) -> &KeyMetaData {
666 &self.metadata
667 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800668 /// This returns true if the entry is a pure certificate entry with no
669 /// private key component.
670 pub fn pure_cert(&self) -> bool {
671 self.pure_cert
672 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000673 /// Consumes this key entry and extracts the keyparameters and metadata from it.
674 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
675 (self.parameters, self.metadata)
676 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700677}
678
679/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800680#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700681pub struct SubComponentType(u32);
682impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800683 /// Persistent identifier for a key blob.
684 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700685 /// Persistent identifier for a certificate blob.
686 pub const CERT: SubComponentType = Self(1);
687 /// Persistent identifier for a certificate chain blob.
688 pub const CERT_CHAIN: SubComponentType = Self(2);
689}
690
691impl ToSql for SubComponentType {
692 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
693 self.0.to_sql()
694 }
695}
696
697impl FromSql for SubComponentType {
698 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
699 Ok(Self(u32::column_result(value)?))
700 }
701}
702
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800703/// This trait is private to the database module. It is used to convey whether or not the garbage
704/// collector shall be invoked after a database access. All closures passed to
705/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
706/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
707/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
708/// `.need_gc()`.
709trait DoGc<T> {
710 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
711
712 fn no_gc(self) -> Result<(bool, T)>;
713
714 fn need_gc(self) -> Result<(bool, T)>;
715}
716
717impl<T> DoGc<T> for Result<T> {
718 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
719 self.map(|r| (need_gc, r))
720 }
721
722 fn no_gc(self) -> Result<(bool, T)> {
723 self.do_gc(false)
724 }
725
726 fn need_gc(self) -> Result<(bool, T)> {
727 self.do_gc(true)
728 }
729}
730
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700731/// KeystoreDB wraps a connection to an SQLite database and tracks its
732/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700733pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700734 conn: Connection,
Janis Danisevskis3395f862021-05-06 10:54:17 -0700735 gc: Option<Arc<Gc>>,
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700736 perboot: Arc<perboot::PerbootDB>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700737}
738
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000739/// Database representation of the monotonic time retrieved from the system call clock_gettime with
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000740/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in milliseconds.
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000741#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
742pub struct MonotonicRawTime(i64);
743
744impl MonotonicRawTime {
745 /// Constructs a new MonotonicRawTime
746 pub fn now() -> Self {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000747 Self(get_current_time_in_milliseconds())
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000748 }
749
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000750 /// Returns the value of MonotonicRawTime in milliseconds as i64
751 pub fn milliseconds(&self) -> i64 {
752 self.0
David Drysdale0e45a612021-02-25 17:24:36 +0000753 }
754
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000755 /// Returns the integer value of MonotonicRawTime as i64
756 pub fn seconds(&self) -> i64 {
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000757 self.0 / 1000
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000758 }
759
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800760 /// Like i64::checked_sub.
761 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
762 self.0.checked_sub(other.0).map(Self)
763 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000764}
765
766impl ToSql for MonotonicRawTime {
767 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
768 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
769 }
770}
771
772impl FromSql for MonotonicRawTime {
773 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
774 Ok(Self(i64::column_result(value)?))
775 }
776}
777
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000778/// This struct encapsulates the information to be stored in the database about the auth tokens
779/// received by keystore.
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700780#[derive(Clone)]
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000781pub struct AuthTokenEntry {
782 auth_token: HardwareAuthToken,
Hasini Gunasinghe66a24602021-05-12 19:03:12 +0000783 // Time received in milliseconds
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000784 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000785}
786
787impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000788 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000789 AuthTokenEntry { auth_token, time_received }
790 }
791
792 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800793 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000794 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800795 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
796 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000797 })
798 }
799
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000800 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800801 pub fn auth_token(&self) -> &HardwareAuthToken {
802 &self.auth_token
803 }
804
805 /// Returns the auth token wrapped by the AuthTokenEntry
806 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000807 self.auth_token
808 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800809
810 /// Returns the time that this auth token was received.
811 pub fn time_received(&self) -> MonotonicRawTime {
812 self.time_received
813 }
Hasini Gunasingheb3715fb2021-02-26 20:34:45 +0000814
815 /// Returns the challenge value of the auth token.
816 pub fn challenge(&self) -> i64 {
817 self.auth_token.challenge
818 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000819}
820
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800821/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
822/// This object does not allow access to the database connection. But it keeps a database
823/// connection alive in order to keep the in memory per boot database alive.
824pub struct PerBootDbKeepAlive(Connection);
825
Joel Galenson26f4d012020-07-17 14:57:21 -0700826impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800827 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700828 const CURRENT_DB_VERSION: u32 = 1;
829 const UPGRADERS: &'static [fn(&Transaction) -> Result<u32>] = &[Self::from_0_to_1];
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800830
Seth Moore78c091f2021-04-09 21:38:30 +0000831 /// Name of the file that holds the cross-boot persistent database.
832 pub const PERSISTENT_DB_FILENAME: &'static str = &"persistent.sqlite";
833
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700834 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800835 /// files persistent.sqlite and perboot.sqlite in the given directory.
836 /// It also attempts to initialize all of the tables.
837 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700838 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis3395f862021-05-06 10:54:17 -0700839 pub fn new(db_root: &Path, gc: Option<Arc<Gc>>) -> Result<Self> {
Janis Danisevskis850d4862021-05-05 08:41:14 -0700840 let _wp = wd::watch_millis("KeystoreDB::new", 500);
841
Seth Moore472fcbb2021-05-12 10:07:51 -0700842 let persistent_path = Self::make_persistent_path(&db_root)?;
843 let conn = Self::make_connection(&persistent_path)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800844
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700845 let mut db = Self { conn, gc, perboot: perboot::PERBOOT_DB.clone() };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800846 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700847 versioning::upgrade_database(tx, Self::CURRENT_DB_VERSION, Self::UPGRADERS)
848 .context("In KeystoreDB::new: trying to upgrade database.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800849 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800850 })?;
851 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700852 }
853
Janis Danisevskiscfaf9192021-05-26 16:31:02 -0700854 // This upgrade function deletes all MAX_BOOT_LEVEL keys, that were generated before
855 // cryptographic binding to the boot level keys was implemented.
856 fn from_0_to_1(tx: &Transaction) -> Result<u32> {
857 tx.execute(
858 "UPDATE persistent.keyentry SET state = ?
859 WHERE
860 id IN (SELECT keyentryid FROM persistent.keyparameter WHERE tag = ?)
861 AND
862 id NOT IN (
863 SELECT keyentryid FROM persistent.blobentry
864 WHERE id IN (
865 SELECT blobentryid FROM persistent.blobmetadata WHERE tag = ?
866 )
867 );",
868 params![KeyLifeCycle::Unreferenced, Tag::MAX_BOOT_LEVEL.0, BlobMetaData::MaxBootLevel],
869 )
870 .context("In from_0_to_1: Failed to delete logical boot level keys.")?;
871 Ok(1)
872 }
873
Janis Danisevskis66784c42021-01-27 08:40:25 -0800874 fn init_tables(tx: &Transaction) -> Result<()> {
875 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700876 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700877 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800878 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700879 domain INTEGER,
880 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800881 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800882 state INTEGER,
883 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700884 NO_PARAMS,
885 )
886 .context("Failed to initialize \"keyentry\" table.")?;
887
Janis Danisevskis66784c42021-01-27 08:40:25 -0800888 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800889 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
890 ON keyentry(id);",
891 NO_PARAMS,
892 )
893 .context("Failed to create index keyentry_id_index.")?;
894
895 tx.execute(
896 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
897 ON keyentry(domain, namespace, alias);",
898 NO_PARAMS,
899 )
900 .context("Failed to create index keyentry_domain_namespace_index.")?;
901
902 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700903 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
904 id INTEGER PRIMARY KEY,
905 subcomponent_type INTEGER,
906 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800907 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700908 NO_PARAMS,
909 )
910 .context("Failed to initialize \"blobentry\" table.")?;
911
Janis Danisevskis66784c42021-01-27 08:40:25 -0800912 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800913 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
914 ON blobentry(keyentryid);",
915 NO_PARAMS,
916 )
917 .context("Failed to create index blobentry_keyentryid_index.")?;
918
919 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800920 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
921 id INTEGER PRIMARY KEY,
922 blobentryid INTEGER,
923 tag INTEGER,
924 data ANY,
925 UNIQUE (blobentryid, tag));",
926 NO_PARAMS,
927 )
928 .context("Failed to initialize \"blobmetadata\" table.")?;
929
930 tx.execute(
931 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
932 ON blobmetadata(blobentryid);",
933 NO_PARAMS,
934 )
935 .context("Failed to create index blobmetadata_blobentryid_index.")?;
936
937 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700938 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000939 keyentryid INTEGER,
940 tag INTEGER,
941 data ANY,
942 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700943 NO_PARAMS,
944 )
945 .context("Failed to initialize \"keyparameter\" table.")?;
946
Janis Danisevskis66784c42021-01-27 08:40:25 -0800947 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800948 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
949 ON keyparameter(keyentryid);",
950 NO_PARAMS,
951 )
952 .context("Failed to create index keyparameter_keyentryid_index.")?;
953
954 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800955 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
956 keyentryid INTEGER,
957 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000958 data ANY,
959 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800960 NO_PARAMS,
961 )
962 .context("Failed to initialize \"keymetadata\" table.")?;
963
Janis Danisevskis66784c42021-01-27 08:40:25 -0800964 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800965 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
966 ON keymetadata(keyentryid);",
967 NO_PARAMS,
968 )
969 .context("Failed to create index keymetadata_keyentryid_index.")?;
970
971 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800972 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700973 id INTEGER UNIQUE,
974 grantee INTEGER,
975 keyentryid INTEGER,
976 access_vector INTEGER);",
977 NO_PARAMS,
978 )
979 .context("Failed to initialize \"grant\" table.")?;
980
Joel Galenson0891bc12020-07-20 10:37:03 -0700981 Ok(())
982 }
983
Seth Moore472fcbb2021-05-12 10:07:51 -0700984 fn make_persistent_path(db_root: &Path) -> Result<String> {
985 // Build the path to the sqlite file.
986 let mut persistent_path = db_root.to_path_buf();
987 persistent_path.push(Self::PERSISTENT_DB_FILENAME);
988
989 // Now convert them to strings prefixed with "file:"
990 let mut persistent_path_str = "file:".to_owned();
991 persistent_path_str.push_str(&persistent_path.to_string_lossy());
992
993 Ok(persistent_path_str)
994 }
995
Matthew Maurerd7815ca2021-05-06 21:58:45 -0700996 fn make_connection(persistent_file: &str) -> Result<Connection> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700997 let conn =
998 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
999
Janis Danisevskis66784c42021-01-27 08:40:25 -08001000 loop {
1001 if let Err(e) = conn
1002 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
1003 .context("Failed to attach database persistent.")
1004 {
1005 if Self::is_locked_error(&e) {
1006 std::thread::sleep(std::time::Duration::from_micros(500));
1007 continue;
1008 } else {
1009 return Err(e);
1010 }
1011 }
1012 break;
1013 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001014
Matthew Maurer4fb19112021-05-06 15:40:44 -07001015 // Drop the cache size from default (2M) to 0.5M
1016 conn.execute("PRAGMA persistent.cache_size = -500;", params![])
1017 .context("Failed to decrease cache size for persistent db")?;
Matthew Maurer4fb19112021-05-06 15:40:44 -07001018
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001019 Ok(conn)
1020 }
1021
Seth Moore78c091f2021-04-09 21:38:30 +00001022 fn do_table_size_query(
1023 &mut self,
1024 storage_type: StatsdStorageType,
1025 query: &str,
1026 params: &[&str],
1027 ) -> Result<Keystore2StorageStats> {
1028 let (total, unused) = self.with_transaction(TransactionBehavior::Deferred, |tx| {
Joel Galensonff79e362021-05-25 16:30:17 -07001029 tx.query_row(query, params_from_iter(params), |row| Ok((row.get(0)?, row.get(1)?)))
Seth Moore78c091f2021-04-09 21:38:30 +00001030 .with_context(|| {
1031 format!("get_storage_stat: Error size of storage type {}", storage_type as i32)
1032 })
1033 .no_gc()
1034 })?;
1035 Ok(Keystore2StorageStats { storage_type, size: total, unused_size: unused })
1036 }
1037
1038 fn get_total_size(&mut self) -> Result<Keystore2StorageStats> {
1039 self.do_table_size_query(
1040 StatsdStorageType::Database,
1041 "SELECT page_count * page_size, freelist_count * page_size
1042 FROM pragma_page_count('persistent'),
1043 pragma_page_size('persistent'),
1044 persistent.pragma_freelist_count();",
1045 &[],
1046 )
1047 }
1048
1049 fn get_table_size(
1050 &mut self,
1051 storage_type: StatsdStorageType,
1052 schema: &str,
1053 table: &str,
1054 ) -> Result<Keystore2StorageStats> {
1055 self.do_table_size_query(
1056 storage_type,
1057 "SELECT pgsize,unused FROM dbstat(?1)
1058 WHERE name=?2 AND aggregate=TRUE;",
1059 &[schema, table],
1060 )
1061 }
1062
1063 /// Fetches a storage statisitics atom for a given storage type. For storage
1064 /// types that map to a table, information about the table's storage is
1065 /// returned. Requests for storage types that are not DB tables return None.
1066 pub fn get_storage_stat(
1067 &mut self,
1068 storage_type: StatsdStorageType,
1069 ) -> Result<Keystore2StorageStats> {
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 {
1073 StatsdStorageType::Database => self.get_total_size(),
1074 StatsdStorageType::KeyEntry => {
1075 self.get_table_size(storage_type, "persistent", "keyentry")
1076 }
1077 StatsdStorageType::KeyEntryIdIndex => {
1078 self.get_table_size(storage_type, "persistent", "keyentry_id_index")
1079 }
1080 StatsdStorageType::KeyEntryDomainNamespaceIndex => {
1081 self.get_table_size(storage_type, "persistent", "keyentry_domain_namespace_index")
1082 }
1083 StatsdStorageType::BlobEntry => {
1084 self.get_table_size(storage_type, "persistent", "blobentry")
1085 }
1086 StatsdStorageType::BlobEntryKeyEntryIdIndex => {
1087 self.get_table_size(storage_type, "persistent", "blobentry_keyentryid_index")
1088 }
1089 StatsdStorageType::KeyParameter => {
1090 self.get_table_size(storage_type, "persistent", "keyparameter")
1091 }
1092 StatsdStorageType::KeyParameterKeyEntryIdIndex => {
1093 self.get_table_size(storage_type, "persistent", "keyparameter_keyentryid_index")
1094 }
1095 StatsdStorageType::KeyMetadata => {
1096 self.get_table_size(storage_type, "persistent", "keymetadata")
1097 }
1098 StatsdStorageType::KeyMetadataKeyEntryIdIndex => {
1099 self.get_table_size(storage_type, "persistent", "keymetadata_keyentryid_index")
1100 }
1101 StatsdStorageType::Grant => self.get_table_size(storage_type, "persistent", "grant"),
1102 StatsdStorageType::AuthToken => {
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
1106 Ok(Keystore2StorageStats {
1107 storage_type,
1108 size: (self.perboot.auth_tokens_len() * std::mem::size_of::<AuthTokenEntry>())
1109 as i64,
1110 unused_size: 0,
1111 })
Seth Moore78c091f2021-04-09 21:38:30 +00001112 }
1113 StatsdStorageType::BlobMetadata => {
1114 self.get_table_size(storage_type, "persistent", "blobmetadata")
1115 }
1116 StatsdStorageType::BlobMetadataBlobEntryIdIndex => {
1117 self.get_table_size(storage_type, "persistent", "blobmetadata_blobentryid_index")
1118 }
1119 _ => Err(anyhow::Error::msg(format!(
1120 "Unsupported storage type: {}",
1121 storage_type as i32
1122 ))),
1123 }
1124 }
1125
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001126 /// This function is intended to be used by the garbage collector.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001127 /// It deletes the blobs given by `blob_ids_to_delete`. It then tries to find up to `max_blobs`
1128 /// superseded key blobs that might need special handling by the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001129 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1130 /// need special handling and returns None.
Janis Danisevskis3395f862021-05-06 10:54:17 -07001131 pub fn handle_next_superseded_blobs(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001132 &mut self,
Janis Danisevskis3395f862021-05-06 10:54:17 -07001133 blob_ids_to_delete: &[i64],
1134 max_blobs: usize,
1135 ) -> Result<Vec<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001136 let _wp = wd::watch_millis("KeystoreDB::handle_next_superseded_blob", 500);
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001137 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis3395f862021-05-06 10:54:17 -07001138 // Delete the given blobs.
1139 for blob_id in blob_ids_to_delete {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001140 tx.execute(
1141 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
Janis Danisevskis3395f862021-05-06 10:54:17 -07001142 params![blob_id],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001143 )
1144 .context("Trying to delete blob metadata.")?;
Janis Danisevskis3395f862021-05-06 10:54:17 -07001145 tx.execute("DELETE FROM persistent.blobentry WHERE id = ?;", params![blob_id])
1146 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001147 }
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07001148
1149 Self::cleanup_unreferenced(tx).context("Trying to cleanup unreferenced.")?;
1150
Janis Danisevskis3395f862021-05-06 10:54:17 -07001151 // Find up to max_blobx more superseded key blobs, load their metadata and return it.
1152 let result: Vec<(i64, Vec<u8>)> = {
1153 let mut stmt = tx
1154 .prepare(
1155 "SELECT id, blob FROM persistent.blobentry
1156 WHERE subcomponent_type = ?
1157 AND (
1158 id NOT IN (
1159 SELECT MAX(id) FROM persistent.blobentry
1160 WHERE subcomponent_type = ?
1161 GROUP BY keyentryid, subcomponent_type
1162 )
1163 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1164 ) LIMIT ?;",
1165 )
1166 .context("Trying to prepare query for superseded blobs.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001167
Janis Danisevskis3395f862021-05-06 10:54:17 -07001168 let rows = stmt
1169 .query_map(
1170 params![
1171 SubComponentType::KEY_BLOB,
1172 SubComponentType::KEY_BLOB,
1173 max_blobs as i64,
1174 ],
1175 |row| Ok((row.get(0)?, row.get(1)?)),
1176 )
1177 .context("Trying to query superseded blob.")?;
1178
1179 rows.collect::<Result<Vec<(i64, Vec<u8>)>, rusqlite::Error>>()
1180 .context("Trying to extract superseded blobs.")?
1181 };
1182
1183 let result = result
1184 .into_iter()
1185 .map(|(blob_id, blob)| {
1186 Ok((blob_id, blob, BlobMetaData::load_from_db(blob_id, tx)?))
1187 })
1188 .collect::<Result<Vec<(i64, Vec<u8>, BlobMetaData)>>>()
1189 .context("Trying to load blob metadata.")?;
1190 if !result.is_empty() {
1191 return Ok(result).no_gc();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001192 }
1193
1194 // We did not find any superseded key blob, so let's remove other superseded blob in
1195 // one transaction.
1196 tx.execute(
1197 "DELETE FROM persistent.blobentry
1198 WHERE NOT subcomponent_type = ?
1199 AND (
1200 id NOT IN (
1201 SELECT MAX(id) FROM persistent.blobentry
1202 WHERE NOT subcomponent_type = ?
1203 GROUP BY keyentryid, subcomponent_type
1204 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1205 );",
1206 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1207 )
1208 .context("Trying to purge superseded blobs.")?;
1209
Janis Danisevskis3395f862021-05-06 10:54:17 -07001210 Ok(vec![]).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001211 })
Janis Danisevskis3395f862021-05-06 10:54:17 -07001212 .context("In handle_next_superseded_blobs.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001213 }
1214
1215 /// This maintenance function should be called only once before the database is used for the
1216 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1217 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1218 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1219 /// Keystore crashed at some point during key generation. Callers may want to log such
1220 /// occurrences.
1221 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1222 /// it to `KeyLifeCycle::Live` may have grants.
1223 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001224 let _wp = wd::watch_millis("KeystoreDB::cleanup_leftovers", 500);
1225
Janis Danisevskis66784c42021-01-27 08:40:25 -08001226 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1227 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001228 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1229 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1230 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001231 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001232 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001233 })
1234 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001235 }
1236
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001237 /// Checks if a key exists with given key type and key descriptor properties.
1238 pub fn key_exists(
1239 &mut self,
1240 domain: Domain,
1241 nspace: i64,
1242 alias: &str,
1243 key_type: KeyType,
1244 ) -> Result<bool> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001245 let _wp = wd::watch_millis("KeystoreDB::key_exists", 500);
1246
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001247 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1248 let key_descriptor =
1249 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1250 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1251 match result {
1252 Ok(_) => Ok(true),
1253 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1254 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1255 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1256 },
1257 }
1258 .no_gc()
1259 })
1260 .context("In key_exists.")
1261 }
1262
Hasini Gunasingheda895552021-01-27 19:34:37 +00001263 /// Stores a super key in the database.
1264 pub fn store_super_key(
1265 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001266 user_id: u32,
Paul Crowley7a658392021-03-18 17:08:20 -07001267 key_type: &SuperKeyType,
1268 blob: &[u8],
1269 blob_metadata: &BlobMetaData,
Paul Crowley8d5b2532021-03-19 10:53:07 -07001270 key_metadata: &KeyMetaData,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001271 ) -> Result<KeyEntry> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001272 let _wp = wd::watch_millis("KeystoreDB::store_super_key", 500);
1273
Hasini Gunasingheda895552021-01-27 19:34:37 +00001274 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1275 let key_id = Self::insert_with_retry(|id| {
1276 tx.execute(
1277 "INSERT into persistent.keyentry
1278 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001279 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001280 params![
1281 id,
1282 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001283 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001284 user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001285 key_type.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001286 KeyLifeCycle::Live,
1287 &KEYSTORE_UUID,
1288 ],
1289 )
1290 })
1291 .context("Failed to insert into keyentry table.")?;
1292
Paul Crowley8d5b2532021-03-19 10:53:07 -07001293 key_metadata.store_in_db(key_id, tx).context("KeyMetaData::store_in_db failed")?;
1294
Hasini Gunasingheda895552021-01-27 19:34:37 +00001295 Self::set_blob_internal(
1296 &tx,
1297 key_id,
1298 SubComponentType::KEY_BLOB,
1299 Some(blob),
1300 Some(blob_metadata),
1301 )
1302 .context("Failed to store key blob.")?;
1303
1304 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1305 .context("Trying to load key components.")
1306 .no_gc()
1307 })
1308 .context("In store_super_key.")
1309 }
1310
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001311 /// Loads super key of a given user, if exists
Paul Crowley7a658392021-03-18 17:08:20 -07001312 pub fn load_super_key(
1313 &mut self,
1314 key_type: &SuperKeyType,
1315 user_id: u32,
1316 ) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001317 let _wp = wd::watch_millis("KeystoreDB::load_super_key", 500);
1318
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001319 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1320 let key_descriptor = KeyDescriptor {
1321 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001322 nspace: user_id as i64,
Paul Crowley7a658392021-03-18 17:08:20 -07001323 alias: Some(key_type.alias.into()),
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001324 blob: None,
1325 };
1326 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1327 match id {
1328 Ok(id) => {
1329 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1330 .context("In load_super_key. Failed to load key entry.")?;
1331 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1332 }
1333 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1334 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1335 _ => Err(error).context("In load_super_key."),
1336 },
1337 }
1338 .no_gc()
1339 })
1340 .context("In load_super_key.")
1341 }
1342
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001343 /// Atomically loads a key entry and associated metadata or creates it using the
1344 /// callback create_new_key callback. The callback is called during a database
1345 /// transaction. This means that implementers should be mindful about using
1346 /// blocking operations such as IPC or grabbing mutexes.
1347 pub fn get_or_create_key_with<F>(
1348 &mut self,
1349 domain: Domain,
1350 namespace: i64,
1351 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001352 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001353 create_new_key: F,
1354 ) -> Result<(KeyIdGuard, KeyEntry)>
1355 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001356 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001357 {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001358 let _wp = wd::watch_millis("KeystoreDB::get_or_create_key_with", 500);
1359
Janis Danisevskis66784c42021-01-27 08:40:25 -08001360 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1361 let id = {
1362 let mut stmt = tx
1363 .prepare(
1364 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001365 WHERE
1366 key_type = ?
1367 AND domain = ?
1368 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001369 AND alias = ?
1370 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001371 )
1372 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1373 let mut rows = stmt
1374 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1375 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001376
Janis Danisevskis66784c42021-01-27 08:40:25 -08001377 db_utils::with_rows_extract_one(&mut rows, |row| {
1378 Ok(match row {
1379 Some(r) => r.get(0).context("Failed to unpack id.")?,
1380 None => None,
1381 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001382 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001383 .context("In get_or_create_key_with.")?
1384 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001385
Janis Danisevskis66784c42021-01-27 08:40:25 -08001386 let (id, entry) = match id {
1387 Some(id) => (
1388 id,
1389 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1390 .context("In get_or_create_key_with.")?,
1391 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001392
Janis Danisevskis66784c42021-01-27 08:40:25 -08001393 None => {
1394 let id = Self::insert_with_retry(|id| {
1395 tx.execute(
1396 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001397 (id, key_type, domain, namespace, alias, state, km_uuid)
1398 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001399 params![
1400 id,
1401 KeyType::Super,
1402 domain.0,
1403 namespace,
1404 alias,
1405 KeyLifeCycle::Live,
1406 km_uuid,
1407 ],
1408 )
1409 })
1410 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001411
Janis Danisevskis66784c42021-01-27 08:40:25 -08001412 let (blob, metadata) =
1413 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001414 Self::set_blob_internal(
1415 &tx,
1416 id,
1417 SubComponentType::KEY_BLOB,
1418 Some(&blob),
1419 Some(&metadata),
1420 )
Paul Crowley7a658392021-03-18 17:08:20 -07001421 .context("In get_or_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001422 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001423 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001424 KeyEntry {
1425 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001426 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001427 pure_cert: false,
1428 ..Default::default()
1429 },
1430 )
1431 }
1432 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001433 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001434 })
1435 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001436 }
1437
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001438 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001439 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1440 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001441 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1442 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001443 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001444 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001445 loop {
1446 match self
1447 .conn
1448 .transaction_with_behavior(behavior)
1449 .context("In with_transaction.")
1450 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1451 .and_then(|(result, tx)| {
1452 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1453 Ok(result)
1454 }) {
1455 Ok(result) => break Ok(result),
1456 Err(e) => {
1457 if Self::is_locked_error(&e) {
1458 std::thread::sleep(std::time::Duration::from_micros(500));
1459 continue;
1460 } else {
1461 return Err(e).context("In with_transaction.");
1462 }
1463 }
1464 }
1465 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001466 .map(|(need_gc, result)| {
1467 if need_gc {
1468 if let Some(ref gc) = self.gc {
1469 gc.notify_gc();
1470 }
1471 }
1472 result
1473 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001474 }
1475
1476 fn is_locked_error(e: &anyhow::Error) -> bool {
Paul Crowleyf61fee72021-03-17 14:38:44 -07001477 matches!(
1478 e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1479 Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. })
1480 | Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseLocked, .. })
1481 )
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001482 }
1483
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001484 /// Creates a new key entry and allocates a new randomized id for the new key.
1485 /// The key id gets associated with a domain and namespace but not with an alias.
1486 /// To complete key generation `rebind_alias` should be called after all of the
1487 /// key artifacts, i.e., blobs and parameters have been associated with the new
1488 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1489 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001490 pub fn create_key_entry(
1491 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001492 domain: &Domain,
1493 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001494 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001495 km_uuid: &Uuid,
1496 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001497 let _wp = wd::watch_millis("KeystoreDB::create_key_entry", 500);
1498
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001499 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001500 Self::create_key_entry_internal(tx, domain, namespace, key_type, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001501 })
1502 .context("In create_key_entry.")
1503 }
1504
1505 fn create_key_entry_internal(
1506 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001507 domain: &Domain,
1508 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001509 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08001510 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001511 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001512 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001513 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001514 _ => {
1515 return Err(KsError::sys())
1516 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1517 }
1518 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001519 Ok(KEY_ID_LOCK.get(
1520 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001521 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001522 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001523 (id, key_type, domain, namespace, alias, state, km_uuid)
1524 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001525 params![
1526 id,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07001527 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001529 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001530 KeyLifeCycle::Existing,
1531 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001532 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001533 )
1534 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001535 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001536 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001537 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001538
Max Bires2b2e6562020-09-22 11:22:36 -07001539 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1540 /// The key id gets associated with a domain and namespace later but not with an alias. The
1541 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1542 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1543 /// a key.
1544 pub fn create_attestation_key_entry(
1545 &mut self,
1546 maced_public_key: &[u8],
1547 raw_public_key: &[u8],
1548 private_key: &[u8],
1549 km_uuid: &Uuid,
1550 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001551 let _wp = wd::watch_millis("KeystoreDB::create_attestation_key_entry", 500);
1552
Max Bires2b2e6562020-09-22 11:22:36 -07001553 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1554 let key_id = KEY_ID_LOCK.get(
1555 Self::insert_with_retry(|id| {
1556 tx.execute(
1557 "INSERT into persistent.keyentry
1558 (id, key_type, domain, namespace, alias, state, km_uuid)
1559 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1560 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1561 )
1562 })
1563 .context("In create_key_entry")?,
1564 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001565 Self::set_blob_internal(
1566 &tx,
1567 key_id.0,
1568 SubComponentType::KEY_BLOB,
1569 Some(private_key),
1570 None,
1571 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001572 let mut metadata = KeyMetaData::new();
1573 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1574 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1575 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001576 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001577 })
1578 .context("In create_attestation_key_entry")
1579 }
1580
Janis Danisevskis377d1002021-01-27 19:07:48 -08001581 /// Set a new blob and associates it with the given key id. Each blob
1582 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001583 /// Each key can have one of each sub component type associated. If more
1584 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001585 /// will get garbage collected.
1586 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1587 /// removed by setting blob to None.
1588 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001589 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001590 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001591 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001592 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001593 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001594 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001595 let _wp = wd::watch_millis("KeystoreDB::set_blob", 500);
1596
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001597 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001598 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001599 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001600 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001601 }
1602
Janis Danisevskiseed69842021-02-18 20:04:10 -08001603 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1604 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1605 /// We use this to insert key blobs into the database which can then be garbage collected
1606 /// lazily by the key garbage collector.
1607 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001608 let _wp = wd::watch_millis("KeystoreDB::set_deleted_blob", 500);
1609
Janis Danisevskiseed69842021-02-18 20:04:10 -08001610 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1611 Self::set_blob_internal(
1612 &tx,
1613 Self::UNASSIGNED_KEY_ID,
1614 SubComponentType::KEY_BLOB,
1615 Some(blob),
1616 Some(blob_metadata),
1617 )
1618 .need_gc()
1619 })
1620 .context("In set_deleted_blob.")
1621 }
1622
Janis Danisevskis377d1002021-01-27 19:07:48 -08001623 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001624 tx: &Transaction,
1625 key_id: i64,
1626 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001627 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001628 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001629 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001630 match (blob, sc_type) {
1631 (Some(blob), _) => {
1632 tx.execute(
1633 "INSERT INTO persistent.blobentry
1634 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1635 params![sc_type, key_id, blob],
1636 )
1637 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001638 if let Some(blob_metadata) = blob_metadata {
1639 let blob_id = tx
1640 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1641 row.get(0)
1642 })
1643 .context("In set_blob_internal: Failed to get new blob id.")?;
1644 blob_metadata
1645 .store_in_db(blob_id, tx)
1646 .context("In set_blob_internal: Trying to store blob metadata.")?;
1647 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001648 }
1649 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1650 tx.execute(
1651 "DELETE FROM persistent.blobentry
1652 WHERE subcomponent_type = ? AND keyentryid = ?;",
1653 params![sc_type, key_id],
1654 )
1655 .context("In set_blob_internal: Failed to delete blob.")?;
1656 }
1657 (None, _) => {
1658 return Err(KsError::sys())
1659 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1660 }
1661 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001662 Ok(())
1663 }
1664
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001665 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1666 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001667 #[cfg(test)]
1668 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001669 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001670 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001671 })
1672 .context("In insert_keyparameter.")
1673 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001674
Janis Danisevskis66784c42021-01-27 08:40:25 -08001675 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001676 tx: &Transaction,
1677 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001678 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001679 ) -> Result<()> {
1680 let mut stmt = tx
1681 .prepare(
1682 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1683 VALUES (?, ?, ?, ?);",
1684 )
1685 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1686
Janis Danisevskis66784c42021-01-27 08:40:25 -08001687 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001688 stmt.insert(params![
1689 key_id.0,
1690 p.get_tag().0,
1691 p.key_parameter_value(),
1692 p.security_level().0
1693 ])
1694 .with_context(|| {
1695 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1696 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001697 }
1698 Ok(())
1699 }
1700
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001701 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001702 #[cfg(test)]
1703 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001704 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001705 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001706 })
1707 .context("In insert_key_metadata.")
1708 }
1709
Max Bires2b2e6562020-09-22 11:22:36 -07001710 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1711 /// on the public key.
1712 pub fn store_signed_attestation_certificate_chain(
1713 &mut self,
1714 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001715 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001716 cert_chain: &[u8],
1717 expiration_date: i64,
1718 km_uuid: &Uuid,
1719 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001720 let _wp = wd::watch_millis("KeystoreDB::store_signed_attestation_certificate_chain", 500);
1721
Max Bires2b2e6562020-09-22 11:22:36 -07001722 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1723 let mut stmt = tx
1724 .prepare(
1725 "SELECT keyentryid
1726 FROM persistent.keymetadata
1727 WHERE tag = ? AND data = ? AND keyentryid IN
1728 (SELECT id
1729 FROM persistent.keyentry
1730 WHERE
1731 alias IS NULL AND
1732 domain IS NULL AND
1733 namespace IS NULL AND
1734 key_type = ? AND
1735 km_uuid = ?);",
1736 )
1737 .context("Failed to store attestation certificate chain.")?;
1738 let mut rows = stmt
1739 .query(params![
1740 KeyMetaData::AttestationRawPubKey,
1741 raw_public_key,
1742 KeyType::Attestation,
1743 km_uuid
1744 ])
1745 .context("Failed to fetch keyid")?;
1746 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1747 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1748 .get(0)
1749 .context("Failed to unpack id.")
1750 })
1751 .context("Failed to get key_id.")?;
1752 let num_updated = tx
1753 .execute(
1754 "UPDATE persistent.keyentry
1755 SET alias = ?
1756 WHERE id = ?;",
1757 params!["signed", key_id],
1758 )
1759 .context("Failed to update alias.")?;
1760 if num_updated != 1 {
1761 return Err(KsError::sys()).context("Alias not updated for the key.");
1762 }
1763 let mut metadata = KeyMetaData::new();
1764 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1765 expiration_date,
1766 )));
1767 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001768 Self::set_blob_internal(
1769 &tx,
1770 key_id,
1771 SubComponentType::CERT_CHAIN,
1772 Some(cert_chain),
1773 None,
1774 )
1775 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001776 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1777 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001778 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001779 })
1780 .context("In store_signed_attestation_certificate_chain: ")
1781 }
1782
1783 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1784 /// currently have a key assigned to it.
1785 pub fn assign_attestation_key(
1786 &mut self,
1787 domain: Domain,
1788 namespace: i64,
1789 km_uuid: &Uuid,
1790 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001791 let _wp = wd::watch_millis("KeystoreDB::assign_attestation_key", 500);
1792
Max Bires2b2e6562020-09-22 11:22:36 -07001793 match domain {
1794 Domain::APP | Domain::SELINUX => {}
1795 _ => {
1796 return Err(KsError::sys()).context(format!(
1797 concat!(
1798 "In assign_attestation_key: Domain {:?} ",
1799 "must be either App or SELinux.",
1800 ),
1801 domain
1802 ));
1803 }
1804 }
1805 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1806 let result = tx
1807 .execute(
1808 "UPDATE persistent.keyentry
1809 SET domain=?1, namespace=?2
1810 WHERE
1811 id =
1812 (SELECT MIN(id)
1813 FROM persistent.keyentry
1814 WHERE ALIAS IS NOT NULL
1815 AND domain IS NULL
1816 AND key_type IS ?3
1817 AND state IS ?4
1818 AND km_uuid IS ?5)
1819 AND
1820 (SELECT COUNT(*)
1821 FROM persistent.keyentry
1822 WHERE domain=?1
1823 AND namespace=?2
1824 AND key_type IS ?3
1825 AND state IS ?4
1826 AND km_uuid IS ?5) = 0;",
1827 params![
1828 domain.0 as u32,
1829 namespace,
1830 KeyType::Attestation,
1831 KeyLifeCycle::Live,
1832 km_uuid,
1833 ],
1834 )
1835 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001836 if result == 0 {
1837 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1838 } else if result > 1 {
1839 return Err(KsError::sys())
1840 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001841 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001842 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001843 })
1844 .context("In assign_attestation_key: ")
1845 }
1846
1847 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1848 /// provisioning server, or the maximum number available if there are not num_keys number of
1849 /// entries in the table.
1850 pub fn fetch_unsigned_attestation_keys(
1851 &mut self,
1852 num_keys: i32,
1853 km_uuid: &Uuid,
1854 ) -> Result<Vec<Vec<u8>>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001855 let _wp = wd::watch_millis("KeystoreDB::fetch_unsigned_attestation_keys", 500);
1856
Max Bires2b2e6562020-09-22 11:22:36 -07001857 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1858 let mut stmt = tx
1859 .prepare(
1860 "SELECT data
1861 FROM persistent.keymetadata
1862 WHERE tag = ? AND keyentryid IN
1863 (SELECT id
1864 FROM persistent.keyentry
1865 WHERE
1866 alias IS NULL AND
1867 domain IS NULL AND
1868 namespace IS NULL AND
1869 key_type = ? AND
1870 km_uuid = ?
1871 LIMIT ?);",
1872 )
1873 .context("Failed to prepare statement")?;
1874 let rows = stmt
1875 .query_map(
1876 params![
1877 KeyMetaData::AttestationMacedPublicKey,
1878 KeyType::Attestation,
1879 km_uuid,
1880 num_keys
1881 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001882 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001883 )?
1884 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1885 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001886 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001887 })
1888 .context("In fetch_unsigned_attestation_keys")
1889 }
1890
1891 /// Removes any keys that have expired as of the current time. Returns the number of keys
1892 /// marked unreferenced that are bound to be garbage collected.
1893 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001894 let _wp = wd::watch_millis("KeystoreDB::delete_expired_attestation_keys", 500);
1895
Max Bires2b2e6562020-09-22 11:22:36 -07001896 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1897 let mut stmt = tx
1898 .prepare(
1899 "SELECT keyentryid, data
1900 FROM persistent.keymetadata
1901 WHERE tag = ? AND keyentryid IN
1902 (SELECT id
1903 FROM persistent.keyentry
1904 WHERE key_type = ?);",
1905 )
1906 .context("Failed to prepare query")?;
1907 let key_ids_to_check = stmt
1908 .query_map(
1909 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1910 |row| Ok((row.get(0)?, row.get(1)?)),
1911 )?
1912 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1913 .context("Failed to get date metadata")?;
1914 let curr_time = DateTime::from_millis_epoch(
1915 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1916 );
1917 let mut num_deleted = 0;
1918 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1919 if Self::mark_unreferenced(&tx, id)? {
1920 num_deleted += 1;
1921 }
1922 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001923 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001924 })
1925 .context("In delete_expired_attestation_keys: ")
1926 }
1927
Max Bires60d7ed12021-03-05 15:59:22 -08001928 /// Deletes all remotely provisioned attestation keys in the system, regardless of the state
1929 /// they are in. This is useful primarily as a testing mechanism.
1930 pub fn delete_all_attestation_keys(&mut self) -> Result<i64> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001931 let _wp = wd::watch_millis("KeystoreDB::delete_all_attestation_keys", 500);
1932
Max Bires60d7ed12021-03-05 15:59:22 -08001933 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1934 let mut stmt = tx
1935 .prepare(
1936 "SELECT id FROM persistent.keyentry
1937 WHERE key_type IS ?;",
1938 )
1939 .context("Failed to prepare statement")?;
1940 let keys_to_delete = stmt
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001941 .query_map(params![KeyType::Attestation], |row| row.get(0))?
Max Bires60d7ed12021-03-05 15:59:22 -08001942 .collect::<rusqlite::Result<Vec<i64>>>()
1943 .context("Failed to execute statement")?;
1944 let num_deleted = keys_to_delete
1945 .iter()
1946 .map(|id| Self::mark_unreferenced(&tx, *id))
1947 .collect::<Result<Vec<bool>>>()
1948 .context("Failed to execute mark_unreferenced on a keyid")?
1949 .into_iter()
1950 .filter(|result| *result)
1951 .count() as i64;
1952 Ok(num_deleted).do_gc(num_deleted != 0)
1953 })
1954 .context("In delete_all_attestation_keys: ")
1955 }
1956
Max Bires2b2e6562020-09-22 11:22:36 -07001957 /// Counts the number of keys that will expire by the provided epoch date and the number of
1958 /// keys not currently assigned to a domain.
1959 pub fn get_attestation_pool_status(
1960 &mut self,
1961 date: i64,
1962 km_uuid: &Uuid,
1963 ) -> Result<AttestationPoolStatus> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07001964 let _wp = wd::watch_millis("KeystoreDB::get_attestation_pool_status", 500);
1965
Max Bires2b2e6562020-09-22 11:22:36 -07001966 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1967 let mut stmt = tx.prepare(
1968 "SELECT data
1969 FROM persistent.keymetadata
1970 WHERE tag = ? AND keyentryid IN
1971 (SELECT id
1972 FROM persistent.keyentry
1973 WHERE alias IS NOT NULL
1974 AND key_type = ?
1975 AND km_uuid = ?
1976 AND state = ?);",
1977 )?;
1978 let times = stmt
1979 .query_map(
1980 params![
1981 KeyMetaData::AttestationExpirationDate,
1982 KeyType::Attestation,
1983 km_uuid,
1984 KeyLifeCycle::Live
1985 ],
Janis Danisevskis82e55f92021-05-06 14:55:48 -07001986 |row| row.get(0),
Max Bires2b2e6562020-09-22 11:22:36 -07001987 )?
1988 .collect::<rusqlite::Result<Vec<DateTime>>>()
1989 .context("Failed to execute metadata statement")?;
1990 let expiring =
1991 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1992 as i32;
1993 stmt = tx.prepare(
1994 "SELECT alias, domain
1995 FROM persistent.keyentry
1996 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1997 )?;
1998 let rows = stmt
1999 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
2000 Ok((row.get(0)?, row.get(1)?))
2001 })?
2002 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
2003 .context("Failed to execute keyentry statement")?;
2004 let mut unassigned = 0i32;
2005 let mut attested = 0i32;
2006 let total = rows.len() as i32;
2007 for (alias, domain) in rows {
2008 match (alias, domain) {
2009 (Some(_alias), None) => {
2010 attested += 1;
2011 unassigned += 1;
2012 }
2013 (Some(_alias), Some(_domain)) => {
2014 attested += 1;
2015 }
2016 _ => {}
2017 }
2018 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002019 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07002020 })
2021 .context("In get_attestation_pool_status: ")
2022 }
2023
2024 /// Fetches the private key and corresponding certificate chain assigned to a
2025 /// domain/namespace pair. Will either return nothing if the domain/namespace is
2026 /// not assigned, or one CertificateChain.
2027 pub fn retrieve_attestation_key_and_cert_chain(
2028 &mut self,
2029 domain: Domain,
2030 namespace: i64,
2031 km_uuid: &Uuid,
2032 ) -> Result<Option<CertificateChain>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002033 let _wp = wd::watch_millis("KeystoreDB::retrieve_attestation_key_and_cert_chain", 500);
2034
Max Bires2b2e6562020-09-22 11:22:36 -07002035 match domain {
2036 Domain::APP | Domain::SELINUX => {}
2037 _ => {
2038 return Err(KsError::sys())
2039 .context(format!("Domain {:?} must be either App or SELinux.", domain));
2040 }
2041 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002042 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2043 let mut stmt = tx.prepare(
2044 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07002045 FROM persistent.blobentry
2046 WHERE keyentryid IN
2047 (SELECT id
2048 FROM persistent.keyentry
2049 WHERE key_type = ?
2050 AND domain = ?
2051 AND namespace = ?
2052 AND state = ?
2053 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002054 )?;
2055 let rows = stmt
2056 .query_map(
2057 params![
2058 KeyType::Attestation,
2059 domain.0 as u32,
2060 namespace,
2061 KeyLifeCycle::Live,
2062 km_uuid
2063 ],
2064 |row| Ok((row.get(0)?, row.get(1)?)),
2065 )?
2066 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08002067 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002068 if rows.is_empty() {
2069 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08002070 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002071 return Err(KsError::sys()).context(format!(
2072 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08002073 "Expected to get a single attestation",
2074 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
2075 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002076 rows.len()
2077 ));
Max Bires2b2e6562020-09-22 11:22:36 -07002078 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002079 let mut km_blob: Vec<u8> = Vec::new();
2080 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08002081 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002082 for row in rows {
2083 let sub_type: SubComponentType = row.0;
2084 match sub_type {
2085 SubComponentType::KEY_BLOB => {
2086 km_blob = row.1;
2087 }
2088 SubComponentType::CERT_CHAIN => {
2089 cert_chain_blob = row.1;
2090 }
Max Biresb2e1d032021-02-08 21:35:05 -08002091 SubComponentType::CERT => {
2092 batch_cert_blob = row.1;
2093 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002094 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
2095 }
2096 }
2097 Ok(Some(CertificateChain {
2098 private_key: ZVec::try_from(km_blob)?,
Max Bires97f96812021-02-23 23:44:57 -08002099 batch_cert: batch_cert_blob,
2100 cert_chain: cert_chain_blob,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002101 }))
2102 .no_gc()
2103 })
Max Biresb2e1d032021-02-08 21:35:05 -08002104 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07002105 }
2106
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002107 /// Updates the alias column of the given key id `newid` with the given alias,
2108 /// and atomically, removes the alias, domain, and namespace from another row
2109 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002110 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
2111 /// collector.
2112 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002113 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002114 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07002115 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002116 domain: &Domain,
2117 namespace: &i64,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002118 key_type: KeyType,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002119 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002120 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002121 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07002122 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002123 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002124 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002125 domain
2126 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07002127 }
2128 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002129 let updated = tx
2130 .execute(
2131 "UPDATE persistent.keyentry
2132 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002133 WHERE alias = ? AND domain = ? AND namespace = ? AND key_type = ?;",
2134 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace, key_type],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002135 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002136 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002137 let result = tx
2138 .execute(
2139 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002140 SET alias = ?, state = ?
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002141 WHERE id = ? AND domain = ? AND namespace = ? AND state = ? AND key_type = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002142 params![
2143 alias,
2144 KeyLifeCycle::Live,
2145 newid.0,
2146 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002147 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08002148 KeyLifeCycle::Existing,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002149 key_type,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002150 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07002151 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002152 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07002153 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07002154 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002155 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07002156 result
2157 ));
2158 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002159 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002160 }
2161
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002162 /// Moves the key given by KeyIdGuard to the new location at `destination`. If the destination
2163 /// is already occupied by a key, this function fails with `ResponseCode::INVALID_ARGUMENT`.
2164 pub fn migrate_key_namespace(
2165 &mut self,
2166 key_id_guard: KeyIdGuard,
2167 destination: &KeyDescriptor,
2168 caller_uid: u32,
2169 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
2170 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002171 let _wp = wd::watch_millis("KeystoreDB::migrate_key_namespace", 500);
2172
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07002173 let destination = match destination.domain {
2174 Domain::APP => KeyDescriptor { nspace: caller_uid as i64, ..(*destination).clone() },
2175 Domain::SELINUX => (*destination).clone(),
2176 domain => {
2177 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2178 .context(format!("Domain {:?} must be either APP or SELINUX.", domain));
2179 }
2180 };
2181
2182 // Security critical: Must return immediately on failure. Do not remove the '?';
2183 check_permission(&destination)
2184 .context("In migrate_key_namespace: Trying to check permission.")?;
2185
2186 let alias = destination
2187 .alias
2188 .as_ref()
2189 .ok_or(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2190 .context("In migrate_key_namespace: Alias must be specified.")?;
2191
2192 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2193 // Query the destination location. If there is a key, the migration request fails.
2194 if tx
2195 .query_row(
2196 "SELECT id FROM persistent.keyentry
2197 WHERE alias = ? AND domain = ? AND namespace = ?;",
2198 params![alias, destination.domain.0, destination.nspace],
2199 |_| Ok(()),
2200 )
2201 .optional()
2202 .context("Failed to query destination.")?
2203 .is_some()
2204 {
2205 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2206 .context("Target already exists.");
2207 }
2208
2209 let updated = tx
2210 .execute(
2211 "UPDATE persistent.keyentry
2212 SET alias = ?, domain = ?, namespace = ?
2213 WHERE id = ?;",
2214 params![alias, destination.domain.0, destination.nspace, key_id_guard.id()],
2215 )
2216 .context("Failed to update key entry.")?;
2217
2218 if updated != 1 {
2219 return Err(KsError::sys())
2220 .context(format!("Update succeeded, but {} rows were updated.", updated));
2221 }
2222 Ok(()).no_gc()
2223 })
2224 .context("In migrate_key_namespace:")
2225 }
2226
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002227 /// Store a new key in a single transaction.
2228 /// The function creates a new key entry, populates the blob, key parameter, and metadata
2229 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002230 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
2231 /// is now unreferenced and needs to be collected.
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002232 #[allow(clippy::clippy::too_many_arguments)]
Janis Danisevskis66784c42021-01-27 08:40:25 -08002233 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002234 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002235 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002236 key_type: KeyType,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002237 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002238 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08002239 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002240 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08002241 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002242 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002243 let _wp = wd::watch_millis("KeystoreDB::store_new_key", 500);
2244
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002245 let (alias, domain, namespace) = match key {
2246 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2247 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2248 (alias, key.domain, nspace)
2249 }
2250 _ => {
2251 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2252 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2253 }
2254 };
2255 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002256 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002257 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002258 let (blob, blob_metadata) = *blob_info;
2259 Self::set_blob_internal(
2260 tx,
2261 key_id.id(),
2262 SubComponentType::KEY_BLOB,
2263 Some(blob),
2264 Some(&blob_metadata),
2265 )
2266 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002267 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002268 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002269 .context("Trying to insert the certificate.")?;
2270 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002271 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002272 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 tx,
2274 key_id.id(),
2275 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002276 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002277 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002278 )
2279 .context("Trying to insert the certificate chain.")?;
2280 }
2281 Self::insert_keyparameter_internal(tx, &key_id, params)
2282 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002283 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002284 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace, key_type)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002285 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002286 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002287 })
2288 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002289 }
2290
Janis Danisevskis377d1002021-01-27 19:07:48 -08002291 /// Store a new certificate
2292 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2293 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002294 pub fn store_new_certificate(
2295 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002296 key: &KeyDescriptor,
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002297 key_type: KeyType,
Max Bires8e93d2b2021-01-14 13:17:59 -08002298 cert: &[u8],
2299 km_uuid: &Uuid,
2300 ) -> Result<KeyIdGuard> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002301 let _wp = wd::watch_millis("KeystoreDB::store_new_certificate", 500);
2302
Janis Danisevskis377d1002021-01-27 19:07:48 -08002303 let (alias, domain, namespace) = match key {
2304 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2305 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2306 (alias, key.domain, nspace)
2307 }
2308 _ => {
2309 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2310 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2311 )
2312 }
2313 };
2314 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002315 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, key_type, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002316 .context("Trying to create new key entry.")?;
2317
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002318 Self::set_blob_internal(
2319 tx,
2320 key_id.id(),
2321 SubComponentType::CERT_CHAIN,
2322 Some(cert),
2323 None,
2324 )
2325 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002326
2327 let mut metadata = KeyMetaData::new();
2328 metadata.add(KeyMetaEntry::CreationDate(
2329 DateTime::now().context("Trying to make creation time.")?,
2330 ));
2331
2332 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2333
Janis Danisevskis0cabd712021-05-25 11:07:10 -07002334 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace, key_type)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002335 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002336 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002337 })
2338 .context("In store_new_certificate.")
2339 }
2340
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002341 // Helper function loading the key_id given the key descriptor
2342 // tuple comprising domain, namespace, and alias.
2343 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002344 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002345 let alias = key
2346 .alias
2347 .as_ref()
2348 .map_or_else(|| Err(KsError::sys()), Ok)
2349 .context("In load_key_entry_id: Alias must be specified.")?;
2350 let mut stmt = tx
2351 .prepare(
2352 "SELECT id FROM persistent.keyentry
2353 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002354 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002355 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002356 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002357 AND alias = ?
2358 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002359 )
2360 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2361 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002362 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002363 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002364 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002365 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002366 .get(0)
2367 .context("Failed to unpack id.")
2368 })
2369 .context("In load_key_entry_id.")
2370 }
2371
2372 /// This helper function completes the access tuple of a key, which is required
2373 /// to perform access control. The strategy depends on the `domain` field in the
2374 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002375 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002376 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002377 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002378 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002379 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002380 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002381 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002382 /// `namespace`.
2383 /// In each case the information returned is sufficient to perform the access
2384 /// check and the key id can be used to load further key artifacts.
2385 fn load_access_tuple(
2386 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002387 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002388 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002389 caller_uid: u32,
2390 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2391 match key.domain {
2392 // Domain App or SELinux. In this case we load the key_id from
2393 // the keyentry database for further loading of key components.
2394 // We already have the full access tuple to perform access control.
2395 // The only distinction is that we use the caller_uid instead
2396 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002397 // Domain::APP.
2398 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002399 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002400 if access_key.domain == Domain::APP {
2401 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002402 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002403 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002404 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002405
2406 Ok((key_id, access_key, None))
2407 }
2408
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002409 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002410 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002411 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002412 let mut stmt = tx
2413 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002414 "SELECT keyentryid, access_vector FROM persistent.grant
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002415 WHERE grantee = ? AND id = ? AND
2416 (SELECT state FROM persistent.keyentry WHERE id = keyentryid) = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002417 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002418 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002419 let mut rows = stmt
Hasini Gunasinghee70a0ec2021-05-10 21:12:34 +00002420 .query(params![caller_uid as i64, key.nspace, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002421 .context("Domain:Grant: query failed.")?;
2422 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002423 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002424 let r =
2425 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002426 Ok((
2427 r.get(0).context("Failed to unpack key_id.")?,
2428 r.get(1).context("Failed to unpack access_vector.")?,
2429 ))
2430 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002431 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002432 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002433 }
2434
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002435 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002436 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002437 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002438 let (domain, namespace): (Domain, i64) = {
2439 let mut stmt = tx
2440 .prepare(
2441 "SELECT domain, namespace FROM persistent.keyentry
2442 WHERE
2443 id = ?
2444 AND state = ?;",
2445 )
2446 .context("Domain::KEY_ID: prepare statement failed")?;
2447 let mut rows = stmt
2448 .query(params![key.nspace, KeyLifeCycle::Live])
2449 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002450 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002451 let r =
2452 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002453 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002454 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002455 r.get(1).context("Failed to unpack namespace.")?,
2456 ))
2457 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002458 .context("Domain::KEY_ID.")?
2459 };
2460
2461 // We may use a key by id after loading it by grant.
2462 // In this case we have to check if the caller has a grant for this particular
2463 // key. We can skip this if we already know that the caller is the owner.
2464 // But we cannot know this if domain is anything but App. E.g. in the case
2465 // of Domain::SELINUX we have to speculatively check for grants because we have to
2466 // consult the SEPolicy before we know if the caller is the owner.
2467 let access_vector: Option<KeyPermSet> =
2468 if domain != Domain::APP || namespace != caller_uid as i64 {
2469 let access_vector: Option<i32> = tx
2470 .query_row(
2471 "SELECT access_vector FROM persistent.grant
2472 WHERE grantee = ? AND keyentryid = ?;",
2473 params![caller_uid as i64, key.nspace],
2474 |row| row.get(0),
2475 )
2476 .optional()
2477 .context("Domain::KEY_ID: query grant failed.")?;
2478 access_vector.map(|p| p.into())
2479 } else {
2480 None
2481 };
2482
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002483 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002484 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002485 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002486 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002487
Janis Danisevskis45760022021-01-19 16:34:10 -08002488 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002489 }
2490 _ => Err(anyhow!(KsError::sys())),
2491 }
2492 }
2493
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002494 fn load_blob_components(
2495 key_id: i64,
2496 load_bits: KeyEntryLoadBits,
2497 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002498 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002499 let mut stmt = tx
2500 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002501 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002502 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2503 )
2504 .context("In load_blob_components: prepare statement failed.")?;
2505
2506 let mut rows =
2507 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2508
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002509 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002510 let mut cert_blob: Option<Vec<u8>> = None;
2511 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002512 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002513 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002514 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002515 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002516 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002517 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2518 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002519 key_blob = Some((
2520 row.get(0).context("Failed to extract key blob id.")?,
2521 row.get(2).context("Failed to extract key blob.")?,
2522 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002523 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002524 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002525 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002526 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002527 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002528 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002529 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002530 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002531 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002532 (SubComponentType::CERT, _, _)
2533 | (SubComponentType::CERT_CHAIN, _, _)
2534 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002535 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2536 }
2537 Ok(())
2538 })
2539 .context("In load_blob_components.")?;
2540
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002541 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2542 Ok(Some((
2543 blob,
2544 BlobMetaData::load_from_db(blob_id, tx)
2545 .context("In load_blob_components: Trying to load blob_metadata.")?,
2546 )))
2547 })?;
2548
2549 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002550 }
2551
2552 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2553 let mut stmt = tx
2554 .prepare(
2555 "SELECT tag, data, security_level from persistent.keyparameter
2556 WHERE keyentryid = ?;",
2557 )
2558 .context("In load_key_parameters: prepare statement failed.")?;
2559
2560 let mut parameters: Vec<KeyParameter> = Vec::new();
2561
2562 let mut rows =
2563 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002564 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002565 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2566 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002567 parameters.push(
2568 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2569 .context("Failed to read KeyParameter.")?,
2570 );
2571 Ok(())
2572 })
2573 .context("In load_key_parameters.")?;
2574
2575 Ok(parameters)
2576 }
2577
Qi Wub9433b52020-12-01 14:52:46 +08002578 /// Decrements the usage count of a limited use key. This function first checks whether the
2579 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2580 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2581 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002582 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002583 let _wp = wd::watch_millis("KeystoreDB::check_and_update_key_usage_count", 500);
2584
Qi Wub9433b52020-12-01 14:52:46 +08002585 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2586 let limit: Option<i32> = tx
2587 .query_row(
2588 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2589 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2590 |row| row.get(0),
2591 )
2592 .optional()
2593 .context("Trying to load usage count")?;
2594
2595 let limit = limit
2596 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2597 .context("The Key no longer exists. Key is exhausted.")?;
2598
2599 tx.execute(
2600 "UPDATE persistent.keyparameter
2601 SET data = data - 1
2602 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2603 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2604 )
2605 .context("Failed to update key usage count.")?;
2606
2607 match limit {
2608 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002609 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002610 .context("Trying to mark limited use key for deletion."),
2611 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002612 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002613 }
2614 })
2615 .context("In check_and_update_key_usage_count.")
2616 }
2617
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002618 /// Load a key entry by the given key descriptor.
2619 /// It uses the `check_permission` callback to verify if the access is allowed
2620 /// given the key access tuple read from the database using `load_access_tuple`.
2621 /// With `load_bits` the caller may specify which blobs shall be loaded from
2622 /// the blob database.
2623 pub fn load_key_entry(
2624 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002625 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002626 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002627 load_bits: KeyEntryLoadBits,
2628 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002629 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2630 ) -> Result<(KeyIdGuard, KeyEntry)> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002631 let _wp = wd::watch_millis("KeystoreDB::load_key_entry", 500);
2632
Janis Danisevskis66784c42021-01-27 08:40:25 -08002633 loop {
2634 match self.load_key_entry_internal(
2635 key,
2636 key_type,
2637 load_bits,
2638 caller_uid,
2639 &check_permission,
2640 ) {
2641 Ok(result) => break Ok(result),
2642 Err(e) => {
2643 if Self::is_locked_error(&e) {
2644 std::thread::sleep(std::time::Duration::from_micros(500));
2645 continue;
2646 } else {
2647 return Err(e).context("In load_key_entry.");
2648 }
2649 }
2650 }
2651 }
2652 }
2653
2654 fn load_key_entry_internal(
2655 &mut self,
2656 key: &KeyDescriptor,
2657 key_type: KeyType,
2658 load_bits: KeyEntryLoadBits,
2659 caller_uid: u32,
2660 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002661 ) -> Result<(KeyIdGuard, KeyEntry)> {
2662 // KEY ID LOCK 1/2
2663 // If we got a key descriptor with a key id we can get the lock right away.
2664 // Otherwise we have to defer it until we know the key id.
2665 let key_id_guard = match key.domain {
2666 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2667 _ => None,
2668 };
2669
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002670 let tx = self
2671 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002672 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002673 .context("In load_key_entry: Failed to initialize transaction.")?;
2674
2675 // Load the key_id and complete the access control tuple.
2676 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002677 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2678 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002679
2680 // Perform access control. It is vital that we return here if the permission is denied.
2681 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002682 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002683
Janis Danisevskisaec14592020-11-12 09:41:49 -08002684 // KEY ID LOCK 2/2
2685 // If we did not get a key id lock by now, it was because we got a key descriptor
2686 // without a key id. At this point we got the key id, so we can try and get a lock.
2687 // However, we cannot block here, because we are in the middle of the transaction.
2688 // So first we try to get the lock non blocking. If that fails, we roll back the
2689 // transaction and block until we get the lock. After we successfully got the lock,
2690 // we start a new transaction and load the access tuple again.
2691 //
2692 // We don't need to perform access control again, because we already established
2693 // that the caller had access to the given key. But we need to make sure that the
2694 // key id still exists. So we have to load the key entry by key id this time.
2695 let (key_id_guard, tx) = match key_id_guard {
2696 None => match KEY_ID_LOCK.try_get(key_id) {
2697 None => {
2698 // Roll back the transaction.
2699 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002700
Janis Danisevskisaec14592020-11-12 09:41:49 -08002701 // Block until we have a key id lock.
2702 let key_id_guard = KEY_ID_LOCK.get(key_id);
2703
2704 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002705 let tx = self
2706 .conn
2707 .unchecked_transaction()
2708 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002709
2710 Self::load_access_tuple(
2711 &tx,
2712 // This time we have to load the key by the retrieved key id, because the
2713 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002714 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002715 domain: Domain::KEY_ID,
2716 nspace: key_id,
2717 ..Default::default()
2718 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002719 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002720 caller_uid,
2721 )
2722 .context("In load_key_entry. (deferred key lock)")?;
2723 (key_id_guard, tx)
2724 }
2725 Some(l) => (l, tx),
2726 },
2727 Some(key_id_guard) => (key_id_guard, tx),
2728 };
2729
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002730 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2731 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002732
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002733 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2734
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002735 Ok((key_id_guard, key_entry))
2736 }
2737
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002738 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002739 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002740 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2741 .context("Trying to delete keyentry.")?;
2742 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2743 .context("Trying to delete keymetadata.")?;
2744 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2745 .context("Trying to delete keyparameters.")?;
2746 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2747 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002748 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002749 }
2750
2751 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002752 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002753 pub fn unbind_key(
2754 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002755 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002756 key_type: KeyType,
2757 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002758 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002759 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002760 let _wp = wd::watch_millis("KeystoreDB::unbind_key", 500);
2761
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002762 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2763 let (key_id, access_key_descriptor, access_vector) =
2764 Self::load_access_tuple(tx, key, key_type, caller_uid)
2765 .context("Trying to get access tuple.")?;
2766
2767 // Perform access control. It is vital that we return here if the permission is denied.
2768 // So do not touch that '?' at the end.
2769 check_permission(&access_key_descriptor, access_vector)
2770 .context("While checking permission.")?;
2771
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002772 Self::mark_unreferenced(tx, key_id)
2773 .map(|need_gc| (need_gc, ()))
2774 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002775 })
2776 .context("In unbind_key.")
2777 }
2778
Max Bires8e93d2b2021-01-14 13:17:59 -08002779 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2780 tx.query_row(
2781 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2782 params![key_id],
2783 |row| row.get(0),
2784 )
2785 .context("In get_key_km_uuid.")
2786 }
2787
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002788 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2789 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2790 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002791 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_namespace", 500);
2792
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002793 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2794 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2795 .context("In unbind_keys_for_namespace.");
2796 }
2797 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2798 tx.execute(
2799 "DELETE FROM persistent.keymetadata
2800 WHERE keyentryid IN (
2801 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002802 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002803 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002804 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002805 )
2806 .context("Trying to delete keymetadata.")?;
2807 tx.execute(
2808 "DELETE FROM persistent.keyparameter
2809 WHERE keyentryid IN (
2810 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002811 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002812 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002813 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002814 )
2815 .context("Trying to delete keyparameters.")?;
2816 tx.execute(
2817 "DELETE FROM persistent.grant
2818 WHERE keyentryid IN (
2819 SELECT id FROM persistent.keyentry
Janis Danisevskisb146f312021-05-06 15:05:45 -07002820 WHERE domain = ? AND namespace = ? AND key_type = ?
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002821 );",
Janis Danisevskisb146f312021-05-06 15:05:45 -07002822 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002823 )
2824 .context("Trying to delete grants.")?;
2825 tx.execute(
Janis Danisevskisb146f312021-05-06 15:05:45 -07002826 "DELETE FROM persistent.keyentry
2827 WHERE domain = ? AND namespace = ? AND key_type = ?;",
2828 params![domain.0, namespace, KeyType::Client],
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002829 )
2830 .context("Trying to delete keyentry.")?;
2831 Ok(()).need_gc()
2832 })
2833 .context("In unbind_keys_for_namespace")
2834 }
2835
Janis Danisevskis3cba10d2021-05-06 17:02:19 -07002836 fn cleanup_unreferenced(tx: &Transaction) -> Result<()> {
2837 let _wp = wd::watch_millis("KeystoreDB::cleanup_unreferenced", 500);
2838 {
2839 tx.execute(
2840 "DELETE FROM persistent.keymetadata
2841 WHERE keyentryid IN (
2842 SELECT id FROM persistent.keyentry
2843 WHERE state = ?
2844 );",
2845 params![KeyLifeCycle::Unreferenced],
2846 )
2847 .context("Trying to delete keymetadata.")?;
2848 tx.execute(
2849 "DELETE FROM persistent.keyparameter
2850 WHERE keyentryid IN (
2851 SELECT id FROM persistent.keyentry
2852 WHERE state = ?
2853 );",
2854 params![KeyLifeCycle::Unreferenced],
2855 )
2856 .context("Trying to delete keyparameters.")?;
2857 tx.execute(
2858 "DELETE FROM persistent.grant
2859 WHERE keyentryid IN (
2860 SELECT id FROM persistent.keyentry
2861 WHERE state = ?
2862 );",
2863 params![KeyLifeCycle::Unreferenced],
2864 )
2865 .context("Trying to delete grants.")?;
2866 tx.execute(
2867 "DELETE FROM persistent.keyentry
2868 WHERE state = ?;",
2869 params![KeyLifeCycle::Unreferenced],
2870 )
2871 .context("Trying to delete keyentry.")?;
2872 Result::<()>::Ok(())
2873 }
2874 .context("In cleanup_unreferenced")
2875 }
2876
Hasini Gunasingheda895552021-01-27 19:34:37 +00002877 /// Delete the keys created on behalf of the user, denoted by the user id.
2878 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2879 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2880 /// The caller of this function should notify the gc if the returned value is true.
2881 pub fn unbind_keys_for_user(
2882 &mut self,
2883 user_id: u32,
2884 keep_non_super_encrypted_keys: bool,
2885 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002886 let _wp = wd::watch_millis("KeystoreDB::unbind_keys_for_user", 500);
2887
Hasini Gunasingheda895552021-01-27 19:34:37 +00002888 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2889 let mut stmt = tx
2890 .prepare(&format!(
2891 "SELECT id from persistent.keyentry
2892 WHERE (
2893 key_type = ?
2894 AND domain = ?
2895 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2896 AND state = ?
2897 ) OR (
2898 key_type = ?
2899 AND namespace = ?
2900 AND alias = ?
2901 AND state = ?
2902 );",
2903 aid_user_offset = AID_USER_OFFSET
2904 ))
2905 .context(concat!(
2906 "In unbind_keys_for_user. ",
2907 "Failed to prepare the query to find the keys created by apps."
2908 ))?;
2909
2910 let mut rows = stmt
2911 .query(params![
2912 // WHERE client key:
2913 KeyType::Client,
2914 Domain::APP.0 as u32,
2915 user_id,
2916 KeyLifeCycle::Live,
2917 // OR super key:
2918 KeyType::Super,
2919 user_id,
Paul Crowley7a658392021-03-18 17:08:20 -07002920 USER_SUPER_KEY.alias,
Hasini Gunasingheda895552021-01-27 19:34:37 +00002921 KeyLifeCycle::Live
2922 ])
2923 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2924
2925 let mut key_ids: Vec<i64> = Vec::new();
2926 db_utils::with_rows_extract_all(&mut rows, |row| {
2927 key_ids
2928 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2929 Ok(())
2930 })
2931 .context("In unbind_keys_for_user.")?;
2932
2933 let mut notify_gc = false;
2934 for key_id in key_ids {
2935 if keep_non_super_encrypted_keys {
2936 // Load metadata and filter out non-super-encrypted keys.
2937 if let (_, Some((_, blob_metadata)), _, _) =
2938 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2939 .context("In unbind_keys_for_user: Trying to load blob info.")?
2940 {
2941 if blob_metadata.encrypted_by().is_none() {
2942 continue;
2943 }
2944 }
2945 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002946 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002947 .context("In unbind_keys_for_user.")?
2948 || notify_gc;
2949 }
2950 Ok(()).do_gc(notify_gc)
2951 })
2952 .context("In unbind_keys_for_user.")
2953 }
2954
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002955 fn load_key_components(
2956 tx: &Transaction,
2957 load_bits: KeyEntryLoadBits,
2958 key_id: i64,
2959 ) -> Result<KeyEntry> {
2960 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2961
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002962 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002963 Self::load_blob_components(key_id, load_bits, &tx)
2964 .context("In load_key_components.")?;
2965
Max Bires8e93d2b2021-01-14 13:17:59 -08002966 let parameters = Self::load_key_parameters(key_id, &tx)
2967 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002968
Max Bires8e93d2b2021-01-14 13:17:59 -08002969 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2970 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002971
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002972 Ok(KeyEntry {
2973 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002974 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002975 cert: cert_blob,
2976 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002977 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002978 parameters,
2979 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002980 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002981 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002982 }
2983
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002984 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2985 /// The key descriptors will have the domain, nspace, and alias field set.
2986 /// Domain must be APP or SELINUX, the caller must make sure of that.
Janis Danisevskis18313832021-05-17 13:30:32 -07002987 pub fn list(
2988 &mut self,
2989 domain: Domain,
2990 namespace: i64,
2991 key_type: KeyType,
2992 ) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07002993 let _wp = wd::watch_millis("KeystoreDB::list", 500);
2994
Janis Danisevskis66784c42021-01-27 08:40:25 -08002995 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2996 let mut stmt = tx
2997 .prepare(
2998 "SELECT alias FROM persistent.keyentry
Janis Danisevskis18313832021-05-17 13:30:32 -07002999 WHERE domain = ?
3000 AND namespace = ?
3001 AND alias IS NOT NULL
3002 AND state = ?
3003 AND key_type = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003004 )
3005 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003006
Janis Danisevskis66784c42021-01-27 08:40:25 -08003007 let mut rows = stmt
Janis Danisevskis18313832021-05-17 13:30:32 -07003008 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live, key_type])
Janis Danisevskis66784c42021-01-27 08:40:25 -08003009 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003010
Janis Danisevskis66784c42021-01-27 08:40:25 -08003011 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
3012 db_utils::with_rows_extract_all(&mut rows, |row| {
3013 descriptors.push(KeyDescriptor {
3014 domain,
3015 nspace: namespace,
3016 alias: Some(row.get(0).context("Trying to extract alias.")?),
3017 blob: None,
3018 });
3019 Ok(())
3020 })
3021 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003022 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003023 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08003024 }
3025
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003026 /// Adds a grant to the grant table.
3027 /// Like `load_key_entry` this function loads the access tuple before
3028 /// it uses the callback for a permission check. Upon success,
3029 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
3030 /// grant table. The new row will have a randomized id, which is used as
3031 /// grant id in the namespace field of the resulting KeyDescriptor.
3032 pub fn grant(
3033 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003034 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003035 caller_uid: u32,
3036 grantee_uid: u32,
3037 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003038 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003039 ) -> Result<KeyDescriptor> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003040 let _wp = wd::watch_millis("KeystoreDB::grant", 500);
3041
Janis Danisevskis66784c42021-01-27 08:40:25 -08003042 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3043 // Load the key_id and complete the access control tuple.
3044 // We ignore the access vector here because grants cannot be granted.
3045 // The access vector returned here expresses the permissions the
3046 // grantee has if key.domain == Domain::GRANT. But this vector
3047 // cannot include the grant permission by design, so there is no way the
3048 // subsequent permission check can pass.
3049 // We could check key.domain == Domain::GRANT and fail early.
3050 // But even if we load the access tuple by grant here, the permission
3051 // check denies the attempt to create a grant by grant descriptor.
3052 let (key_id, access_key_descriptor, _) =
3053 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3054 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003055
Janis Danisevskis66784c42021-01-27 08:40:25 -08003056 // Perform access control. It is vital that we return here if the permission
3057 // was denied. So do not touch that '?' at the end of the line.
3058 // This permission check checks if the caller has the grant permission
3059 // for the given key and in addition to all of the permissions
3060 // expressed in `access_vector`.
3061 check_permission(&access_key_descriptor, &access_vector)
3062 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003063
Janis Danisevskis66784c42021-01-27 08:40:25 -08003064 let grant_id = if let Some(grant_id) = tx
3065 .query_row(
3066 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003067 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003068 params![key_id, grantee_uid],
3069 |row| row.get(0),
3070 )
3071 .optional()
3072 .context("In grant: Failed get optional existing grant id.")?
3073 {
3074 tx.execute(
3075 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003076 SET access_vector = ?
3077 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003078 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07003079 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08003080 .context("In grant: Failed to update existing grant.")?;
3081 grant_id
3082 } else {
3083 Self::insert_with_retry(|id| {
3084 tx.execute(
3085 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
3086 VALUES (?, ?, ?, ?);",
3087 params![id, grantee_uid, key_id, i32::from(access_vector)],
3088 )
3089 })
3090 .context("In grant")?
3091 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003092
Janis Danisevskis66784c42021-01-27 08:40:25 -08003093 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003094 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003095 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003096 }
3097
3098 /// This function checks permissions like `grant` and `load_key_entry`
3099 /// before removing a grant from the grant table.
3100 pub fn ungrant(
3101 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003102 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003103 caller_uid: u32,
3104 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08003105 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003106 ) -> Result<()> {
Janis Danisevskis850d4862021-05-05 08:41:14 -07003107 let _wp = wd::watch_millis("KeystoreDB::ungrant", 500);
3108
Janis Danisevskis66784c42021-01-27 08:40:25 -08003109 self.with_transaction(TransactionBehavior::Immediate, |tx| {
3110 // Load the key_id and complete the access control tuple.
3111 // We ignore the access vector here because grants cannot be granted.
3112 let (key_id, access_key_descriptor, _) =
3113 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
3114 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003115
Janis Danisevskis66784c42021-01-27 08:40:25 -08003116 // Perform access control. We must return here if the permission
3117 // was denied. So do not touch the '?' at the end of this line.
3118 check_permission(&access_key_descriptor)
3119 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003120
Janis Danisevskis66784c42021-01-27 08:40:25 -08003121 tx.execute(
3122 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003123 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08003124 params![key_id, grantee_uid],
3125 )
3126 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003127
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003128 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003129 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003130 }
3131
Joel Galenson845f74b2020-09-09 14:11:55 -07003132 // Generates a random id and passes it to the given function, which will
3133 // try to insert it into a database. If that insertion fails, retry;
3134 // otherwise return the id.
3135 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
3136 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08003137 let newid: i64 = match random() {
3138 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
3139 i => i,
3140 };
Joel Galenson845f74b2020-09-09 14:11:55 -07003141 match inserter(newid) {
3142 // If the id already existed, try again.
3143 Err(rusqlite::Error::SqliteFailure(
3144 libsqlite3_sys::Error {
3145 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
3146 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
3147 },
3148 _,
3149 )) => (),
3150 Err(e) => {
3151 return Err(e).context("In insert_with_retry: failed to insert into database.")
3152 }
3153 _ => return Ok(newid),
3154 }
3155 }
3156 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003157
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003158 /// Insert or replace the auth token based on (user_id, auth_id, auth_type)
3159 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) {
3160 self.perboot.insert_auth_token_entry(AuthTokenEntry::new(
3161 auth_token.clone(),
3162 MonotonicRawTime::now(),
3163 ))
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003164 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003165
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003166 /// Find the newest auth token matching the given predicate.
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003167 pub fn find_auth_token_entry<F>(&self, p: F) -> Option<(AuthTokenEntry, MonotonicRawTime)>
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003168 where
3169 F: Fn(&AuthTokenEntry) -> bool,
3170 {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003171 self.perboot.find_auth_token_entry(p).map(|entry| (entry, self.get_last_off_body()))
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003172 }
3173
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003174 /// Insert last_off_body into the metadata table at the initialization of auth token table
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003175 pub fn insert_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 /// Update last_off_body when on_device_off_body is called
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003180 pub fn update_last_off_body(&self, last_off_body: MonotonicRawTime) {
3181 self.perboot.set_last_off_body(last_off_body)
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003182 }
3183
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08003184 /// Get last_off_body time when finding auth tokens
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003185 fn get_last_off_body(&self) -> MonotonicRawTime {
3186 self.perboot.get_last_off_body()
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003187 }
Pavel Grafovf45034a2021-05-12 22:35:45 +01003188
3189 /// Load descriptor of a key by key id
3190 pub fn load_key_descriptor(&mut self, key_id: i64) -> Result<Option<KeyDescriptor>> {
3191 let _wp = wd::watch_millis("KeystoreDB::load_key_descriptor", 500);
3192
3193 self.with_transaction(TransactionBehavior::Deferred, |tx| {
3194 tx.query_row(
3195 "SELECT domain, namespace, alias FROM persistent.keyentry WHERE id = ?;",
3196 params![key_id],
3197 |row| {
3198 Ok(KeyDescriptor {
3199 domain: Domain(row.get(0)?),
3200 nspace: row.get(1)?,
3201 alias: row.get(2)?,
3202 blob: None,
3203 })
3204 },
3205 )
3206 .optional()
3207 .context("Trying to load key descriptor")
3208 .no_gc()
3209 })
3210 .context("In load_key_descriptor.")
3211 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003212}
3213
3214#[cfg(test)]
3215mod tests {
3216
3217 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07003218 use crate::key_parameter::{
3219 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
3220 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
3221 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003222 use crate::key_perm_set;
3223 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00003224 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08003225 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003226 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
3227 HardwareAuthToken::HardwareAuthToken,
3228 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08003229 };
3230 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003231 Timestamp::Timestamp,
3232 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003233 use rusqlite::NO_PARAMS;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003234 use rusqlite::TransactionBehavior;
Joel Galenson0891bc12020-07-20 10:37:03 -07003235 use std::cell::RefCell;
Seth Moore78c091f2021-04-09 21:38:30 +00003236 use std::collections::BTreeMap;
3237 use std::fmt::Write;
Janis Danisevskisaec14592020-11-12 09:41:49 -08003238 use std::sync::atomic::{AtomicU8, Ordering};
3239 use std::sync::Arc;
3240 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00003241 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08003242 #[cfg(disabled)]
3243 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07003244
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003245 fn new_test_db() -> Result<KeystoreDB> {
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003246 let conn = KeystoreDB::make_connection("file::memory:")?;
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003247
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003248 let mut db = KeystoreDB { conn, gc: None, perboot: Arc::new(perboot::PerbootDB::new()) };
Janis Danisevskis66784c42021-01-27 08:40:25 -08003249 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003250 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08003251 })?;
3252 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003253 }
3254
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003255 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
3256 where
3257 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
3258 {
Paul Crowleye8826e52021-03-31 08:33:53 -07003259 let super_key: Arc<SuperKeyManager> = Default::default();
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003260
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003261 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00003262 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003263
Janis Danisevskis3395f862021-05-06 10:54:17 -07003264 KeystoreDB::new(path, Some(Arc::new(gc)))
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003265 }
3266
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003267 fn rebind_alias(
3268 db: &mut KeystoreDB,
3269 newid: &KeyIdGuard,
3270 alias: &str,
3271 domain: Domain,
3272 namespace: i64,
3273 ) -> Result<bool> {
3274 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003275 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace, KeyType::Client).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003276 })
3277 .context("In rebind_alias.")
3278 }
3279
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003280 #[test]
3281 fn datetime() -> Result<()> {
3282 let conn = Connection::open_in_memory()?;
3283 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
3284 let now = SystemTime::now();
3285 let duration = Duration::from_secs(1000);
3286 let then = now.checked_sub(duration).unwrap();
3287 let soon = now.checked_add(duration).unwrap();
3288 conn.execute(
3289 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3290 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3291 )?;
3292 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3293 let mut rows = stmt.query(NO_PARAMS)?;
3294 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3295 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3296 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3297 assert!(rows.next()?.is_none());
3298 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3299 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3300 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3301 Ok(())
3302 }
3303
Joel Galenson0891bc12020-07-20 10:37:03 -07003304 // Ensure that we're using the "injected" random function, not the real one.
3305 #[test]
3306 fn test_mocked_random() {
3307 let rand1 = random();
3308 let rand2 = random();
3309 let rand3 = random();
3310 if rand1 == rand2 {
3311 assert_eq!(rand2 + 1, rand3);
3312 } else {
3313 assert_eq!(rand1 + 1, rand2);
3314 assert_eq!(rand2, rand3);
3315 }
3316 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003317
Joel Galenson26f4d012020-07-17 14:57:21 -07003318 // Test that we have the correct tables.
3319 #[test]
3320 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003321 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003322 let tables = db
3323 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003324 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003325 .query_map(params![], |row| row.get(0))?
3326 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003327 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003328 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003329 assert_eq!(tables[1], "blobmetadata");
3330 assert_eq!(tables[2], "grant");
3331 assert_eq!(tables[3], "keyentry");
3332 assert_eq!(tables[4], "keymetadata");
3333 assert_eq!(tables[5], "keyparameter");
Joel Galenson2aab4432020-07-22 15:27:57 -07003334 Ok(())
3335 }
3336
3337 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003338 fn test_auth_token_table_invariant() -> Result<()> {
3339 let mut db = new_test_db()?;
3340 let auth_token1 = HardwareAuthToken {
3341 challenge: i64::MAX,
3342 userId: 200,
3343 authenticatorId: 200,
3344 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3345 timestamp: Timestamp { milliSeconds: 500 },
3346 mac: String::from("mac").into_bytes(),
3347 };
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003348 db.insert_auth_token(&auth_token1);
3349 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003350 assert_eq!(auth_tokens_returned.len(), 1);
3351
3352 // insert another auth token with the same values for the columns in the UNIQUE constraint
3353 // of the auth token table and different value for timestamp
3354 let auth_token2 = HardwareAuthToken {
3355 challenge: i64::MAX,
3356 userId: 200,
3357 authenticatorId: 200,
3358 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3359 timestamp: Timestamp { milliSeconds: 600 },
3360 mac: String::from("mac").into_bytes(),
3361 };
3362
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003363 db.insert_auth_token(&auth_token2);
3364 let mut auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003365 assert_eq!(auth_tokens_returned.len(), 1);
3366
3367 if let Some(auth_token) = auth_tokens_returned.pop() {
3368 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3369 }
3370
3371 // insert another auth token with the different values for the columns in the UNIQUE
3372 // constraint of the auth token table
3373 let auth_token3 = HardwareAuthToken {
3374 challenge: i64::MAX,
3375 userId: 201,
3376 authenticatorId: 200,
3377 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3378 timestamp: Timestamp { milliSeconds: 600 },
3379 mac: String::from("mac").into_bytes(),
3380 };
3381
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003382 db.insert_auth_token(&auth_token3);
3383 let auth_tokens_returned = get_auth_tokens(&db);
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003384 assert_eq!(auth_tokens_returned.len(), 2);
3385
3386 Ok(())
3387 }
3388
3389 // utility function for test_auth_token_table_invariant()
Matthew Maurerd7815ca2021-05-06 21:58:45 -07003390 fn get_auth_tokens(db: &KeystoreDB) -> Vec<AuthTokenEntry> {
3391 db.perboot.get_all_auth_token_entries()
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003392 }
3393
3394 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003395 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003396 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003397 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003398
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003399 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003400 let entries = get_keyentry(&db)?;
3401 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003402
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003403 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003404
3405 let entries_new = get_keyentry(&db)?;
3406 assert_eq!(entries, entries_new);
3407 Ok(())
3408 }
3409
3410 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003411 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003412 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3413 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003414 }
3415
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003416 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003417
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003418 db.create_key_entry(&Domain::APP, &100, KeyType::Client, &KEYSTORE_UUID)?;
3419 db.create_key_entry(&Domain::SELINUX, &101, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003420
3421 let entries = get_keyentry(&db)?;
3422 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003423 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3424 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003425
3426 // Test that we must pass in a valid Domain.
3427 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003428 db.create_key_entry(&Domain::GRANT, &102, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003429 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003430 );
3431 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003432 db.create_key_entry(&Domain::BLOB, &103, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003433 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003434 );
3435 check_result_is_error_containing_string(
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003436 db.create_key_entry(&Domain::KEY_ID, &104, KeyType::Client, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003437 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003438 );
3439
3440 Ok(())
3441 }
3442
Joel Galenson33c04ad2020-08-03 11:04:38 -07003443 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003444 fn test_add_unsigned_key() -> Result<()> {
3445 let mut db = new_test_db()?;
3446 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3447 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3448 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3449 db.create_attestation_key_entry(
3450 &public_key,
3451 &raw_public_key,
3452 &private_key,
3453 &KEYSTORE_UUID,
3454 )?;
3455 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3456 assert_eq!(keys.len(), 1);
3457 assert_eq!(keys[0], public_key);
3458 Ok(())
3459 }
3460
3461 #[test]
3462 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3463 let mut db = new_test_db()?;
3464 let expiration_date: i64 = 20;
3465 let namespace: i64 = 30;
3466 let base_byte: u8 = 1;
3467 let loaded_values =
3468 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3469 let chain =
3470 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3471 assert_eq!(true, chain.is_some());
3472 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003473 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
Max Bires97f96812021-02-23 23:44:57 -08003474 assert_eq!(cert_chain.batch_cert, loaded_values.batch_cert);
3475 assert_eq!(cert_chain.cert_chain, loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003476 Ok(())
3477 }
3478
3479 #[test]
3480 fn test_get_attestation_pool_status() -> Result<()> {
3481 let mut db = new_test_db()?;
3482 let namespace: i64 = 30;
3483 load_attestation_key_pool(
3484 &mut db, 10, /* expiration */
3485 namespace, 0x01, /* base_byte */
3486 )?;
3487 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3488 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3489 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3490 assert_eq!(status.expiring, 0);
3491 assert_eq!(status.attested, 3);
3492 assert_eq!(status.unassigned, 0);
3493 assert_eq!(status.total, 3);
3494 assert_eq!(
3495 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3496 1
3497 );
3498 assert_eq!(
3499 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3500 2
3501 );
3502 assert_eq!(
3503 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3504 3
3505 );
3506 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3507 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3508 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3509 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003510 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003511 db.create_attestation_key_entry(
3512 &public_key,
3513 &raw_public_key,
3514 &private_key,
3515 &KEYSTORE_UUID,
3516 )?;
3517 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3518 assert_eq!(status.attested, 3);
3519 assert_eq!(status.unassigned, 0);
3520 assert_eq!(status.total, 4);
3521 db.store_signed_attestation_certificate_chain(
3522 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003523 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003524 &cert_chain,
3525 20,
3526 &KEYSTORE_UUID,
3527 )?;
3528 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3529 assert_eq!(status.attested, 4);
3530 assert_eq!(status.unassigned, 1);
3531 assert_eq!(status.total, 4);
3532 Ok(())
3533 }
3534
3535 #[test]
3536 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003537 let temp_dir =
3538 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3539 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003540 let expiration_date: i64 =
3541 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3542 let namespace: i64 = 30;
3543 let namespace_del1: i64 = 45;
3544 let namespace_del2: i64 = 60;
3545 let entry_values = load_attestation_key_pool(
3546 &mut db,
3547 expiration_date,
3548 namespace,
3549 0x01, /* base_byte */
3550 )?;
3551 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3552 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003553
3554 let blob_entry_row_count: u32 = db
3555 .conn
3556 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3557 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003558 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3559 // one key, one certificate chain, and one certificate.
3560 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003561
Max Bires2b2e6562020-09-22 11:22:36 -07003562 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3563
3564 let mut cert_chain =
3565 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003566 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003567 let value = cert_chain.unwrap();
Max Bires97f96812021-02-23 23:44:57 -08003568 assert_eq!(entry_values.batch_cert, value.batch_cert);
3569 assert_eq!(entry_values.cert_chain, value.cert_chain);
Max Biresb2e1d032021-02-08 21:35:05 -08003570 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003571
3572 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3573 Domain::APP,
3574 namespace_del1,
3575 &KEYSTORE_UUID,
3576 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003577 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003578 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3579 Domain::APP,
3580 namespace_del2,
3581 &KEYSTORE_UUID,
3582 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003583 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003584
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003585 // Give the garbage collector half a second to catch up.
3586 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003587
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003588 let blob_entry_row_count: u32 = db
3589 .conn
3590 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3591 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003592 // There shound be 3 blob entries left, because we deleted two of the attestation
3593 // key entries with three blobs each.
3594 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003595
Max Bires2b2e6562020-09-22 11:22:36 -07003596 Ok(())
3597 }
3598
3599 #[test]
Max Bires60d7ed12021-03-05 15:59:22 -08003600 fn test_delete_all_attestation_keys() -> Result<()> {
3601 let mut db = new_test_db()?;
3602 load_attestation_key_pool(&mut db, 45 /* expiration */, 1 /* namespace */, 0x02)?;
3603 load_attestation_key_pool(&mut db, 80 /* expiration */, 2 /* namespace */, 0x03)?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003604 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Max Bires60d7ed12021-03-05 15:59:22 -08003605 let result = db.delete_all_attestation_keys()?;
3606
3607 // Give the garbage collector half a second to catch up.
3608 std::thread::sleep(Duration::from_millis(500));
3609
3610 // Attestation keys should be deleted, and the regular key should remain.
3611 assert_eq!(result, 2);
3612
3613 Ok(())
3614 }
3615
3616 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003617 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003618 fn extractor(
3619 ke: &KeyEntryRow,
3620 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3621 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003622 }
3623
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003624 let mut db = new_test_db()?;
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003625 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
3626 db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003627 let entries = get_keyentry(&db)?;
3628 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003629 assert_eq!(
3630 extractor(&entries[0]),
3631 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3632 );
3633 assert_eq!(
3634 extractor(&entries[1]),
3635 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3636 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003637
3638 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003639 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003640 let entries = get_keyentry(&db)?;
3641 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003642 assert_eq!(
3643 extractor(&entries[0]),
3644 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3645 );
3646 assert_eq!(
3647 extractor(&entries[1]),
3648 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3649 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003650
3651 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003652 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003653 let entries = get_keyentry(&db)?;
3654 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003655 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3656 assert_eq!(
3657 extractor(&entries[1]),
3658 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3659 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003660
3661 // Test that we must pass in a valid Domain.
3662 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003663 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003664 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003665 );
3666 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003667 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003668 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003669 );
3670 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003671 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003672 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003673 );
3674
3675 // Test that we correctly handle setting an alias for something that does not exist.
3676 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003677 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003678 "Expected to update a single entry but instead updated 0",
3679 );
3680 // Test that we correctly abort the transaction in this case.
3681 let entries = get_keyentry(&db)?;
3682 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003683 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3684 assert_eq!(
3685 extractor(&entries[1]),
3686 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3687 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003688
3689 Ok(())
3690 }
3691
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003692 #[test]
3693 fn test_grant_ungrant() -> Result<()> {
3694 const CALLER_UID: u32 = 15;
3695 const GRANTEE_UID: u32 = 12;
3696 const SELINUX_NAMESPACE: i64 = 7;
3697
3698 let mut db = new_test_db()?;
3699 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003700 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3701 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3702 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003703 )?;
3704 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003705 domain: super::Domain::APP,
3706 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003707 alias: Some("key".to_string()),
3708 blob: None,
3709 };
3710 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3711 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3712
3713 // Reset totally predictable random number generator in case we
3714 // are not the first test running on this thread.
3715 reset_random();
3716 let next_random = 0i64;
3717
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003718 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003719 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003720 assert_eq!(*a, PVEC1);
3721 assert_eq!(
3722 *k,
3723 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003724 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003725 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003726 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003727 alias: Some("key".to_string()),
3728 blob: None,
3729 }
3730 );
3731 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003732 })
3733 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003734
3735 assert_eq!(
3736 app_granted_key,
3737 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003738 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003739 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003740 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003741 alias: None,
3742 blob: None,
3743 }
3744 );
3745
3746 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003747 domain: super::Domain::SELINUX,
3748 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003749 alias: Some("yek".to_string()),
3750 blob: None,
3751 };
3752
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003753 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003754 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003755 assert_eq!(*a, PVEC1);
3756 assert_eq!(
3757 *k,
3758 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003759 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003760 // namespace must be the supplied SELinux
3761 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003762 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003763 alias: Some("yek".to_string()),
3764 blob: None,
3765 }
3766 );
3767 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003768 })
3769 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003770
3771 assert_eq!(
3772 selinux_granted_key,
3773 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003774 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003776 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003777 alias: None,
3778 blob: None,
3779 }
3780 );
3781
3782 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003783 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003784 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003785 assert_eq!(*a, PVEC2);
3786 assert_eq!(
3787 *k,
3788 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003789 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003790 // namespace must be the supplied SELinux
3791 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003792 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003793 alias: Some("yek".to_string()),
3794 blob: None,
3795 }
3796 );
3797 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003798 })
3799 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003800
3801 assert_eq!(
3802 selinux_granted_key,
3803 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003804 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003805 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003806 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003807 alias: None,
3808 blob: None,
3809 }
3810 );
3811
3812 {
3813 // Limiting scope of stmt, because it borrows db.
3814 let mut stmt = db
3815 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003816 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003817 let mut rows =
3818 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3819 Ok((
3820 row.get(0)?,
3821 row.get(1)?,
3822 row.get(2)?,
3823 KeyPermSet::from(row.get::<_, i32>(3)?),
3824 ))
3825 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003826
3827 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003828 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003829 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003830 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003831 assert!(rows.next().is_none());
3832 }
3833
3834 debug_dump_keyentry_table(&mut db)?;
3835 println!("app_key {:?}", app_key);
3836 println!("selinux_key {:?}", selinux_key);
3837
Janis Danisevskis66784c42021-01-27 08:40:25 -08003838 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3839 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003840
3841 Ok(())
3842 }
3843
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003844 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003845 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3846 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3847
3848 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003849 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003850 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003851 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003852 let mut blob_metadata = BlobMetaData::new();
3853 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3854 db.set_blob(
3855 &key_id,
3856 SubComponentType::KEY_BLOB,
3857 Some(TEST_KEY_BLOB),
3858 Some(&blob_metadata),
3859 )?;
3860 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3861 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003862 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003863
3864 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003865 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003866 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003867 )?;
3868 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003869 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3870 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003871 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003872 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003873 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003874 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003875 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003876 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003877 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003878
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003879 drop(rows);
3880 drop(stmt);
3881
3882 assert_eq!(
3883 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3884 BlobMetaData::load_from_db(id, tx).no_gc()
3885 })
3886 .expect("Should find blob metadata."),
3887 blob_metadata
3888 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003889 Ok(())
3890 }
3891
3892 static TEST_ALIAS: &str = "my super duper key";
3893
3894 #[test]
3895 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3896 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003897 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003898 .context("test_insert_and_load_full_keyentry_domain_app")?
3899 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003900 let (_key_guard, key_entry) = db
3901 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003902 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003903 domain: Domain::APP,
3904 nspace: 0,
3905 alias: Some(TEST_ALIAS.to_string()),
3906 blob: None,
3907 },
3908 KeyType::Client,
3909 KeyEntryLoadBits::BOTH,
3910 1,
3911 |_k, _av| Ok(()),
3912 )
3913 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003914 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003915
3916 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003917 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003918 domain: Domain::APP,
3919 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003920 alias: Some(TEST_ALIAS.to_string()),
3921 blob: None,
3922 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003923 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003924 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003925 |_, _| Ok(()),
3926 )
3927 .unwrap();
3928
3929 assert_eq!(
3930 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3931 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003932 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003933 domain: Domain::APP,
3934 nspace: 0,
3935 alias: Some(TEST_ALIAS.to_string()),
3936 blob: None,
3937 },
3938 KeyType::Client,
3939 KeyEntryLoadBits::NONE,
3940 1,
3941 |_k, _av| Ok(()),
3942 )
3943 .unwrap_err()
3944 .root_cause()
3945 .downcast_ref::<KsError>()
3946 );
3947
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003948 Ok(())
3949 }
3950
3951 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003952 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3953 let mut db = new_test_db()?;
3954
3955 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003956 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003957 domain: Domain::APP,
3958 nspace: 1,
3959 alias: Some(TEST_ALIAS.to_string()),
3960 blob: None,
3961 },
Janis Danisevskis0cabd712021-05-25 11:07:10 -07003962 KeyType::Client,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003963 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003964 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003965 )
3966 .expect("Trying to insert cert.");
3967
3968 let (_key_guard, mut key_entry) = db
3969 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003970 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003971 domain: Domain::APP,
3972 nspace: 1,
3973 alias: Some(TEST_ALIAS.to_string()),
3974 blob: None,
3975 },
3976 KeyType::Client,
3977 KeyEntryLoadBits::PUBLIC,
3978 1,
3979 |_k, _av| Ok(()),
3980 )
3981 .expect("Trying to read certificate entry.");
3982
3983 assert!(key_entry.pure_cert());
3984 assert!(key_entry.cert().is_none());
3985 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3986
3987 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003988 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003989 domain: Domain::APP,
3990 nspace: 1,
3991 alias: Some(TEST_ALIAS.to_string()),
3992 blob: None,
3993 },
3994 KeyType::Client,
3995 1,
3996 |_, _| Ok(()),
3997 )
3998 .unwrap();
3999
4000 assert_eq!(
4001 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4002 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004003 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08004004 domain: Domain::APP,
4005 nspace: 1,
4006 alias: Some(TEST_ALIAS.to_string()),
4007 blob: None,
4008 },
4009 KeyType::Client,
4010 KeyEntryLoadBits::NONE,
4011 1,
4012 |_k, _av| Ok(()),
4013 )
4014 .unwrap_err()
4015 .root_cause()
4016 .downcast_ref::<KsError>()
4017 );
4018
4019 Ok(())
4020 }
4021
4022 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004023 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
4024 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004025 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004026 .context("test_insert_and_load_full_keyentry_domain_selinux")?
4027 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004028 let (_key_guard, key_entry) = db
4029 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004030 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004031 domain: Domain::SELINUX,
4032 nspace: 1,
4033 alias: Some(TEST_ALIAS.to_string()),
4034 blob: None,
4035 },
4036 KeyType::Client,
4037 KeyEntryLoadBits::BOTH,
4038 1,
4039 |_k, _av| Ok(()),
4040 )
4041 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004042 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004043
4044 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004045 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004046 domain: Domain::SELINUX,
4047 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004048 alias: Some(TEST_ALIAS.to_string()),
4049 blob: None,
4050 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004051 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004052 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004053 |_, _| Ok(()),
4054 )
4055 .unwrap();
4056
4057 assert_eq!(
4058 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4059 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004060 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004061 domain: Domain::SELINUX,
4062 nspace: 1,
4063 alias: Some(TEST_ALIAS.to_string()),
4064 blob: None,
4065 },
4066 KeyType::Client,
4067 KeyEntryLoadBits::NONE,
4068 1,
4069 |_k, _av| Ok(()),
4070 )
4071 .unwrap_err()
4072 .root_cause()
4073 .downcast_ref::<KsError>()
4074 );
4075
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004076 Ok(())
4077 }
4078
4079 #[test]
4080 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
4081 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004082 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004083 .context("test_insert_and_load_full_keyentry_domain_key_id")?
4084 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004085 let (_, key_entry) = db
4086 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004087 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004088 KeyType::Client,
4089 KeyEntryLoadBits::BOTH,
4090 1,
4091 |_k, _av| Ok(()),
4092 )
4093 .unwrap();
4094
Qi Wub9433b52020-12-01 14:52:46 +08004095 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004096
4097 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004098 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004099 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004100 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004101 |_, _| Ok(()),
4102 )
4103 .unwrap();
4104
4105 assert_eq!(
4106 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4107 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004108 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004109 KeyType::Client,
4110 KeyEntryLoadBits::NONE,
4111 1,
4112 |_k, _av| Ok(()),
4113 )
4114 .unwrap_err()
4115 .root_cause()
4116 .downcast_ref::<KsError>()
4117 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004118
4119 Ok(())
4120 }
4121
4122 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08004123 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
4124 let mut db = new_test_db()?;
4125 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
4126 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
4127 .0;
4128 // Update the usage count of the limited use key.
4129 db.check_and_update_key_usage_count(key_id)?;
4130
4131 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004132 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08004133 KeyType::Client,
4134 KeyEntryLoadBits::BOTH,
4135 1,
4136 |_k, _av| Ok(()),
4137 )?;
4138
4139 // The usage count is decremented now.
4140 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
4141
4142 Ok(())
4143 }
4144
4145 #[test]
4146 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
4147 let mut db = new_test_db()?;
4148 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
4149 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
4150 .0;
4151 // Update the usage count of the limited use key.
4152 db.check_and_update_key_usage_count(key_id).expect(concat!(
4153 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4154 "This should succeed."
4155 ));
4156
4157 // Try to update the exhausted limited use key.
4158 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
4159 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
4160 "This should fail."
4161 ));
4162 assert_eq!(
4163 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
4164 e.root_cause().downcast_ref::<KsError>().unwrap()
4165 );
4166
4167 Ok(())
4168 }
4169
4170 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004171 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
4172 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08004173 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004174 .context("test_insert_and_load_full_keyentry_from_grant")?
4175 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004176
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004177 let granted_key = db
4178 .grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004179 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004180 domain: Domain::APP,
4181 nspace: 0,
4182 alias: Some(TEST_ALIAS.to_string()),
4183 blob: None,
4184 },
4185 1,
4186 2,
4187 key_perm_set![KeyPerm::use_()],
4188 |_k, _av| Ok(()),
4189 )
4190 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004191
4192 debug_dump_grant_table(&mut db)?;
4193
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004194 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08004195 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
4196 assert_eq!(Domain::GRANT, k.domain);
4197 assert!(av.unwrap().includes(KeyPerm::use_()));
4198 Ok(())
4199 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004200 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004201
Qi Wub9433b52020-12-01 14:52:46 +08004202 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004203
Janis Danisevskis66784c42021-01-27 08:40:25 -08004204 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004205
4206 assert_eq!(
4207 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4208 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004209 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004210 KeyType::Client,
4211 KeyEntryLoadBits::NONE,
4212 2,
4213 |_k, _av| Ok(()),
4214 )
4215 .unwrap_err()
4216 .root_cause()
4217 .downcast_ref::<KsError>()
4218 );
4219
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004220 Ok(())
4221 }
4222
Janis Danisevskis45760022021-01-19 16:34:10 -08004223 // This test attempts to load a key by key id while the caller is not the owner
4224 // but a grant exists for the given key and the caller.
4225 #[test]
4226 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
4227 let mut db = new_test_db()?;
4228 const OWNER_UID: u32 = 1u32;
4229 const GRANTEE_UID: u32 = 2u32;
4230 const SOMEONE_ELSE_UID: u32 = 3u32;
4231 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
4232 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
4233 .0;
4234
4235 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004236 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08004237 domain: Domain::APP,
4238 nspace: 0,
4239 alias: Some(TEST_ALIAS.to_string()),
4240 blob: None,
4241 },
4242 OWNER_UID,
4243 GRANTEE_UID,
4244 key_perm_set![KeyPerm::use_()],
4245 |_k, _av| Ok(()),
4246 )
4247 .unwrap();
4248
4249 debug_dump_grant_table(&mut db)?;
4250
4251 let id_descriptor =
4252 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
4253
4254 let (_, key_entry) = db
4255 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004256 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004257 KeyType::Client,
4258 KeyEntryLoadBits::BOTH,
4259 GRANTEE_UID,
4260 |k, av| {
4261 assert_eq!(Domain::APP, k.domain);
4262 assert_eq!(OWNER_UID as i64, k.nspace);
4263 assert!(av.unwrap().includes(KeyPerm::use_()));
4264 Ok(())
4265 },
4266 )
4267 .unwrap();
4268
4269 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4270
4271 let (_, key_entry) = db
4272 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004273 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004274 KeyType::Client,
4275 KeyEntryLoadBits::BOTH,
4276 SOMEONE_ELSE_UID,
4277 |k, av| {
4278 assert_eq!(Domain::APP, k.domain);
4279 assert_eq!(OWNER_UID as i64, k.nspace);
4280 assert!(av.is_none());
4281 Ok(())
4282 },
4283 )
4284 .unwrap();
4285
4286 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4287
Janis Danisevskis66784c42021-01-27 08:40:25 -08004288 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004289
4290 assert_eq!(
4291 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4292 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004293 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004294 KeyType::Client,
4295 KeyEntryLoadBits::NONE,
4296 GRANTEE_UID,
4297 |_k, _av| Ok(()),
4298 )
4299 .unwrap_err()
4300 .root_cause()
4301 .downcast_ref::<KsError>()
4302 );
4303
4304 Ok(())
4305 }
4306
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004307 // Creates a key migrates it to a different location and then tries to access it by the old
4308 // and new location.
4309 #[test]
4310 fn test_migrate_key_app_to_app() -> Result<()> {
4311 let mut db = new_test_db()?;
4312 const SOURCE_UID: u32 = 1u32;
4313 const DESTINATION_UID: u32 = 2u32;
4314 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4315 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4316 let key_id_guard =
4317 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4318 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4319
4320 let source_descriptor: KeyDescriptor = KeyDescriptor {
4321 domain: Domain::APP,
4322 nspace: -1,
4323 alias: Some(SOURCE_ALIAS.to_string()),
4324 blob: None,
4325 };
4326
4327 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4328 domain: Domain::APP,
4329 nspace: -1,
4330 alias: Some(DESTINATION_ALIAS.to_string()),
4331 blob: None,
4332 };
4333
4334 let key_id = key_id_guard.id();
4335
4336 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4337 Ok(())
4338 })
4339 .unwrap();
4340
4341 let (_, key_entry) = db
4342 .load_key_entry(
4343 &destination_descriptor,
4344 KeyType::Client,
4345 KeyEntryLoadBits::BOTH,
4346 DESTINATION_UID,
4347 |k, av| {
4348 assert_eq!(Domain::APP, k.domain);
4349 assert_eq!(DESTINATION_UID as i64, k.nspace);
4350 assert!(av.is_none());
4351 Ok(())
4352 },
4353 )
4354 .unwrap();
4355
4356 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4357
4358 assert_eq!(
4359 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4360 db.load_key_entry(
4361 &source_descriptor,
4362 KeyType::Client,
4363 KeyEntryLoadBits::NONE,
4364 SOURCE_UID,
4365 |_k, _av| Ok(()),
4366 )
4367 .unwrap_err()
4368 .root_cause()
4369 .downcast_ref::<KsError>()
4370 );
4371
4372 Ok(())
4373 }
4374
4375 // Creates a key migrates it to a different location and then tries to access it by the old
4376 // and new location.
4377 #[test]
4378 fn test_migrate_key_app_to_selinux() -> Result<()> {
4379 let mut db = new_test_db()?;
4380 const SOURCE_UID: u32 = 1u32;
4381 const DESTINATION_UID: u32 = 2u32;
4382 const DESTINATION_NAMESPACE: i64 = 1000i64;
4383 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4384 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4385 let key_id_guard =
4386 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4387 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4388
4389 let source_descriptor: KeyDescriptor = KeyDescriptor {
4390 domain: Domain::APP,
4391 nspace: -1,
4392 alias: Some(SOURCE_ALIAS.to_string()),
4393 blob: None,
4394 };
4395
4396 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4397 domain: Domain::SELINUX,
4398 nspace: DESTINATION_NAMESPACE,
4399 alias: Some(DESTINATION_ALIAS.to_string()),
4400 blob: None,
4401 };
4402
4403 let key_id = key_id_guard.id();
4404
4405 db.migrate_key_namespace(key_id_guard, &destination_descriptor, DESTINATION_UID, |_k| {
4406 Ok(())
4407 })
4408 .unwrap();
4409
4410 let (_, key_entry) = db
4411 .load_key_entry(
4412 &destination_descriptor,
4413 KeyType::Client,
4414 KeyEntryLoadBits::BOTH,
4415 DESTINATION_UID,
4416 |k, av| {
4417 assert_eq!(Domain::SELINUX, k.domain);
4418 assert_eq!(DESTINATION_NAMESPACE as i64, k.nspace);
4419 assert!(av.is_none());
4420 Ok(())
4421 },
4422 )
4423 .unwrap();
4424
4425 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4426
4427 assert_eq!(
4428 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4429 db.load_key_entry(
4430 &source_descriptor,
4431 KeyType::Client,
4432 KeyEntryLoadBits::NONE,
4433 SOURCE_UID,
4434 |_k, _av| Ok(()),
4435 )
4436 .unwrap_err()
4437 .root_cause()
4438 .downcast_ref::<KsError>()
4439 );
4440
4441 Ok(())
4442 }
4443
4444 // Creates two keys and tries to migrate the first to the location of the second which
4445 // is expected to fail.
4446 #[test]
4447 fn test_migrate_key_destination_occupied() -> Result<()> {
4448 let mut db = new_test_db()?;
4449 const SOURCE_UID: u32 = 1u32;
4450 const DESTINATION_UID: u32 = 2u32;
4451 static SOURCE_ALIAS: &str = &"SOURCE_ALIAS";
4452 static DESTINATION_ALIAS: &str = &"DESTINATION_ALIAS";
4453 let key_id_guard =
4454 make_test_key_entry(&mut db, Domain::APP, SOURCE_UID as i64, SOURCE_ALIAS, None)
4455 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4456 make_test_key_entry(&mut db, Domain::APP, DESTINATION_UID as i64, DESTINATION_ALIAS, None)
4457 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?;
4458
4459 let destination_descriptor: KeyDescriptor = KeyDescriptor {
4460 domain: Domain::APP,
4461 nspace: -1,
4462 alias: Some(DESTINATION_ALIAS.to_string()),
4463 blob: None,
4464 };
4465
4466 assert_eq!(
4467 Some(&KsError::Rc(ResponseCode::INVALID_ARGUMENT)),
4468 db.migrate_key_namespace(
4469 key_id_guard,
4470 &destination_descriptor,
4471 DESTINATION_UID,
4472 |_k| Ok(())
4473 )
4474 .unwrap_err()
4475 .root_cause()
4476 .downcast_ref::<KsError>()
4477 );
4478
4479 Ok(())
4480 }
4481
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07004482 #[test]
4483 fn test_upgrade_0_to_1() {
4484 const ALIAS1: &str = &"test_upgrade_0_to_1_1";
4485 const ALIAS2: &str = &"test_upgrade_0_to_1_2";
4486 const ALIAS3: &str = &"test_upgrade_0_to_1_3";
4487 const UID: u32 = 33;
4488 let temp_dir = Arc::new(TempDir::new("test_upgrade_0_to_1").unwrap());
4489 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
4490 let key_id_untouched1 =
4491 make_test_key_entry(&mut db, Domain::APP, UID as i64, ALIAS1, None).unwrap().id();
4492 let key_id_untouched2 =
4493 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS2, false).unwrap().id();
4494 let key_id_deleted =
4495 make_bootlevel_key_entry(&mut db, Domain::APP, UID as i64, ALIAS3, true).unwrap().id();
4496
4497 let (_, key_entry) = db
4498 .load_key_entry(
4499 &KeyDescriptor {
4500 domain: Domain::APP,
4501 nspace: -1,
4502 alias: Some(ALIAS1.to_string()),
4503 blob: None,
4504 },
4505 KeyType::Client,
4506 KeyEntryLoadBits::BOTH,
4507 UID,
4508 |k, av| {
4509 assert_eq!(Domain::APP, k.domain);
4510 assert_eq!(UID as i64, k.nspace);
4511 assert!(av.is_none());
4512 Ok(())
4513 },
4514 )
4515 .unwrap();
4516 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4517 let (_, key_entry) = db
4518 .load_key_entry(
4519 &KeyDescriptor {
4520 domain: Domain::APP,
4521 nspace: -1,
4522 alias: Some(ALIAS2.to_string()),
4523 blob: None,
4524 },
4525 KeyType::Client,
4526 KeyEntryLoadBits::BOTH,
4527 UID,
4528 |k, av| {
4529 assert_eq!(Domain::APP, k.domain);
4530 assert_eq!(UID as i64, k.nspace);
4531 assert!(av.is_none());
4532 Ok(())
4533 },
4534 )
4535 .unwrap();
4536 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4537 let (_, key_entry) = db
4538 .load_key_entry(
4539 &KeyDescriptor {
4540 domain: Domain::APP,
4541 nspace: -1,
4542 alias: Some(ALIAS3.to_string()),
4543 blob: None,
4544 },
4545 KeyType::Client,
4546 KeyEntryLoadBits::BOTH,
4547 UID,
4548 |k, av| {
4549 assert_eq!(Domain::APP, k.domain);
4550 assert_eq!(UID as i64, k.nspace);
4551 assert!(av.is_none());
4552 Ok(())
4553 },
4554 )
4555 .unwrap();
4556 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_deleted, true));
4557
4558 db.with_transaction(TransactionBehavior::Immediate, |tx| {
4559 KeystoreDB::from_0_to_1(tx).no_gc()
4560 })
4561 .unwrap();
4562
4563 let (_, key_entry) = db
4564 .load_key_entry(
4565 &KeyDescriptor {
4566 domain: Domain::APP,
4567 nspace: -1,
4568 alias: Some(ALIAS1.to_string()),
4569 blob: None,
4570 },
4571 KeyType::Client,
4572 KeyEntryLoadBits::BOTH,
4573 UID,
4574 |k, av| {
4575 assert_eq!(Domain::APP, k.domain);
4576 assert_eq!(UID as i64, k.nspace);
4577 assert!(av.is_none());
4578 Ok(())
4579 },
4580 )
4581 .unwrap();
4582 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id_untouched1, None));
4583 let (_, key_entry) = db
4584 .load_key_entry(
4585 &KeyDescriptor {
4586 domain: Domain::APP,
4587 nspace: -1,
4588 alias: Some(ALIAS2.to_string()),
4589 blob: None,
4590 },
4591 KeyType::Client,
4592 KeyEntryLoadBits::BOTH,
4593 UID,
4594 |k, av| {
4595 assert_eq!(Domain::APP, k.domain);
4596 assert_eq!(UID as i64, k.nspace);
4597 assert!(av.is_none());
4598 Ok(())
4599 },
4600 )
4601 .unwrap();
4602 assert_eq!(key_entry, make_bootlevel_test_key_entry_test_vector(key_id_untouched2, false));
4603 assert_eq!(
4604 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4605 db.load_key_entry(
4606 &KeyDescriptor {
4607 domain: Domain::APP,
4608 nspace: -1,
4609 alias: Some(ALIAS3.to_string()),
4610 blob: None,
4611 },
4612 KeyType::Client,
4613 KeyEntryLoadBits::BOTH,
4614 UID,
4615 |k, av| {
4616 assert_eq!(Domain::APP, k.domain);
4617 assert_eq!(UID as i64, k.nspace);
4618 assert!(av.is_none());
4619 Ok(())
4620 },
4621 )
4622 .unwrap_err()
4623 .root_cause()
4624 .downcast_ref::<KsError>()
4625 );
4626 }
4627
Janis Danisevskisaec14592020-11-12 09:41:49 -08004628 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4629
Janis Danisevskisaec14592020-11-12 09:41:49 -08004630 #[test]
4631 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4632 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004633 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4634 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004635 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004636 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004637 .context("test_insert_and_load_full_keyentry_domain_app")?
4638 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004639 let (_key_guard, key_entry) = db
4640 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004641 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004642 domain: Domain::APP,
4643 nspace: 0,
4644 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4645 blob: None,
4646 },
4647 KeyType::Client,
4648 KeyEntryLoadBits::BOTH,
4649 33,
4650 |_k, _av| Ok(()),
4651 )
4652 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004653 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004654 let state = Arc::new(AtomicU8::new(1));
4655 let state2 = state.clone();
4656
4657 // Spawning a second thread that attempts to acquire the key id lock
4658 // for the same key as the primary thread. The primary thread then
4659 // waits, thereby forcing the secondary thread into the second stage
4660 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4661 // The test succeeds if the secondary thread observes the transition
4662 // of `state` from 1 to 2, despite having a whole second to overtake
4663 // the primary thread.
4664 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004665 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004666 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004667 assert!(db
4668 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004669 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004670 domain: Domain::APP,
4671 nspace: 0,
4672 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4673 blob: None,
4674 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004675 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004676 KeyEntryLoadBits::BOTH,
4677 33,
4678 |_k, _av| Ok(()),
4679 )
4680 .is_ok());
4681 // We should only see a 2 here because we can only return
4682 // from load_key_entry when the `_key_guard` expires,
4683 // which happens at the end of the scope.
4684 assert_eq!(2, state2.load(Ordering::Relaxed));
4685 });
4686
4687 thread::sleep(std::time::Duration::from_millis(1000));
4688
4689 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4690
4691 // Return the handle from this scope so we can join with the
4692 // secondary thread after the key id lock has expired.
4693 handle
4694 // This is where the `_key_guard` goes out of scope,
4695 // which is the reason for concurrent load_key_entry on the same key
4696 // to unblock.
4697 };
4698 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4699 // main test thread. We will not see failing asserts in secondary threads otherwise.
4700 handle.join().unwrap();
4701 Ok(())
4702 }
4703
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004704 #[test]
Janis Danisevskiscdcf4e52021-04-14 15:44:36 -07004705 fn test_database_busy_error_code() {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004706 let temp_dir =
4707 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4708
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004709 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4710 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004711
4712 let _tx1 = db1
4713 .conn
4714 .transaction_with_behavior(TransactionBehavior::Immediate)
4715 .expect("Failed to create first transaction.");
4716
4717 let error = db2
4718 .conn
4719 .transaction_with_behavior(TransactionBehavior::Immediate)
4720 .context("Transaction begin failed.")
4721 .expect_err("This should fail.");
4722 let root_cause = error.root_cause();
4723 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4724 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4725 {
4726 return;
4727 }
4728 panic!(
4729 "Unexpected error {:?} \n{:?} \n{:?}",
4730 error,
4731 root_cause,
4732 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4733 )
4734 }
4735
4736 #[cfg(disabled)]
4737 #[test]
4738 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4739 let temp_dir = Arc::new(
4740 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4741 .expect("Failed to create temp dir."),
4742 );
4743
4744 let test_begin = Instant::now();
4745
Janis Danisevskis66784c42021-01-27 08:40:25 -08004746 const KEY_COUNT: u32 = 500u32;
Seth Moore444b51a2021-06-11 09:49:49 -07004747 let mut db =
4748 new_test_db_with_gc(temp_dir.path(), |_, _| Ok(())).expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004749 const OPEN_DB_COUNT: u32 = 50u32;
4750
4751 let mut actual_key_count = KEY_COUNT;
4752 // First insert KEY_COUNT keys.
4753 for count in 0..KEY_COUNT {
4754 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4755 actual_key_count = count;
4756 break;
4757 }
4758 let alias = format!("test_alias_{}", count);
4759 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4760 .expect("Failed to make key entry.");
4761 }
4762
4763 // Insert more keys from a different thread and into a different namespace.
4764 let temp_dir1 = temp_dir.clone();
4765 let handle1 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004766 let mut db = new_test_db_with_gc(temp_dir1.path(), |_, _| Ok(()))
4767 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004768
4769 for count in 0..actual_key_count {
4770 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4771 return;
4772 }
4773 let alias = format!("test_alias_{}", count);
4774 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4775 .expect("Failed to make key entry.");
4776 }
4777
4778 // then unbind them again.
4779 for count in 0..actual_key_count {
4780 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4781 return;
4782 }
4783 let key = KeyDescriptor {
4784 domain: Domain::APP,
4785 nspace: -1,
4786 alias: Some(format!("test_alias_{}", count)),
4787 blob: None,
4788 };
4789 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4790 }
4791 });
4792
4793 // And start unbinding the first set of keys.
4794 let temp_dir2 = temp_dir.clone();
4795 let handle2 = thread::spawn(move || {
Seth Moore444b51a2021-06-11 09:49:49 -07004796 let mut db = new_test_db_with_gc(temp_dir2.path(), |_, _| Ok(()))
4797 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004798
4799 for count in 0..actual_key_count {
4800 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4801 return;
4802 }
4803 let key = KeyDescriptor {
4804 domain: Domain::APP,
4805 nspace: -1,
4806 alias: Some(format!("test_alias_{}", count)),
4807 blob: None,
4808 };
4809 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4810 }
4811 });
4812
Janis Danisevskis66784c42021-01-27 08:40:25 -08004813 // While a lot of inserting and deleting is going on we have to open database connections
4814 // successfully and use them.
4815 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4816 // out of scope.
4817 #[allow(clippy::redundant_clone)]
4818 let temp_dir4 = temp_dir.clone();
4819 let handle4 = thread::spawn(move || {
4820 for count in 0..OPEN_DB_COUNT {
4821 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4822 return;
4823 }
Seth Moore444b51a2021-06-11 09:49:49 -07004824 let mut db = new_test_db_with_gc(temp_dir4.path(), |_, _| Ok(()))
4825 .expect("Failed to open database.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004826
4827 let alias = format!("test_alias_{}", count);
4828 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4829 .expect("Failed to make key entry.");
4830 let key = KeyDescriptor {
4831 domain: Domain::APP,
4832 nspace: -1,
4833 alias: Some(alias),
4834 blob: None,
4835 };
4836 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4837 }
4838 });
4839
4840 handle1.join().expect("Thread 1 panicked.");
4841 handle2.join().expect("Thread 2 panicked.");
4842 handle4.join().expect("Thread 4 panicked.");
4843
Janis Danisevskis66784c42021-01-27 08:40:25 -08004844 Ok(())
4845 }
4846
4847 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004848 fn list() -> Result<()> {
4849 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004850 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004851 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4852 (Domain::APP, 1, "test1"),
4853 (Domain::APP, 1, "test2"),
4854 (Domain::APP, 1, "test3"),
4855 (Domain::APP, 1, "test4"),
4856 (Domain::APP, 1, "test5"),
4857 (Domain::APP, 1, "test6"),
4858 (Domain::APP, 1, "test7"),
4859 (Domain::APP, 2, "test1"),
4860 (Domain::APP, 2, "test2"),
4861 (Domain::APP, 2, "test3"),
4862 (Domain::APP, 2, "test4"),
4863 (Domain::APP, 2, "test5"),
4864 (Domain::APP, 2, "test6"),
4865 (Domain::APP, 2, "test8"),
4866 (Domain::SELINUX, 100, "test1"),
4867 (Domain::SELINUX, 100, "test2"),
4868 (Domain::SELINUX, 100, "test3"),
4869 (Domain::SELINUX, 100, "test4"),
4870 (Domain::SELINUX, 100, "test5"),
4871 (Domain::SELINUX, 100, "test6"),
4872 (Domain::SELINUX, 100, "test9"),
4873 ];
4874
4875 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4876 .iter()
4877 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004878 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4879 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004880 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4881 });
4882 (entry.id(), *ns)
4883 })
4884 .collect();
4885
4886 for (domain, namespace) in
4887 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4888 {
4889 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4890 .iter()
4891 .filter_map(|(domain, ns, alias)| match ns {
4892 ns if *ns == *namespace => Some(KeyDescriptor {
4893 domain: *domain,
4894 nspace: *ns,
4895 alias: Some(alias.to_string()),
4896 blob: None,
4897 }),
4898 _ => None,
4899 })
4900 .collect();
4901 list_o_descriptors.sort();
Janis Danisevskis18313832021-05-17 13:30:32 -07004902 let mut list_result = db.list(*domain, *namespace, KeyType::Client)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004903 list_result.sort();
4904 assert_eq!(list_o_descriptors, list_result);
4905
4906 let mut list_o_ids: Vec<i64> = list_o_descriptors
4907 .into_iter()
4908 .map(|d| {
4909 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004910 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004911 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004912 KeyType::Client,
4913 KeyEntryLoadBits::NONE,
4914 *namespace as u32,
4915 |_, _| Ok(()),
4916 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004917 .unwrap();
4918 entry.id()
4919 })
4920 .collect();
4921 list_o_ids.sort_unstable();
4922 let mut loaded_entries: Vec<i64> = list_o_keys
4923 .iter()
4924 .filter_map(|(id, ns)| match ns {
4925 ns if *ns == *namespace => Some(*id),
4926 _ => None,
4927 })
4928 .collect();
4929 loaded_entries.sort_unstable();
4930 assert_eq!(list_o_ids, loaded_entries);
4931 }
Janis Danisevskis18313832021-05-17 13:30:32 -07004932 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101, KeyType::Client)?);
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004933
4934 Ok(())
4935 }
4936
Joel Galenson0891bc12020-07-20 10:37:03 -07004937 // Helpers
4938
4939 // Checks that the given result is an error containing the given string.
4940 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4941 let error_str = format!(
4942 "{:#?}",
4943 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4944 );
4945 assert!(
4946 error_str.contains(target),
4947 "The string \"{}\" should contain \"{}\"",
4948 error_str,
4949 target
4950 );
4951 }
4952
Joel Galenson2aab4432020-07-22 15:27:57 -07004953 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004954 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004955 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004956 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004957 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004958 namespace: Option<i64>,
4959 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004960 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004961 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004962 }
4963
4964 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4965 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004966 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004967 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004968 Ok(KeyEntryRow {
4969 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004970 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004971 domain: match row.get(2)? {
4972 Some(i) => Some(Domain(i)),
4973 None => None,
4974 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004975 namespace: row.get(3)?,
4976 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004977 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004978 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004979 })
4980 })?
4981 .map(|r| r.context("Could not read keyentry row."))
4982 .collect::<Result<Vec<_>>>()
4983 }
4984
Max Biresb2e1d032021-02-08 21:35:05 -08004985 struct RemoteProvValues {
4986 cert_chain: Vec<u8>,
4987 priv_key: Vec<u8>,
4988 batch_cert: Vec<u8>,
4989 }
4990
Max Bires2b2e6562020-09-22 11:22:36 -07004991 fn load_attestation_key_pool(
4992 db: &mut KeystoreDB,
4993 expiration_date: i64,
4994 namespace: i64,
4995 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004996 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004997 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4998 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4999 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
5000 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08005001 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07005002 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
5003 db.store_signed_attestation_certificate_chain(
5004 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08005005 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07005006 &cert_chain,
5007 expiration_date,
5008 &KEYSTORE_UUID,
5009 )?;
5010 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08005011 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07005012 }
5013
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005014 // Note: The parameters and SecurityLevel associations are nonsensical. This
5015 // collection is only used to check if the parameters are preserved as expected by the
5016 // database.
Qi Wub9433b52020-12-01 14:52:46 +08005017 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
5018 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005019 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
5020 KeyParameter::new(
5021 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
5022 SecurityLevel::TRUSTED_ENVIRONMENT,
5023 ),
5024 KeyParameter::new(
5025 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
5026 SecurityLevel::TRUSTED_ENVIRONMENT,
5027 ),
5028 KeyParameter::new(
5029 KeyParameterValue::Algorithm(Algorithm::RSA),
5030 SecurityLevel::TRUSTED_ENVIRONMENT,
5031 ),
5032 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
5033 KeyParameter::new(
5034 KeyParameterValue::BlockMode(BlockMode::ECB),
5035 SecurityLevel::TRUSTED_ENVIRONMENT,
5036 ),
5037 KeyParameter::new(
5038 KeyParameterValue::BlockMode(BlockMode::GCM),
5039 SecurityLevel::TRUSTED_ENVIRONMENT,
5040 ),
5041 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
5042 KeyParameter::new(
5043 KeyParameterValue::Digest(Digest::MD5),
5044 SecurityLevel::TRUSTED_ENVIRONMENT,
5045 ),
5046 KeyParameter::new(
5047 KeyParameterValue::Digest(Digest::SHA_2_224),
5048 SecurityLevel::TRUSTED_ENVIRONMENT,
5049 ),
5050 KeyParameter::new(
5051 KeyParameterValue::Digest(Digest::SHA_2_256),
5052 SecurityLevel::STRONGBOX,
5053 ),
5054 KeyParameter::new(
5055 KeyParameterValue::PaddingMode(PaddingMode::NONE),
5056 SecurityLevel::TRUSTED_ENVIRONMENT,
5057 ),
5058 KeyParameter::new(
5059 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
5060 SecurityLevel::TRUSTED_ENVIRONMENT,
5061 ),
5062 KeyParameter::new(
5063 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
5064 SecurityLevel::STRONGBOX,
5065 ),
5066 KeyParameter::new(
5067 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
5068 SecurityLevel::TRUSTED_ENVIRONMENT,
5069 ),
5070 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
5071 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
5072 KeyParameter::new(
5073 KeyParameterValue::EcCurve(EcCurve::P_224),
5074 SecurityLevel::TRUSTED_ENVIRONMENT,
5075 ),
5076 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
5077 KeyParameter::new(
5078 KeyParameterValue::EcCurve(EcCurve::P_384),
5079 SecurityLevel::TRUSTED_ENVIRONMENT,
5080 ),
5081 KeyParameter::new(
5082 KeyParameterValue::EcCurve(EcCurve::P_521),
5083 SecurityLevel::TRUSTED_ENVIRONMENT,
5084 ),
5085 KeyParameter::new(
5086 KeyParameterValue::RSAPublicExponent(3),
5087 SecurityLevel::TRUSTED_ENVIRONMENT,
5088 ),
5089 KeyParameter::new(
5090 KeyParameterValue::IncludeUniqueID,
5091 SecurityLevel::TRUSTED_ENVIRONMENT,
5092 ),
5093 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
5094 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
5095 KeyParameter::new(
5096 KeyParameterValue::ActiveDateTime(1234567890),
5097 SecurityLevel::STRONGBOX,
5098 ),
5099 KeyParameter::new(
5100 KeyParameterValue::OriginationExpireDateTime(1234567890),
5101 SecurityLevel::TRUSTED_ENVIRONMENT,
5102 ),
5103 KeyParameter::new(
5104 KeyParameterValue::UsageExpireDateTime(1234567890),
5105 SecurityLevel::TRUSTED_ENVIRONMENT,
5106 ),
5107 KeyParameter::new(
5108 KeyParameterValue::MinSecondsBetweenOps(1234567890),
5109 SecurityLevel::TRUSTED_ENVIRONMENT,
5110 ),
5111 KeyParameter::new(
5112 KeyParameterValue::MaxUsesPerBoot(1234567890),
5113 SecurityLevel::TRUSTED_ENVIRONMENT,
5114 ),
5115 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
5116 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
5117 KeyParameter::new(
5118 KeyParameterValue::NoAuthRequired,
5119 SecurityLevel::TRUSTED_ENVIRONMENT,
5120 ),
5121 KeyParameter::new(
5122 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
5123 SecurityLevel::TRUSTED_ENVIRONMENT,
5124 ),
5125 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
5126 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
5127 KeyParameter::new(
5128 KeyParameterValue::TrustedUserPresenceRequired,
5129 SecurityLevel::TRUSTED_ENVIRONMENT,
5130 ),
5131 KeyParameter::new(
5132 KeyParameterValue::TrustedConfirmationRequired,
5133 SecurityLevel::TRUSTED_ENVIRONMENT,
5134 ),
5135 KeyParameter::new(
5136 KeyParameterValue::UnlockedDeviceRequired,
5137 SecurityLevel::TRUSTED_ENVIRONMENT,
5138 ),
5139 KeyParameter::new(
5140 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
5141 SecurityLevel::SOFTWARE,
5142 ),
5143 KeyParameter::new(
5144 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
5145 SecurityLevel::SOFTWARE,
5146 ),
5147 KeyParameter::new(
5148 KeyParameterValue::CreationDateTime(12345677890),
5149 SecurityLevel::SOFTWARE,
5150 ),
5151 KeyParameter::new(
5152 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
5153 SecurityLevel::TRUSTED_ENVIRONMENT,
5154 ),
5155 KeyParameter::new(
5156 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
5157 SecurityLevel::TRUSTED_ENVIRONMENT,
5158 ),
5159 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
5160 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
5161 KeyParameter::new(
5162 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
5163 SecurityLevel::SOFTWARE,
5164 ),
5165 KeyParameter::new(
5166 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
5167 SecurityLevel::TRUSTED_ENVIRONMENT,
5168 ),
5169 KeyParameter::new(
5170 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
5171 SecurityLevel::TRUSTED_ENVIRONMENT,
5172 ),
5173 KeyParameter::new(
5174 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
5175 SecurityLevel::TRUSTED_ENVIRONMENT,
5176 ),
5177 KeyParameter::new(
5178 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
5179 SecurityLevel::TRUSTED_ENVIRONMENT,
5180 ),
5181 KeyParameter::new(
5182 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
5183 SecurityLevel::TRUSTED_ENVIRONMENT,
5184 ),
5185 KeyParameter::new(
5186 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
5187 SecurityLevel::TRUSTED_ENVIRONMENT,
5188 ),
5189 KeyParameter::new(
5190 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
5191 SecurityLevel::TRUSTED_ENVIRONMENT,
5192 ),
5193 KeyParameter::new(
5194 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
5195 SecurityLevel::TRUSTED_ENVIRONMENT,
5196 ),
5197 KeyParameter::new(
5198 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
5199 SecurityLevel::TRUSTED_ENVIRONMENT,
5200 ),
5201 KeyParameter::new(
5202 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
5203 SecurityLevel::TRUSTED_ENVIRONMENT,
5204 ),
5205 KeyParameter::new(
5206 KeyParameterValue::VendorPatchLevel(3),
5207 SecurityLevel::TRUSTED_ENVIRONMENT,
5208 ),
5209 KeyParameter::new(
5210 KeyParameterValue::BootPatchLevel(4),
5211 SecurityLevel::TRUSTED_ENVIRONMENT,
5212 ),
5213 KeyParameter::new(
5214 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
5215 SecurityLevel::TRUSTED_ENVIRONMENT,
5216 ),
5217 KeyParameter::new(
5218 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
5219 SecurityLevel::TRUSTED_ENVIRONMENT,
5220 ),
5221 KeyParameter::new(
5222 KeyParameterValue::MacLength(256),
5223 SecurityLevel::TRUSTED_ENVIRONMENT,
5224 ),
5225 KeyParameter::new(
5226 KeyParameterValue::ResetSinceIdRotation,
5227 SecurityLevel::TRUSTED_ENVIRONMENT,
5228 ),
5229 KeyParameter::new(
5230 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
5231 SecurityLevel::TRUSTED_ENVIRONMENT,
5232 ),
Qi Wub9433b52020-12-01 14:52:46 +08005233 ];
5234 if let Some(value) = max_usage_count {
5235 params.push(KeyParameter::new(
5236 KeyParameterValue::UsageCountLimit(value),
5237 SecurityLevel::SOFTWARE,
5238 ));
5239 }
5240 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07005241 }
5242
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005243 fn make_test_key_entry(
5244 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07005245 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005246 namespace: i64,
5247 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08005248 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08005249 ) -> Result<KeyIdGuard> {
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005250 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005251 let mut blob_metadata = BlobMetaData::new();
5252 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5253 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5254 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5255 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5256 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5257
5258 db.set_blob(
5259 &key_id,
5260 SubComponentType::KEY_BLOB,
5261 Some(TEST_KEY_BLOB),
5262 Some(&blob_metadata),
5263 )?;
5264 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5265 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08005266
5267 let params = make_test_params(max_usage_count);
5268 db.insert_keyparameter(&key_id, &params)?;
5269
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005270 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005271 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005272 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08005273 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005274 Ok(key_id)
5275 }
5276
Qi Wub9433b52020-12-01 14:52:46 +08005277 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
5278 let params = make_test_params(max_usage_count);
5279
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005280 let mut blob_metadata = BlobMetaData::new();
5281 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5282 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
5283 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
5284 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
5285 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5286
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005287 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005288 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005289
5290 KeyEntry {
5291 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08005292 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005293 cert: Some(TEST_CERT_BLOB.to_vec()),
5294 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08005295 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08005296 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005297 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08005298 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08005299 }
5300 }
5301
Janis Danisevskiscfaf9192021-05-26 16:31:02 -07005302 fn make_bootlevel_key_entry(
5303 db: &mut KeystoreDB,
5304 domain: Domain,
5305 namespace: i64,
5306 alias: &str,
5307 logical_only: bool,
5308 ) -> Result<KeyIdGuard> {
5309 let key_id = db.create_key_entry(&domain, &namespace, KeyType::Client, &KEYSTORE_UUID)?;
5310 let mut blob_metadata = BlobMetaData::new();
5311 if !logical_only {
5312 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5313 }
5314 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5315
5316 db.set_blob(
5317 &key_id,
5318 SubComponentType::KEY_BLOB,
5319 Some(TEST_KEY_BLOB),
5320 Some(&blob_metadata),
5321 )?;
5322 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
5323 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
5324
5325 let mut params = make_test_params(None);
5326 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5327
5328 db.insert_keyparameter(&key_id, &params)?;
5329
5330 let mut metadata = KeyMetaData::new();
5331 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5332 db.insert_key_metadata(&key_id, &metadata)?;
5333 rebind_alias(db, &key_id, alias, domain, namespace)?;
5334 Ok(key_id)
5335 }
5336
5337 fn make_bootlevel_test_key_entry_test_vector(key_id: i64, logical_only: bool) -> KeyEntry {
5338 let mut params = make_test_params(None);
5339 params.push(KeyParameter::new(KeyParameterValue::MaxBootLevel(3), SecurityLevel::KEYSTORE));
5340
5341 let mut blob_metadata = BlobMetaData::new();
5342 if !logical_only {
5343 blob_metadata.add(BlobMetaEntry::MaxBootLevel(3));
5344 }
5345 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
5346
5347 let mut metadata = KeyMetaData::new();
5348 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5349
5350 KeyEntry {
5351 id: key_id,
5352 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
5353 cert: Some(TEST_CERT_BLOB.to_vec()),
5354 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
5355 km_uuid: KEYSTORE_UUID,
5356 parameters: params,
5357 metadata,
5358 pure_cert: false,
5359 }
5360 }
5361
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005362 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005363 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08005364 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005365 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08005366 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005367 NO_PARAMS,
5368 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08005369 Ok((
5370 row.get(0)?,
5371 row.get(1)?,
5372 row.get(2)?,
5373 row.get(3)?,
5374 row.get(4)?,
5375 row.get(5)?,
5376 row.get(6)?,
5377 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08005378 },
5379 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005380
5381 println!("Key entry table rows:");
5382 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08005383 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005384 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08005385 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
5386 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005387 );
5388 }
5389 Ok(())
5390 }
5391
5392 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08005393 let mut stmt = db
5394 .conn
5395 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005396 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
5397 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
5398 })?;
5399
5400 println!("Grant table rows:");
5401 for r in rows {
5402 let (id, gt, ki, av) = r.unwrap();
5403 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
5404 }
5405 Ok(())
5406 }
5407
Joel Galenson0891bc12020-07-20 10:37:03 -07005408 // Use a custom random number generator that repeats each number once.
5409 // This allows us to test repeated elements.
5410
5411 thread_local! {
5412 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
5413 }
5414
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07005415 fn reset_random() {
5416 RANDOM_COUNTER.with(|counter| {
5417 *counter.borrow_mut() = 0;
5418 })
5419 }
5420
Joel Galenson0891bc12020-07-20 10:37:03 -07005421 pub fn random() -> i64 {
5422 RANDOM_COUNTER.with(|counter| {
5423 let result = *counter.borrow() / 2;
5424 *counter.borrow_mut() += 1;
5425 result
5426 })
5427 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005428
5429 #[test]
5430 fn test_last_off_body() -> Result<()> {
5431 let mut db = new_test_db()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005432 db.insert_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005433 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005434 tx.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005435 let last_off_body_1 = db.get_last_off_body();
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005436 let one_second = Duration::from_secs(1);
5437 thread::sleep(one_second);
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005438 db.update_last_off_body(MonotonicRawTime::now());
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005439 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005440 tx2.commit()?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005441 let last_off_body_2 = db.get_last_off_body();
Hasini Gunasinghe66a24602021-05-12 19:03:12 +00005442 assert!(last_off_body_1 < last_off_body_2);
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00005443 Ok(())
5444 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00005445
5446 #[test]
5447 fn test_unbind_keys_for_user() -> Result<()> {
5448 let mut db = new_test_db()?;
5449 db.unbind_keys_for_user(1, false)?;
5450
5451 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
5452 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
5453 db.unbind_keys_for_user(2, false)?;
5454
Janis Danisevskis18313832021-05-17 13:30:32 -07005455 assert_eq!(1, db.list(Domain::APP, 110000, KeyType::Client)?.len());
5456 assert_eq!(0, db.list(Domain::APP, 210000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005457
5458 db.unbind_keys_for_user(1, true)?;
Janis Danisevskis18313832021-05-17 13:30:32 -07005459 assert_eq!(0, db.list(Domain::APP, 110000, KeyType::Client)?.len());
Hasini Gunasingheda895552021-01-27 19:34:37 +00005460
5461 Ok(())
5462 }
5463
5464 #[test]
5465 fn test_store_super_key() -> Result<()> {
5466 let mut db = new_test_db()?;
Paul Crowleyf61fee72021-03-17 14:38:44 -07005467 let pw: keystore2_crypto::Password = (&b"xyzabc"[..]).into();
Hasini Gunasingheda895552021-01-27 19:34:37 +00005468 let super_key = keystore2_crypto::generate_aes256_key()?;
Paul Crowley7a658392021-03-18 17:08:20 -07005469 let secret_bytes = b"keystore2 is great.";
Hasini Gunasingheda895552021-01-27 19:34:37 +00005470 let (encrypted_secret, iv, tag) =
Paul Crowley7a658392021-03-18 17:08:20 -07005471 keystore2_crypto::aes_gcm_encrypt(secret_bytes, &super_key)?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005472
5473 let (encrypted_super_key, metadata) =
5474 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
Paul Crowley8d5b2532021-03-19 10:53:07 -07005475 db.store_super_key(
5476 1,
5477 &USER_SUPER_KEY,
5478 &encrypted_super_key,
5479 &metadata,
5480 &KeyMetaData::new(),
5481 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005482
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005483 //check if super key exists
Paul Crowley7a658392021-03-18 17:08:20 -07005484 assert!(db.key_exists(Domain::APP, 1, &USER_SUPER_KEY.alias, KeyType::Super)?);
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00005485
Paul Crowley7a658392021-03-18 17:08:20 -07005486 let (_, key_entry) = db.load_super_key(&USER_SUPER_KEY, 1)?.unwrap();
Paul Crowley8d5b2532021-03-19 10:53:07 -07005487 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(
5488 USER_SUPER_KEY.algorithm,
5489 key_entry,
5490 &pw,
5491 None,
5492 )?;
Hasini Gunasingheda895552021-01-27 19:34:37 +00005493
Paul Crowley7a658392021-03-18 17:08:20 -07005494 let decrypted_secret_bytes =
5495 loaded_super_key.aes_gcm_decrypt(&encrypted_secret, &iv, &tag)?;
5496 assert_eq!(secret_bytes, &*decrypted_secret_bytes);
Hasini Gunasingheda895552021-01-27 19:34:37 +00005497 Ok(())
5498 }
Seth Moore78c091f2021-04-09 21:38:30 +00005499
5500 fn get_valid_statsd_storage_types() -> Vec<StatsdStorageType> {
5501 vec![
5502 StatsdStorageType::KeyEntry,
5503 StatsdStorageType::KeyEntryIdIndex,
5504 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5505 StatsdStorageType::BlobEntry,
5506 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5507 StatsdStorageType::KeyParameter,
5508 StatsdStorageType::KeyParameterKeyEntryIdIndex,
5509 StatsdStorageType::KeyMetadata,
5510 StatsdStorageType::KeyMetadataKeyEntryIdIndex,
5511 StatsdStorageType::Grant,
5512 StatsdStorageType::AuthToken,
5513 StatsdStorageType::BlobMetadata,
5514 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5515 ]
5516 }
5517
5518 /// Perform a simple check to ensure that we can query all the storage types
5519 /// that are supported by the DB. Check for reasonable values.
5520 #[test]
5521 fn test_query_all_valid_table_sizes() -> Result<()> {
5522 const PAGE_SIZE: i64 = 4096;
5523
5524 let mut db = new_test_db()?;
5525
5526 for t in get_valid_statsd_storage_types() {
5527 let stat = db.get_storage_stat(t)?;
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005528 // AuthToken can be less than a page since it's in a btree, not sqlite
5529 // TODO(b/187474736) stop using if-let here
5530 if let StatsdStorageType::AuthToken = t {
5531 } else {
5532 assert!(stat.size >= PAGE_SIZE);
5533 }
Seth Moore78c091f2021-04-09 21:38:30 +00005534 assert!(stat.size >= stat.unused_size);
5535 }
5536
5537 Ok(())
5538 }
5539
5540 fn get_storage_stats_map(db: &mut KeystoreDB) -> BTreeMap<i32, Keystore2StorageStats> {
5541 get_valid_statsd_storage_types()
5542 .into_iter()
5543 .map(|t| (t as i32, db.get_storage_stat(t).unwrap()))
5544 .collect()
5545 }
5546
5547 fn assert_storage_increased(
5548 db: &mut KeystoreDB,
5549 increased_storage_types: Vec<StatsdStorageType>,
5550 baseline: &mut BTreeMap<i32, Keystore2StorageStats>,
5551 ) {
5552 for storage in increased_storage_types {
5553 // Verify the expected storage increased.
5554 let new = db.get_storage_stat(storage).unwrap();
5555 let storage = storage as i32;
5556 let old = &baseline[&storage];
5557 assert!(new.size >= old.size, "{}: {} >= {}", storage, new.size, old.size);
5558 assert!(
5559 new.unused_size <= old.unused_size,
5560 "{}: {} <= {}",
5561 storage,
5562 new.unused_size,
5563 old.unused_size
5564 );
5565
5566 // Update the baseline with the new value so that it succeeds in the
5567 // later comparison.
5568 baseline.insert(storage, new);
5569 }
5570
5571 // Get an updated map of the storage and verify there were no unexpected changes.
5572 let updated_stats = get_storage_stats_map(db);
5573 assert_eq!(updated_stats.len(), baseline.len());
5574
5575 for &k in baseline.keys() {
5576 let stringify = |map: &BTreeMap<i32, Keystore2StorageStats>| -> String {
5577 let mut s = String::new();
5578 for &k in map.keys() {
5579 writeln!(&mut s, " {}: {}, {}", &k, map[&k].size, map[&k].unused_size)
5580 .expect("string concat failed");
5581 }
5582 s
5583 };
5584
5585 assert!(
5586 updated_stats[&k].size == baseline[&k].size
5587 && updated_stats[&k].unused_size == baseline[&k].unused_size,
5588 "updated_stats:\n{}\nbaseline:\n{}",
5589 stringify(&updated_stats),
5590 stringify(&baseline)
5591 );
5592 }
5593 }
5594
5595 #[test]
5596 fn test_verify_key_table_size_reporting() -> Result<()> {
5597 let mut db = new_test_db()?;
5598 let mut working_stats = get_storage_stats_map(&mut db);
5599
Janis Danisevskis0cabd712021-05-25 11:07:10 -07005600 let key_id = db.create_key_entry(&Domain::APP, &42, KeyType::Client, &KEYSTORE_UUID)?;
Seth Moore78c091f2021-04-09 21:38:30 +00005601 assert_storage_increased(
5602 &mut db,
5603 vec![
5604 StatsdStorageType::KeyEntry,
5605 StatsdStorageType::KeyEntryIdIndex,
5606 StatsdStorageType::KeyEntryDomainNamespaceIndex,
5607 ],
5608 &mut working_stats,
5609 );
5610
5611 let mut blob_metadata = BlobMetaData::new();
5612 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
5613 db.set_blob(&key_id, SubComponentType::KEY_BLOB, Some(TEST_KEY_BLOB), None)?;
5614 assert_storage_increased(
5615 &mut db,
5616 vec![
5617 StatsdStorageType::BlobEntry,
5618 StatsdStorageType::BlobEntryKeyEntryIdIndex,
5619 StatsdStorageType::BlobMetadata,
5620 StatsdStorageType::BlobMetadataBlobEntryIdIndex,
5621 ],
5622 &mut working_stats,
5623 );
5624
5625 let params = make_test_params(None);
5626 db.insert_keyparameter(&key_id, &params)?;
5627 assert_storage_increased(
5628 &mut db,
5629 vec![StatsdStorageType::KeyParameter, StatsdStorageType::KeyParameterKeyEntryIdIndex],
5630 &mut working_stats,
5631 );
5632
5633 let mut metadata = KeyMetaData::new();
5634 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
5635 db.insert_key_metadata(&key_id, &metadata)?;
5636 assert_storage_increased(
5637 &mut db,
5638 vec![StatsdStorageType::KeyMetadata, StatsdStorageType::KeyMetadataKeyEntryIdIndex],
5639 &mut working_stats,
5640 );
5641
5642 let mut sum = 0;
5643 for stat in working_stats.values() {
5644 sum += stat.size;
5645 }
5646 let total = db.get_storage_stat(StatsdStorageType::Database)?.size;
5647 assert!(sum <= total, "Expected sum <= total. sum: {}, total: {}", sum, total);
5648
5649 Ok(())
5650 }
5651
5652 #[test]
5653 fn test_verify_auth_table_size_reporting() -> Result<()> {
5654 let mut db = new_test_db()?;
5655 let mut working_stats = get_storage_stats_map(&mut db);
5656 db.insert_auth_token(&HardwareAuthToken {
5657 challenge: 123,
5658 userId: 456,
5659 authenticatorId: 789,
5660 authenticatorType: kmhw_authenticator_type::ANY,
5661 timestamp: Timestamp { milliSeconds: 10 },
5662 mac: b"mac".to_vec(),
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005663 });
Seth Moore78c091f2021-04-09 21:38:30 +00005664 assert_storage_increased(&mut db, vec![StatsdStorageType::AuthToken], &mut working_stats);
5665 Ok(())
5666 }
5667
5668 #[test]
5669 fn test_verify_grant_table_size_reporting() -> Result<()> {
5670 const OWNER: i64 = 1;
5671 let mut db = new_test_db()?;
5672 make_test_key_entry(&mut db, Domain::APP, OWNER, TEST_ALIAS, None)?;
5673
5674 let mut working_stats = get_storage_stats_map(&mut db);
5675 db.grant(
5676 &KeyDescriptor {
5677 domain: Domain::APP,
5678 nspace: 0,
5679 alias: Some(TEST_ALIAS.to_string()),
5680 blob: None,
5681 },
5682 OWNER as u32,
5683 123,
5684 key_perm_set![KeyPerm::use_()],
5685 |_, _| Ok(()),
5686 )?;
5687
5688 assert_storage_increased(&mut db, vec![StatsdStorageType::Grant], &mut working_stats);
5689
5690 Ok(())
5691 }
Matthew Maurerd7815ca2021-05-06 21:58:45 -07005692
5693 #[test]
5694 fn find_auth_token_entry_returns_latest() -> Result<()> {
5695 let mut db = new_test_db()?;
5696 db.insert_auth_token(&HardwareAuthToken {
5697 challenge: 123,
5698 userId: 456,
5699 authenticatorId: 789,
5700 authenticatorType: kmhw_authenticator_type::ANY,
5701 timestamp: Timestamp { milliSeconds: 10 },
5702 mac: b"mac0".to_vec(),
5703 });
5704 std::thread::sleep(std::time::Duration::from_millis(1));
5705 db.insert_auth_token(&HardwareAuthToken {
5706 challenge: 123,
5707 userId: 457,
5708 authenticatorId: 789,
5709 authenticatorType: kmhw_authenticator_type::ANY,
5710 timestamp: Timestamp { milliSeconds: 12 },
5711 mac: b"mac1".to_vec(),
5712 });
5713 std::thread::sleep(std::time::Duration::from_millis(1));
5714 db.insert_auth_token(&HardwareAuthToken {
5715 challenge: 123,
5716 userId: 458,
5717 authenticatorId: 789,
5718 authenticatorType: kmhw_authenticator_type::ANY,
5719 timestamp: Timestamp { milliSeconds: 3 },
5720 mac: b"mac2".to_vec(),
5721 });
5722 // All three entries are in the database
5723 assert_eq!(db.perboot.auth_tokens_len(), 3);
5724 // It selected the most recent timestamp
5725 assert_eq!(db.find_auth_token_entry(|_| true).unwrap().0.auth_token.mac, b"mac2".to_vec());
5726 Ok(())
5727 }
Seth Moore472fcbb2021-05-12 10:07:51 -07005728
5729 #[test]
Pavel Grafovf45034a2021-05-12 22:35:45 +01005730 fn test_load_key_descriptor() -> Result<()> {
5731 let mut db = new_test_db()?;
5732 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)?.0;
5733
5734 let key = db.load_key_descriptor(key_id)?.unwrap();
5735
5736 assert_eq!(key.domain, Domain::APP);
5737 assert_eq!(key.nspace, 1);
5738 assert_eq!(key.alias, Some(TEST_ALIAS.to_string()));
5739
5740 // No such id
5741 assert_eq!(db.load_key_descriptor(key_id + 1)?, None);
5742 Ok(())
5743 }
Joel Galenson26f4d012020-07-17 14:57:21 -07005744}