blob: fcfdabef9dab760889b2183413ef0a9dce1b29e9 [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
Qi Wub9433b52020-12-01 14:52:46 +080044use crate::error::{Error as KsError, ErrorCode, ResponseCode};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080045use crate::impl_metadata; // This is in db_utils.rs
Janis Danisevskis4522c2b2020-11-27 18:04:58 -080046use crate::key_parameter::{KeyParameter, Tag};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070047use crate::permission::KeyPermSet;
Hasini Gunasingheda895552021-01-27 19:34:37 +000048use crate::utils::{get_current_time_in_seconds, AID_USER_OFFSET};
Janis Danisevskis7e8b4622021-02-13 10:01:59 -080049use crate::{
50 db_utils::{self, SqlField},
51 gc::Gc,
52};
Janis Danisevskisb42fc182020-12-15 08:41:27 -080053use anyhow::{anyhow, Context, Result};
Max Bires8e93d2b2021-01-14 13:17:59 -080054use std::{convert::TryFrom, convert::TryInto, ops::Deref, time::SystemTimeError};
Janis Danisevskis60400fe2020-08-26 15:24:42 -070055
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000056use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080057 HardwareAuthToken::HardwareAuthToken,
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000058 HardwareAuthenticatorType::HardwareAuthenticatorType, SecurityLevel::SecurityLevel,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -080059};
60use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000061 Timestamp::Timestamp,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +000062};
Janis Danisevskisc5b210b2020-09-11 13:27:37 -070063use android_system_keystore2::aidl::android::system::keystore2::{
Janis Danisevskis04b02832020-10-26 09:21:40 -070064 Domain::Domain, KeyDescriptor::KeyDescriptor,
Janis Danisevskis60400fe2020-08-26 15:24:42 -070065};
Max Bires2b2e6562020-09-22 11:22:36 -070066use android_security_remoteprovisioning::aidl::android::security::remoteprovisioning::{
67 AttestationPoolStatus::AttestationPoolStatus,
68};
69
70use keystore2_crypto::ZVec;
Janis Danisevskisaec14592020-11-12 09:41:49 -080071use lazy_static::lazy_static;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +000072use log::error;
Joel Galenson0891bc12020-07-20 10:37:03 -070073#[cfg(not(test))]
74use rand::prelude::random;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070075use rusqlite::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080076 params,
77 types::FromSql,
78 types::FromSqlResult,
79 types::ToSqlOutput,
80 types::{FromSqlError, Value, ValueRef},
Janis Danisevskis5ed8c532021-01-11 14:19:42 -080081 Connection, OptionalExtension, ToSql, Transaction, TransactionBehavior, NO_PARAMS,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -070082};
Max Bires2b2e6562020-09-22 11:22:36 -070083
Janis Danisevskisaec14592020-11-12 09:41:49 -080084use std::{
Janis Danisevskisb42fc182020-12-15 08:41:27 -080085 collections::{HashMap, HashSet},
Janis Danisevskisbf15d732020-12-08 10:35:26 -080086 path::Path,
87 sync::{Condvar, Mutex},
Janis Danisevskisb42fc182020-12-15 08:41:27 -080088 time::{Duration, SystemTime},
Janis Danisevskisaec14592020-11-12 09:41:49 -080089};
Max Bires2b2e6562020-09-22 11:22:36 -070090
Joel Galenson0891bc12020-07-20 10:37:03 -070091#[cfg(test)]
92use tests::random;
Joel Galenson26f4d012020-07-17 14:57:21 -070093
Janis Danisevskisb42fc182020-12-15 08:41:27 -080094impl_metadata!(
95 /// A set of metadata for key entries.
96 #[derive(Debug, Default, Eq, PartialEq)]
97 pub struct KeyMetaData;
98 /// A metadata entry for key entries.
99 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
100 pub enum KeyMetaEntry {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800101 /// Date of the creation of the key entry.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800102 CreationDate(DateTime) with accessor creation_date,
103 /// Expiration date for attestation keys.
104 AttestationExpirationDate(DateTime) with accessor attestation_expiration_date,
Max Bires2b2e6562020-09-22 11:22:36 -0700105 /// CBOR Blob that represents a COSE_Key and associated metadata needed for remote
106 /// provisioning
107 AttestationMacedPublicKey(Vec<u8>) with accessor attestation_maced_public_key,
108 /// Vector representing the raw public key so results from the server can be matched
109 /// to the right entry
110 AttestationRawPubKey(Vec<u8>) with accessor attestation_raw_pub_key,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800111 // --- ADD NEW META DATA FIELDS HERE ---
112 // For backwards compatibility add new entries only to
113 // end of this list and above this comment.
114 };
115);
116
117impl KeyMetaData {
118 fn load_from_db(key_id: i64, tx: &Transaction) -> Result<Self> {
119 let mut stmt = tx
120 .prepare(
121 "SELECT tag, data from persistent.keymetadata
122 WHERE keyentryid = ?;",
123 )
124 .context("In KeyMetaData::load_from_db: prepare statement failed.")?;
125
126 let mut metadata: HashMap<i64, KeyMetaEntry> = Default::default();
127
128 let mut rows =
129 stmt.query(params![key_id]).context("In KeyMetaData::load_from_db: query failed.")?;
130 db_utils::with_rows_extract_all(&mut rows, |row| {
131 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
132 metadata.insert(
133 db_tag,
134 KeyMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
135 .context("Failed to read KeyMetaEntry.")?,
136 );
137 Ok(())
138 })
139 .context("In KeyMetaData::load_from_db.")?;
140
141 Ok(Self { data: metadata })
142 }
143
144 fn store_in_db(&self, key_id: i64, tx: &Transaction) -> Result<()> {
145 let mut stmt = tx
146 .prepare(
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000147 "INSERT or REPLACE INTO persistent.keymetadata (keyentryid, tag, data)
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800148 VALUES (?, ?, ?);",
149 )
150 .context("In KeyMetaData::store_in_db: Failed to prepare statement.")?;
151
152 let iter = self.data.iter();
153 for (tag, entry) in iter {
154 stmt.insert(params![key_id, tag, entry,]).with_context(|| {
155 format!("In KeyMetaData::store_in_db: Failed to insert {:?}", entry)
156 })?;
157 }
158 Ok(())
159 }
160}
161
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800162impl_metadata!(
163 /// A set of metadata for key blobs.
164 #[derive(Debug, Default, Eq, PartialEq)]
165 pub struct BlobMetaData;
166 /// A metadata entry for key blobs.
167 #[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
168 pub enum BlobMetaEntry {
169 /// If present, indicates that the blob is encrypted with another key or a key derived
170 /// from a password.
171 EncryptedBy(EncryptedBy) with accessor encrypted_by,
172 /// If the blob is password encrypted this field is set to the
173 /// salt used for the key derivation.
174 Salt(Vec<u8>) with accessor salt,
175 /// If the blob is encrypted, this field is set to the initialization vector.
176 Iv(Vec<u8>) with accessor iv,
177 /// If the blob is encrypted, this field holds the AEAD TAG.
178 AeadTag(Vec<u8>) with accessor aead_tag,
179 /// The uuid of the owning KeyMint instance.
180 KmUuid(Uuid) with accessor km_uuid,
181 // --- ADD NEW META DATA FIELDS HERE ---
182 // For backwards compatibility add new entries only to
183 // end of this list and above this comment.
184 };
185);
186
187impl BlobMetaData {
188 fn load_from_db(blob_id: i64, tx: &Transaction) -> Result<Self> {
189 let mut stmt = tx
190 .prepare(
191 "SELECT tag, data from persistent.blobmetadata
192 WHERE blobentryid = ?;",
193 )
194 .context("In BlobMetaData::load_from_db: prepare statement failed.")?;
195
196 let mut metadata: HashMap<i64, BlobMetaEntry> = Default::default();
197
198 let mut rows =
199 stmt.query(params![blob_id]).context("In BlobMetaData::load_from_db: query failed.")?;
200 db_utils::with_rows_extract_all(&mut rows, |row| {
201 let db_tag: i64 = row.get(0).context("Failed to read tag.")?;
202 metadata.insert(
203 db_tag,
204 BlobMetaEntry::new_from_sql(db_tag, &SqlField::new(1, &row))
205 .context("Failed to read BlobMetaEntry.")?,
206 );
207 Ok(())
208 })
209 .context("In BlobMetaData::load_from_db.")?;
210
211 Ok(Self { data: metadata })
212 }
213
214 fn store_in_db(&self, blob_id: i64, tx: &Transaction) -> Result<()> {
215 let mut stmt = tx
216 .prepare(
217 "INSERT or REPLACE INTO persistent.blobmetadata (blobentryid, tag, data)
218 VALUES (?, ?, ?);",
219 )
220 .context("In BlobMetaData::store_in_db: Failed to prepare statement.")?;
221
222 let iter = self.data.iter();
223 for (tag, entry) in iter {
224 stmt.insert(params![blob_id, tag, entry,]).with_context(|| {
225 format!("In BlobMetaData::store_in_db: Failed to insert {:?}", entry)
226 })?;
227 }
228 Ok(())
229 }
230}
231
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800232/// Indicates the type of the keyentry.
233#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
234pub enum KeyType {
235 /// This is a client key type. These keys are created or imported through the Keystore 2.0
236 /// AIDL interface android.system.keystore2.
237 Client,
238 /// This is a super key type. These keys are created by keystore itself and used to encrypt
239 /// other key blobs to provide LSKF binding.
240 Super,
241 /// This is an attestation key. These keys are created by the remote provisioning mechanism.
242 Attestation,
243}
244
245impl ToSql for KeyType {
246 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
247 Ok(ToSqlOutput::Owned(Value::Integer(match self {
248 KeyType::Client => 0,
249 KeyType::Super => 1,
250 KeyType::Attestation => 2,
251 })))
252 }
253}
254
255impl FromSql for KeyType {
256 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
257 match i64::column_result(value)? {
258 0 => Ok(KeyType::Client),
259 1 => Ok(KeyType::Super),
260 2 => Ok(KeyType::Attestation),
261 v => Err(FromSqlError::OutOfRange(v)),
262 }
263 }
264}
265
Max Bires8e93d2b2021-01-14 13:17:59 -0800266/// Uuid representation that can be stored in the database.
267/// Right now it can only be initialized from SecurityLevel.
268/// Once KeyMint provides a UUID type a corresponding From impl shall be added.
269#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
270pub struct Uuid([u8; 16]);
271
272impl Deref for Uuid {
273 type Target = [u8; 16];
274
275 fn deref(&self) -> &Self::Target {
276 &self.0
277 }
278}
279
280impl From<SecurityLevel> for Uuid {
281 fn from(sec_level: SecurityLevel) -> Self {
282 Self((sec_level.0 as u128).to_be_bytes())
283 }
284}
285
286impl ToSql for Uuid {
287 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
288 self.0.to_sql()
289 }
290}
291
292impl FromSql for Uuid {
293 fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
294 let blob = Vec::<u8>::column_result(value)?;
295 if blob.len() != 16 {
296 return Err(FromSqlError::OutOfRange(blob.len() as i64));
297 }
298 let mut arr = [0u8; 16];
299 arr.copy_from_slice(&blob);
300 Ok(Self(arr))
301 }
302}
303
304/// Key entries that are not associated with any KeyMint instance, such as pure certificate
305/// entries are associated with this UUID.
306pub static KEYSTORE_UUID: Uuid = Uuid([
307 0x41, 0xe3, 0xb9, 0xce, 0x27, 0x58, 0x4e, 0x91, 0xbc, 0xfd, 0xa5, 0x5d, 0x91, 0x85, 0xab, 0x11,
308]);
309
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800310/// Indicates how the sensitive part of this key blob is encrypted.
311#[derive(Debug, Eq, PartialEq, Ord, PartialOrd)]
312pub enum EncryptedBy {
313 /// The keyblob is encrypted by a user password.
314 /// In the database this variant is represented as NULL.
315 Password,
316 /// The keyblob is encrypted by another key with wrapped key id.
317 /// In the database this variant is represented as non NULL value
318 /// that is convertible to i64, typically NUMERIC.
319 KeyId(i64),
320}
321
322impl ToSql for EncryptedBy {
323 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
324 match self {
325 Self::Password => Ok(ToSqlOutput::Owned(Value::Null)),
326 Self::KeyId(id) => id.to_sql(),
327 }
328 }
329}
330
331impl FromSql for EncryptedBy {
332 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
333 match value {
334 ValueRef::Null => Ok(Self::Password),
335 _ => Ok(Self::KeyId(i64::column_result(value)?)),
336 }
337 }
338}
339
340/// A database representation of wall clock time. DateTime stores unix epoch time as
341/// i64 in milliseconds.
342#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
343pub struct DateTime(i64);
344
345/// Error type returned when creating DateTime or converting it from and to
346/// SystemTime.
347#[derive(thiserror::Error, Debug)]
348pub enum DateTimeError {
349 /// This is returned when SystemTime and Duration computations fail.
350 #[error(transparent)]
351 SystemTimeError(#[from] SystemTimeError),
352
353 /// This is returned when type conversions fail.
354 #[error(transparent)]
355 TypeConversion(#[from] std::num::TryFromIntError),
356
357 /// This is returned when checked time arithmetic failed.
358 #[error("Time arithmetic failed.")]
359 TimeArithmetic,
360}
361
362impl DateTime {
363 /// Constructs a new DateTime object denoting the current time. This may fail during
364 /// conversion to unix epoch time and during conversion to the internal i64 representation.
365 pub fn now() -> Result<Self, DateTimeError> {
366 Ok(Self(SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
367 }
368
369 /// Constructs a new DateTime object from milliseconds.
370 pub fn from_millis_epoch(millis: i64) -> Self {
371 Self(millis)
372 }
373
374 /// Returns unix epoch time in milliseconds.
375 pub fn to_millis_epoch(&self) -> i64 {
376 self.0
377 }
378
379 /// Returns unix epoch time in seconds.
380 pub fn to_secs_epoch(&self) -> i64 {
381 self.0 / 1000
382 }
383}
384
385impl ToSql for DateTime {
386 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
387 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
388 }
389}
390
391impl FromSql for DateTime {
392 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
393 Ok(Self(i64::column_result(value)?))
394 }
395}
396
397impl TryInto<SystemTime> for DateTime {
398 type Error = DateTimeError;
399
400 fn try_into(self) -> Result<SystemTime, Self::Error> {
401 // We want to construct a SystemTime representation equivalent to self, denoting
402 // a point in time THEN, but we cannot set the time directly. We can only construct
403 // a SystemTime denoting NOW, and we can get the duration between EPOCH and NOW,
404 // and between EPOCH and THEN. With this common reference we can construct the
405 // duration between NOW and THEN which we can add to our SystemTime representation
406 // of NOW to get a SystemTime representation of THEN.
407 // Durations can only be positive, thus the if statement below.
408 let now = SystemTime::now();
409 let now_epoch = now.duration_since(SystemTime::UNIX_EPOCH)?;
410 let then_epoch = Duration::from_millis(self.0.try_into()?);
411 Ok(if now_epoch > then_epoch {
412 // then = now - (now_epoch - then_epoch)
413 now_epoch
414 .checked_sub(then_epoch)
415 .and_then(|d| now.checked_sub(d))
416 .ok_or(DateTimeError::TimeArithmetic)?
417 } else {
418 // then = now + (then_epoch - now_epoch)
419 then_epoch
420 .checked_sub(now_epoch)
421 .and_then(|d| now.checked_add(d))
422 .ok_or(DateTimeError::TimeArithmetic)?
423 })
424 }
425}
426
427impl TryFrom<SystemTime> for DateTime {
428 type Error = DateTimeError;
429
430 fn try_from(t: SystemTime) -> Result<Self, Self::Error> {
431 Ok(Self(t.duration_since(SystemTime::UNIX_EPOCH)?.as_millis().try_into()?))
432 }
433}
434
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800435#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Copy, Clone)]
436enum KeyLifeCycle {
437 /// Existing keys have a key ID but are not fully populated yet.
438 /// This is a transient state. If Keystore finds any such keys when it starts up, it must move
439 /// them to Unreferenced for garbage collection.
440 Existing,
441 /// A live key is fully populated and usable by clients.
442 Live,
443 /// An unreferenced key is scheduled for garbage collection.
444 Unreferenced,
445}
446
447impl ToSql for KeyLifeCycle {
448 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
449 match self {
450 Self::Existing => Ok(ToSqlOutput::Owned(Value::Integer(0))),
451 Self::Live => Ok(ToSqlOutput::Owned(Value::Integer(1))),
452 Self::Unreferenced => Ok(ToSqlOutput::Owned(Value::Integer(2))),
453 }
454 }
455}
456
457impl FromSql for KeyLifeCycle {
458 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
459 match i64::column_result(value)? {
460 0 => Ok(KeyLifeCycle::Existing),
461 1 => Ok(KeyLifeCycle::Live),
462 2 => Ok(KeyLifeCycle::Unreferenced),
463 v => Err(FromSqlError::OutOfRange(v)),
464 }
465 }
466}
467
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700468/// Keys have a KeyMint blob component and optional public certificate and
469/// certificate chain components.
470/// KeyEntryLoadBits is a bitmap that indicates to `KeystoreDB::load_key_entry`
471/// which components shall be loaded from the database if present.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800472#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700473pub struct KeyEntryLoadBits(u32);
474
475impl KeyEntryLoadBits {
476 /// Indicate to `KeystoreDB::load_key_entry` that no component shall be loaded.
477 pub const NONE: KeyEntryLoadBits = Self(0);
478 /// Indicate to `KeystoreDB::load_key_entry` that the KeyMint component shall be loaded.
479 pub const KM: KeyEntryLoadBits = Self(1);
480 /// Indicate to `KeystoreDB::load_key_entry` that the Public components shall be loaded.
481 pub const PUBLIC: KeyEntryLoadBits = Self(2);
482 /// Indicate to `KeystoreDB::load_key_entry` that both components shall be loaded.
483 pub const BOTH: KeyEntryLoadBits = Self(3);
484
485 /// Returns true if this object indicates that the public components shall be loaded.
486 pub const fn load_public(&self) -> bool {
487 self.0 & Self::PUBLIC.0 != 0
488 }
489
490 /// Returns true if the object indicates that the KeyMint component shall be loaded.
491 pub const fn load_km(&self) -> bool {
492 self.0 & Self::KM.0 != 0
493 }
494}
495
Janis Danisevskisaec14592020-11-12 09:41:49 -0800496lazy_static! {
497 static ref KEY_ID_LOCK: KeyIdLockDb = KeyIdLockDb::new();
498}
499
500struct KeyIdLockDb {
501 locked_keys: Mutex<HashSet<i64>>,
502 cond_var: Condvar,
503}
504
505/// A locked key. While a guard exists for a given key id, the same key cannot be loaded
506/// from the database a second time. Most functions manipulating the key blob database
507/// require a KeyIdGuard.
508#[derive(Debug)]
509pub struct KeyIdGuard(i64);
510
511impl KeyIdLockDb {
512 fn new() -> Self {
513 Self { locked_keys: Mutex::new(HashSet::new()), cond_var: Condvar::new() }
514 }
515
516 /// This function blocks until an exclusive lock for the given key entry id can
517 /// be acquired. It returns a guard object, that represents the lifecycle of the
518 /// acquired lock.
519 pub fn get(&self, key_id: i64) -> KeyIdGuard {
520 let mut locked_keys = self.locked_keys.lock().unwrap();
521 while locked_keys.contains(&key_id) {
522 locked_keys = self.cond_var.wait(locked_keys).unwrap();
523 }
524 locked_keys.insert(key_id);
525 KeyIdGuard(key_id)
526 }
527
528 /// This function attempts to acquire an exclusive lock on a given key id. If the
529 /// given key id is already taken the function returns None immediately. If a lock
530 /// can be acquired this function returns a guard object, that represents the
531 /// lifecycle of the acquired lock.
532 pub fn try_get(&self, key_id: i64) -> Option<KeyIdGuard> {
533 let mut locked_keys = self.locked_keys.lock().unwrap();
534 if locked_keys.insert(key_id) {
535 Some(KeyIdGuard(key_id))
536 } else {
537 None
538 }
539 }
540}
541
542impl KeyIdGuard {
543 /// Get the numeric key id of the locked key.
544 pub fn id(&self) -> i64 {
545 self.0
546 }
547}
548
549impl Drop for KeyIdGuard {
550 fn drop(&mut self) {
551 let mut locked_keys = KEY_ID_LOCK.locked_keys.lock().unwrap();
552 locked_keys.remove(&self.0);
Janis Danisevskis7fd53582020-11-23 13:40:34 -0800553 drop(locked_keys);
Janis Danisevskisaec14592020-11-12 09:41:49 -0800554 KEY_ID_LOCK.cond_var.notify_all();
555 }
556}
557
Max Bires8e93d2b2021-01-14 13:17:59 -0800558/// This type represents a certificate and certificate chain entry for a key.
Max Bires2b2e6562020-09-22 11:22:36 -0700559#[derive(Debug, Default)]
Max Bires8e93d2b2021-01-14 13:17:59 -0800560pub struct CertificateInfo {
561 cert: Option<Vec<u8>>,
562 cert_chain: Option<Vec<u8>>,
563}
564
565impl CertificateInfo {
566 /// Constructs a new CertificateInfo object from `cert` and `cert_chain`
567 pub fn new(cert: Option<Vec<u8>>, cert_chain: Option<Vec<u8>>) -> Self {
568 Self { cert, cert_chain }
569 }
570
571 /// Take the cert
572 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
573 self.cert.take()
574 }
575
576 /// Take the cert chain
577 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
578 self.cert_chain.take()
579 }
580}
581
Max Bires2b2e6562020-09-22 11:22:36 -0700582/// This type represents a certificate chain with a private key corresponding to the leaf
583/// certificate. TODO(jbires): This will be used in a follow-on CL, for now it's used in the tests.
584#[allow(dead_code)]
585pub struct CertificateChain {
586 private_key: ZVec,
Max Biresb2e1d032021-02-08 21:35:05 -0800587 batch_cert: ZVec,
Max Bires2b2e6562020-09-22 11:22:36 -0700588 cert_chain: ZVec,
589}
590
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700591/// This type represents a Keystore 2.0 key entry.
592/// An entry has a unique `id` by which it can be found in the database.
593/// It has a security level field, key parameters, and three optional fields
594/// for the KeyMint blob, public certificate and a public certificate chain.
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800595#[derive(Debug, Default, Eq, PartialEq)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700596pub struct KeyEntry {
597 id: i64,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800598 key_blob_info: Option<(Vec<u8>, BlobMetaData)>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700599 cert: Option<Vec<u8>>,
600 cert_chain: Option<Vec<u8>>,
Max Bires8e93d2b2021-01-14 13:17:59 -0800601 km_uuid: Uuid,
Janis Danisevskis3f322cb2020-09-03 14:46:22 -0700602 parameters: Vec<KeyParameter>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800603 metadata: KeyMetaData,
Janis Danisevskis377d1002021-01-27 19:07:48 -0800604 pure_cert: bool,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700605}
606
607impl KeyEntry {
608 /// Returns the unique id of the Key entry.
609 pub fn id(&self) -> i64 {
610 self.id
611 }
612 /// Exposes the optional KeyMint blob.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800613 pub fn key_blob_info(&self) -> &Option<(Vec<u8>, BlobMetaData)> {
614 &self.key_blob_info
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700615 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800616 /// Extracts the Optional KeyMint blob including its metadata.
617 pub fn take_key_blob_info(&mut self) -> Option<(Vec<u8>, BlobMetaData)> {
618 self.key_blob_info.take()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700619 }
620 /// Exposes the optional public certificate.
621 pub fn cert(&self) -> &Option<Vec<u8>> {
622 &self.cert
623 }
624 /// Extracts the optional public certificate.
625 pub fn take_cert(&mut self) -> Option<Vec<u8>> {
626 self.cert.take()
627 }
628 /// Exposes the optional public certificate chain.
629 pub fn cert_chain(&self) -> &Option<Vec<u8>> {
630 &self.cert_chain
631 }
632 /// Extracts the optional public certificate_chain.
633 pub fn take_cert_chain(&mut self) -> Option<Vec<u8>> {
634 self.cert_chain.take()
635 }
Max Bires8e93d2b2021-01-14 13:17:59 -0800636 /// Returns the uuid of the owning KeyMint instance.
637 pub fn km_uuid(&self) -> &Uuid {
638 &self.km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700639 }
Janis Danisevskis04b02832020-10-26 09:21:40 -0700640 /// Exposes the key parameters of this key entry.
641 pub fn key_parameters(&self) -> &Vec<KeyParameter> {
642 &self.parameters
643 }
644 /// Consumes this key entry and extracts the keyparameters from it.
645 pub fn into_key_parameters(self) -> Vec<KeyParameter> {
646 self.parameters
647 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800648 /// Exposes the key metadata of this key entry.
649 pub fn metadata(&self) -> &KeyMetaData {
650 &self.metadata
651 }
Janis Danisevskis377d1002021-01-27 19:07:48 -0800652 /// This returns true if the entry is a pure certificate entry with no
653 /// private key component.
654 pub fn pure_cert(&self) -> bool {
655 self.pure_cert
656 }
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000657 /// Consumes this key entry and extracts the keyparameters and metadata from it.
658 pub fn into_key_parameters_and_metadata(self) -> (Vec<KeyParameter>, KeyMetaData) {
659 (self.parameters, self.metadata)
660 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700661}
662
663/// Indicates the sub component of a key entry for persistent storage.
Janis Danisevskis377d1002021-01-27 19:07:48 -0800664#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd)]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700665pub struct SubComponentType(u32);
666impl SubComponentType {
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800667 /// Persistent identifier for a key blob.
668 pub const KEY_BLOB: SubComponentType = Self(0);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700669 /// Persistent identifier for a certificate blob.
670 pub const CERT: SubComponentType = Self(1);
671 /// Persistent identifier for a certificate chain blob.
672 pub const CERT_CHAIN: SubComponentType = Self(2);
673}
674
675impl ToSql for SubComponentType {
676 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
677 self.0.to_sql()
678 }
679}
680
681impl FromSql for SubComponentType {
682 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
683 Ok(Self(u32::column_result(value)?))
684 }
685}
686
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800687/// This trait is private to the database module. It is used to convey whether or not the garbage
688/// collector shall be invoked after a database access. All closures passed to
689/// `KeystoreDB::with_transaction` return a tuple (bool, T) where the bool indicates if the
690/// gc needs to be triggered. This convenience function allows to turn any anyhow::Result<T>
691/// into anyhow::Result<(bool, T)> by simply appending one of `.do_gc(bool)`, `.no_gc()`, or
692/// `.need_gc()`.
693trait DoGc<T> {
694 fn do_gc(self, need_gc: bool) -> Result<(bool, T)>;
695
696 fn no_gc(self) -> Result<(bool, T)>;
697
698 fn need_gc(self) -> Result<(bool, T)>;
699}
700
701impl<T> DoGc<T> for Result<T> {
702 fn do_gc(self, need_gc: bool) -> Result<(bool, T)> {
703 self.map(|r| (need_gc, r))
704 }
705
706 fn no_gc(self) -> Result<(bool, T)> {
707 self.do_gc(false)
708 }
709
710 fn need_gc(self) -> Result<(bool, T)> {
711 self.do_gc(true)
712 }
713}
714
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700715/// KeystoreDB wraps a connection to an SQLite database and tracks its
716/// ownership. It also implements all of Keystore 2.0's database functionality.
Joel Galenson26f4d012020-07-17 14:57:21 -0700717pub struct KeystoreDB {
Joel Galenson26f4d012020-07-17 14:57:21 -0700718 conn: Connection,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800719 gc: Option<Gc>,
Joel Galenson26f4d012020-07-17 14:57:21 -0700720}
721
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000722/// Database representation of the monotonic time retrieved from the system call clock_gettime with
723/// CLOCK_MONOTONIC_RAW. Stores monotonic time as i64 in seconds.
724#[derive(Debug, Copy, Clone, Default, Eq, PartialEq, Ord, PartialOrd)]
725pub struct MonotonicRawTime(i64);
726
727impl MonotonicRawTime {
728 /// Constructs a new MonotonicRawTime
729 pub fn now() -> Self {
730 Self(get_current_time_in_seconds())
731 }
732
733 /// Returns the integer value of MonotonicRawTime as i64
734 pub fn seconds(&self) -> i64 {
735 self.0
736 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800737
738 /// Like i64::checked_sub.
739 pub fn checked_sub(&self, other: &Self) -> Option<Self> {
740 self.0.checked_sub(other.0).map(Self)
741 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000742}
743
744impl ToSql for MonotonicRawTime {
745 fn to_sql(&self) -> rusqlite::Result<ToSqlOutput> {
746 Ok(ToSqlOutput::Owned(Value::Integer(self.0)))
747 }
748}
749
750impl FromSql for MonotonicRawTime {
751 fn column_result(value: ValueRef) -> FromSqlResult<Self> {
752 Ok(Self(i64::column_result(value)?))
753 }
754}
755
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000756/// This struct encapsulates the information to be stored in the database about the auth tokens
757/// received by keystore.
758pub struct AuthTokenEntry {
759 auth_token: HardwareAuthToken,
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000760 time_received: MonotonicRawTime,
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000761}
762
763impl AuthTokenEntry {
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000764 fn new(auth_token: HardwareAuthToken, time_received: MonotonicRawTime) -> Self {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000765 AuthTokenEntry { auth_token, time_received }
766 }
767
768 /// Checks if this auth token satisfies the given authentication information.
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800769 pub fn satisfies(&self, user_secure_ids: &[i64], auth_type: HardwareAuthenticatorType) -> bool {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000770 user_secure_ids.iter().any(|&sid| {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800771 (sid == self.auth_token.userId || sid == self.auth_token.authenticatorId)
772 && (((auth_type.0 as i32) & (self.auth_token.authenticatorType.0 as i32)) != 0)
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000773 })
774 }
775
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000776 /// Returns the auth token wrapped by the AuthTokenEntry
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800777 pub fn auth_token(&self) -> &HardwareAuthToken {
778 &self.auth_token
779 }
780
781 /// Returns the auth token wrapped by the AuthTokenEntry
782 pub fn take_auth_token(self) -> HardwareAuthToken {
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000783 self.auth_token
784 }
Janis Danisevskis5ed8c532021-01-11 14:19:42 -0800785
786 /// Returns the time that this auth token was received.
787 pub fn time_received(&self) -> MonotonicRawTime {
788 self.time_received
789 }
Hasini Gunasinghe52333ba2020-11-06 01:24:16 +0000790}
791
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800792/// Shared in-memory databases get destroyed as soon as the last connection to them gets closed.
793/// This object does not allow access to the database connection. But it keeps a database
794/// connection alive in order to keep the in memory per boot database alive.
795pub struct PerBootDbKeepAlive(Connection);
796
Joel Galenson26f4d012020-07-17 14:57:21 -0700797impl KeystoreDB {
Janis Danisevskiseed69842021-02-18 20:04:10 -0800798 const UNASSIGNED_KEY_ID: i64 = -1i64;
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800799 const PERBOOT_DB_FILE_NAME: &'static str = &"file:perboot.sqlite?mode=memory&cache=shared";
800
Hasini Gunasinghe0e161452021-01-27 19:34:37 +0000801 /// The alias of the user super key.
802 pub const USER_SUPER_KEY_ALIAS: &'static str = &"USER_SUPER_KEY";
803
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800804 /// This creates a PerBootDbKeepAlive object to keep the per boot database alive.
805 pub fn keep_perboot_db_alive() -> Result<PerBootDbKeepAlive> {
806 let conn = Connection::open_in_memory()
807 .context("In keep_perboot_db_alive: Failed to initialize SQLite connection.")?;
808
809 conn.execute("ATTACH DATABASE ? as perboot;", params![Self::PERBOOT_DB_FILE_NAME])
810 .context("In keep_perboot_db_alive: Failed to attach database perboot.")?;
811 Ok(PerBootDbKeepAlive(conn))
812 }
813
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700814 /// This will create a new database connection connecting the two
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800815 /// files persistent.sqlite and perboot.sqlite in the given directory.
816 /// It also attempts to initialize all of the tables.
817 /// KeystoreDB cannot be used by multiple threads.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700818 /// Each thread should open their own connection using `thread_local!`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800819 pub fn new(db_root: &Path, gc: Option<Gc>) -> Result<Self> {
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800820 // Build the path to the sqlite file.
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800821 let mut persistent_path = db_root.to_path_buf();
822 persistent_path.push("persistent.sqlite");
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700823
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800824 // Now convert them to strings prefixed with "file:"
825 let mut persistent_path_str = "file:".to_owned();
826 persistent_path_str.push_str(&persistent_path.to_string_lossy());
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800827
Janis Danisevskisb00ebd02021-02-02 21:52:24 -0800828 let conn = Self::make_connection(&persistent_path_str, &Self::PERBOOT_DB_FILE_NAME)?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800829
Janis Danisevskis66784c42021-01-27 08:40:25 -0800830 // On busy fail Immediately. It is unlikely to succeed given a bug in sqlite.
831 conn.busy_handler(None).context("In KeystoreDB::new: Failed to set busy handler.")?;
832
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800833 let mut db = Self { conn, gc };
Janis Danisevskis66784c42021-01-27 08:40:25 -0800834 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800835 Self::init_tables(tx).context("Trying to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -0800836 })?;
837 Ok(db)
Joel Galenson2aab4432020-07-22 15:27:57 -0700838 }
839
Janis Danisevskis66784c42021-01-27 08:40:25 -0800840 fn init_tables(tx: &Transaction) -> Result<()> {
841 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700842 "CREATE TABLE IF NOT EXISTS persistent.keyentry (
Joel Galenson0891bc12020-07-20 10:37:03 -0700843 id INTEGER UNIQUE,
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800844 key_type INTEGER,
Joel Galenson0891bc12020-07-20 10:37:03 -0700845 domain INTEGER,
846 namespace INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800847 alias BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -0800848 state INTEGER,
849 km_uuid BLOB);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700850 NO_PARAMS,
851 )
852 .context("Failed to initialize \"keyentry\" table.")?;
853
Janis Danisevskis66784c42021-01-27 08:40:25 -0800854 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800855 "CREATE INDEX IF NOT EXISTS persistent.keyentry_id_index
856 ON keyentry(id);",
857 NO_PARAMS,
858 )
859 .context("Failed to create index keyentry_id_index.")?;
860
861 tx.execute(
862 "CREATE INDEX IF NOT EXISTS persistent.keyentry_domain_namespace_index
863 ON keyentry(domain, namespace, alias);",
864 NO_PARAMS,
865 )
866 .context("Failed to create index keyentry_domain_namespace_index.")?;
867
868 tx.execute(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700869 "CREATE TABLE IF NOT EXISTS persistent.blobentry (
870 id INTEGER PRIMARY KEY,
871 subcomponent_type INTEGER,
872 keyentryid INTEGER,
Janis Danisevskis93927dd2020-12-23 12:23:08 -0800873 blob BLOB);",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700874 NO_PARAMS,
875 )
876 .context("Failed to initialize \"blobentry\" table.")?;
877
Janis Danisevskis66784c42021-01-27 08:40:25 -0800878 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800879 "CREATE INDEX IF NOT EXISTS persistent.blobentry_keyentryid_index
880 ON blobentry(keyentryid);",
881 NO_PARAMS,
882 )
883 .context("Failed to create index blobentry_keyentryid_index.")?;
884
885 tx.execute(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -0800886 "CREATE TABLE IF NOT EXISTS persistent.blobmetadata (
887 id INTEGER PRIMARY KEY,
888 blobentryid INTEGER,
889 tag INTEGER,
890 data ANY,
891 UNIQUE (blobentryid, tag));",
892 NO_PARAMS,
893 )
894 .context("Failed to initialize \"blobmetadata\" table.")?;
895
896 tx.execute(
897 "CREATE INDEX IF NOT EXISTS persistent.blobmetadata_blobentryid_index
898 ON blobmetadata(blobentryid);",
899 NO_PARAMS,
900 )
901 .context("Failed to create index blobmetadata_blobentryid_index.")?;
902
903 tx.execute(
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700904 "CREATE TABLE IF NOT EXISTS persistent.keyparameter (
Hasini Gunasingheaf993662020-07-24 18:40:20 +0000905 keyentryid INTEGER,
906 tag INTEGER,
907 data ANY,
908 security_level INTEGER);",
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700909 NO_PARAMS,
910 )
911 .context("Failed to initialize \"keyparameter\" table.")?;
912
Janis Danisevskis66784c42021-01-27 08:40:25 -0800913 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800914 "CREATE INDEX IF NOT EXISTS persistent.keyparameter_keyentryid_index
915 ON keyparameter(keyentryid);",
916 NO_PARAMS,
917 )
918 .context("Failed to create index keyparameter_keyentryid_index.")?;
919
920 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800921 "CREATE TABLE IF NOT EXISTS persistent.keymetadata (
922 keyentryid INTEGER,
923 tag INTEGER,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +0000924 data ANY,
925 UNIQUE (keyentryid, tag));",
Janis Danisevskisb42fc182020-12-15 08:41:27 -0800926 NO_PARAMS,
927 )
928 .context("Failed to initialize \"keymetadata\" table.")?;
929
Janis Danisevskis66784c42021-01-27 08:40:25 -0800930 tx.execute(
Janis Danisevskisa5438182021-02-02 14:22:59 -0800931 "CREATE INDEX IF NOT EXISTS persistent.keymetadata_keyentryid_index
932 ON keymetadata(keyentryid);",
933 NO_PARAMS,
934 )
935 .context("Failed to create index keymetadata_keyentryid_index.")?;
936
937 tx.execute(
Janis Danisevskisbf15d732020-12-08 10:35:26 -0800938 "CREATE TABLE IF NOT EXISTS persistent.grant (
Janis Danisevskis63f7bc82020-09-03 10:12:56 -0700939 id INTEGER UNIQUE,
940 grantee INTEGER,
941 keyentryid INTEGER,
942 access_vector INTEGER);",
943 NO_PARAMS,
944 )
945 .context("Failed to initialize \"grant\" table.")?;
946
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000947 //TODO: only drop the following two perboot tables if this is the first start up
948 //during the boot (b/175716626).
Janis Danisevskis66784c42021-01-27 08:40:25 -0800949 // tx.execute("DROP TABLE IF EXISTS perboot.authtoken;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000950 // .context("Failed to drop perboot.authtoken table")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -0800951 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000952 "CREATE TABLE IF NOT EXISTS perboot.authtoken (
953 id INTEGER PRIMARY KEY,
954 challenge INTEGER,
955 user_id INTEGER,
956 auth_id INTEGER,
957 authenticator_type INTEGER,
958 timestamp INTEGER,
959 mac BLOB,
960 time_received INTEGER,
961 UNIQUE(user_id, auth_id, authenticator_type));",
962 NO_PARAMS,
963 )
964 .context("Failed to initialize \"authtoken\" table.")?;
965
Janis Danisevskis66784c42021-01-27 08:40:25 -0800966 // tx.execute("DROP TABLE IF EXISTS perboot.metadata;", NO_PARAMS)
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000967 // .context("Failed to drop perboot.metadata table")?;
968 // metadata table stores certain miscellaneous information required for keystore functioning
969 // during a boot cycle, as key-value pairs.
Janis Danisevskis66784c42021-01-27 08:40:25 -0800970 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +0000971 "CREATE TABLE IF NOT EXISTS perboot.metadata (
972 key TEXT,
973 value BLOB,
974 UNIQUE(key));",
975 NO_PARAMS,
976 )
977 .context("Failed to initialize \"metadata\" table.")?;
Joel Galenson0891bc12020-07-20 10:37:03 -0700978 Ok(())
979 }
980
Janis Danisevskis4df44f42020-08-26 14:40:03 -0700981 fn make_connection(persistent_file: &str, perboot_file: &str) -> Result<Connection> {
982 let conn =
983 Connection::open_in_memory().context("Failed to initialize SQLite connection.")?;
984
Janis Danisevskis66784c42021-01-27 08:40:25 -0800985 loop {
986 if let Err(e) = conn
987 .execute("ATTACH DATABASE ? as persistent;", params![persistent_file])
988 .context("Failed to attach database persistent.")
989 {
990 if Self::is_locked_error(&e) {
991 std::thread::sleep(std::time::Duration::from_micros(500));
992 continue;
993 } else {
994 return Err(e);
995 }
996 }
997 break;
998 }
999 loop {
1000 if let Err(e) = conn
1001 .execute("ATTACH DATABASE ? as perboot;", params![perboot_file])
1002 .context("Failed to attach database perboot.")
1003 {
1004 if Self::is_locked_error(&e) {
1005 std::thread::sleep(std::time::Duration::from_micros(500));
1006 continue;
1007 } else {
1008 return Err(e);
1009 }
1010 }
1011 break;
1012 }
Janis Danisevskis4df44f42020-08-26 14:40:03 -07001013
1014 Ok(conn)
1015 }
1016
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001017 /// This function is intended to be used by the garbage collector.
1018 /// It deletes the blob given by `blob_id_to_delete`. It then tries to find a superseded
1019 /// key blob that might need special handling by the garbage collector.
1020 /// If no further superseded blobs can be found it deletes all other superseded blobs that don't
1021 /// need special handling and returns None.
1022 pub fn handle_next_superseded_blob(
1023 &mut self,
1024 blob_id_to_delete: Option<i64>,
1025 ) -> Result<Option<(i64, Vec<u8>, BlobMetaData)>> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001026 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001027 // Delete the given blob if one was given.
1028 if let Some(blob_id_to_delete) = blob_id_to_delete {
1029 tx.execute(
1030 "DELETE FROM persistent.blobmetadata WHERE blobentryid = ?;",
1031 params![blob_id_to_delete],
1032 )
1033 .context("Trying to delete blob metadata.")?;
1034 tx.execute(
1035 "DELETE FROM persistent.blobentry WHERE id = ?;",
1036 params![blob_id_to_delete],
1037 )
1038 .context("Trying to blob.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001039 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001040
1041 // Find another superseded keyblob load its metadata and return it.
1042 if let Some((blob_id, blob)) = tx
1043 .query_row(
1044 "SELECT id, blob FROM persistent.blobentry
1045 WHERE subcomponent_type = ?
1046 AND (
1047 id NOT IN (
1048 SELECT MAX(id) FROM persistent.blobentry
1049 WHERE subcomponent_type = ?
1050 GROUP BY keyentryid, subcomponent_type
1051 )
1052 OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1053 );",
1054 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1055 |row| Ok((row.get(0)?, row.get(1)?)),
1056 )
1057 .optional()
1058 .context("Trying to query superseded blob.")?
1059 {
1060 let blob_metadata = BlobMetaData::load_from_db(blob_id, tx)
1061 .context("Trying to load blob metadata.")?;
1062 return Ok(Some((blob_id, blob, blob_metadata))).no_gc();
1063 }
1064
1065 // We did not find any superseded key blob, so let's remove other superseded blob in
1066 // one transaction.
1067 tx.execute(
1068 "DELETE FROM persistent.blobentry
1069 WHERE NOT subcomponent_type = ?
1070 AND (
1071 id NOT IN (
1072 SELECT MAX(id) FROM persistent.blobentry
1073 WHERE NOT subcomponent_type = ?
1074 GROUP BY keyentryid, subcomponent_type
1075 ) OR keyentryid NOT IN (SELECT id FROM persistent.keyentry)
1076 );",
1077 params![SubComponentType::KEY_BLOB, SubComponentType::KEY_BLOB],
1078 )
1079 .context("Trying to purge superseded blobs.")?;
1080
1081 Ok(None).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001082 })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001083 .context("In handle_next_superseded_blob.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001084 }
1085
1086 /// This maintenance function should be called only once before the database is used for the
1087 /// first time. It restores the invariant that `KeyLifeCycle::Existing` is a transient state.
1088 /// The function transitions all key entries from Existing to Unreferenced unconditionally and
1089 /// returns the number of rows affected. If this returns a value greater than 0, it means that
1090 /// Keystore crashed at some point during key generation. Callers may want to log such
1091 /// occurrences.
1092 /// Unlike with `mark_unreferenced`, we don't need to purge grants, because only keys that made
1093 /// it to `KeyLifeCycle::Live` may have grants.
1094 pub fn cleanup_leftovers(&mut self) -> Result<usize> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001095 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1096 tx.execute(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001097 "UPDATE persistent.keyentry SET state = ? WHERE state = ?;",
1098 params![KeyLifeCycle::Unreferenced, KeyLifeCycle::Existing],
1099 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08001100 .context("Failed to execute query.")
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001101 .need_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001102 })
1103 .context("In cleanup_leftovers.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001104 }
1105
Hasini Gunasinghe0e161452021-01-27 19:34:37 +00001106 /// Checks if a key exists with given key type and key descriptor properties.
1107 pub fn key_exists(
1108 &mut self,
1109 domain: Domain,
1110 nspace: i64,
1111 alias: &str,
1112 key_type: KeyType,
1113 ) -> Result<bool> {
1114 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1115 let key_descriptor =
1116 KeyDescriptor { domain, nspace, alias: Some(alias.to_string()), blob: None };
1117 let result = Self::load_key_entry_id(&tx, &key_descriptor, key_type);
1118 match result {
1119 Ok(_) => Ok(true),
1120 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1121 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(false),
1122 _ => Err(error).context("In key_exists: Failed to find if the key exists."),
1123 },
1124 }
1125 .no_gc()
1126 })
1127 .context("In key_exists.")
1128 }
1129
Hasini Gunasingheda895552021-01-27 19:34:37 +00001130 /// Stores a super key in the database.
1131 pub fn store_super_key(
1132 &mut self,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001133 user_id: u32,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001134 blob_info: &(&[u8], &BlobMetaData),
1135 ) -> Result<KeyEntry> {
1136 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1137 let key_id = Self::insert_with_retry(|id| {
1138 tx.execute(
1139 "INSERT into persistent.keyentry
1140 (id, key_type, domain, namespace, alias, state, km_uuid)
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001141 VALUES(?, ?, ?, ?, ?, ?, ?);",
Hasini Gunasingheda895552021-01-27 19:34:37 +00001142 params![
1143 id,
1144 KeyType::Super,
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00001145 Domain::APP.0,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001146 user_id as i64,
Hasini Gunasingheda895552021-01-27 19:34:37 +00001147 Self::USER_SUPER_KEY_ALIAS,
1148 KeyLifeCycle::Live,
1149 &KEYSTORE_UUID,
1150 ],
1151 )
1152 })
1153 .context("Failed to insert into keyentry table.")?;
1154
1155 let (blob, blob_metadata) = *blob_info;
1156 Self::set_blob_internal(
1157 &tx,
1158 key_id,
1159 SubComponentType::KEY_BLOB,
1160 Some(blob),
1161 Some(blob_metadata),
1162 )
1163 .context("Failed to store key blob.")?;
1164
1165 Self::load_key_components(tx, KeyEntryLoadBits::KM, key_id)
1166 .context("Trying to load key components.")
1167 .no_gc()
1168 })
1169 .context("In store_super_key.")
1170 }
1171
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001172 /// Loads super key of a given user, if exists
1173 pub fn load_super_key(&mut self, user_id: u32) -> Result<Option<(KeyIdGuard, KeyEntry)>> {
1174 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1175 let key_descriptor = KeyDescriptor {
1176 domain: Domain::APP,
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00001177 nspace: user_id as i64,
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00001178 alias: Some(String::from("USER_SUPER_KEY")),
1179 blob: None,
1180 };
1181 let id = Self::load_key_entry_id(&tx, &key_descriptor, KeyType::Super);
1182 match id {
1183 Ok(id) => {
1184 let key_entry = Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1185 .context("In load_super_key. Failed to load key entry.")?;
1186 Ok(Some((KEY_ID_LOCK.get(id), key_entry)))
1187 }
1188 Err(error) => match error.root_cause().downcast_ref::<KsError>() {
1189 Some(KsError::Rc(ResponseCode::KEY_NOT_FOUND)) => Ok(None),
1190 _ => Err(error).context("In load_super_key."),
1191 },
1192 }
1193 .no_gc()
1194 })
1195 .context("In load_super_key.")
1196 }
1197
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001198 /// Atomically loads a key entry and associated metadata or creates it using the
1199 /// callback create_new_key callback. The callback is called during a database
1200 /// transaction. This means that implementers should be mindful about using
1201 /// blocking operations such as IPC or grabbing mutexes.
1202 pub fn get_or_create_key_with<F>(
1203 &mut self,
1204 domain: Domain,
1205 namespace: i64,
1206 alias: &str,
Max Bires8e93d2b2021-01-14 13:17:59 -08001207 km_uuid: Uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001208 create_new_key: F,
1209 ) -> Result<(KeyIdGuard, KeyEntry)>
1210 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001211 F: Fn() -> Result<(Vec<u8>, BlobMetaData)>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001212 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001213 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1214 let id = {
1215 let mut stmt = tx
1216 .prepare(
1217 "SELECT id FROM persistent.keyentry
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001218 WHERE
1219 key_type = ?
1220 AND domain = ?
1221 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001222 AND alias = ?
1223 AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001224 )
1225 .context("In get_or_create_key_with: Failed to select from keyentry table.")?;
1226 let mut rows = stmt
1227 .query(params![KeyType::Super, domain.0, namespace, alias, KeyLifeCycle::Live])
1228 .context("In get_or_create_key_with: Failed to query from keyentry table.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001229
Janis Danisevskis66784c42021-01-27 08:40:25 -08001230 db_utils::with_rows_extract_one(&mut rows, |row| {
1231 Ok(match row {
1232 Some(r) => r.get(0).context("Failed to unpack id.")?,
1233 None => None,
1234 })
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001235 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001236 .context("In get_or_create_key_with.")?
1237 };
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001238
Janis Danisevskis66784c42021-01-27 08:40:25 -08001239 let (id, entry) = match id {
1240 Some(id) => (
1241 id,
1242 Self::load_key_components(&tx, KeyEntryLoadBits::KM, id)
1243 .context("In get_or_create_key_with.")?,
1244 ),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001245
Janis Danisevskis66784c42021-01-27 08:40:25 -08001246 None => {
1247 let id = Self::insert_with_retry(|id| {
1248 tx.execute(
1249 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001250 (id, key_type, domain, namespace, alias, state, km_uuid)
1251 VALUES(?, ?, ?, ?, ?, ?, ?);",
Janis Danisevskis66784c42021-01-27 08:40:25 -08001252 params![
1253 id,
1254 KeyType::Super,
1255 domain.0,
1256 namespace,
1257 alias,
1258 KeyLifeCycle::Live,
1259 km_uuid,
1260 ],
1261 )
1262 })
1263 .context("In get_or_create_key_with.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001264
Janis Danisevskis66784c42021-01-27 08:40:25 -08001265 let (blob, metadata) =
1266 create_new_key().context("In get_or_create_key_with.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001267 Self::set_blob_internal(
1268 &tx,
1269 id,
1270 SubComponentType::KEY_BLOB,
1271 Some(&blob),
1272 Some(&metadata),
1273 )
1274 .context("In get_of_create_key_with.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08001275 (
Janis Danisevskis377d1002021-01-27 19:07:48 -08001276 id,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001277 KeyEntry {
1278 id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001279 key_blob_info: Some((blob, metadata)),
Janis Danisevskis66784c42021-01-27 08:40:25 -08001280 pure_cert: false,
1281 ..Default::default()
1282 },
1283 )
1284 }
1285 };
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001286 Ok((KEY_ID_LOCK.get(id), entry)).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08001287 })
1288 .context("In get_or_create_key_with.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001289 }
1290
Janis Danisevskis66784c42021-01-27 08:40:25 -08001291 /// SQLite3 seems to hold a shared mutex while running the busy handler when
1292 /// waiting for the database file to become available. This makes it
1293 /// impossible to successfully recover from a locked database when the
1294 /// transaction holding the device busy is in the same process on a
1295 /// different connection. As a result the busy handler has to time out and
1296 /// fail in order to make progress.
1297 ///
1298 /// Instead, we set the busy handler to None (return immediately). And catch
1299 /// Busy and Locked errors (the latter occur on in memory databases with
1300 /// shared cache, e.g., the per-boot database.) and restart the transaction
1301 /// after a grace period of half a millisecond.
1302 ///
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001303 /// Creates a transaction with the given behavior and executes f with the new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001304 /// The transaction is committed only if f returns Ok and retried if DatabaseBusy
1305 /// or DatabaseLocked is encountered.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001306 fn with_transaction<T, F>(&mut self, behavior: TransactionBehavior, f: F) -> Result<T>
1307 where
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001308 F: Fn(&Transaction) -> Result<(bool, T)>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001309 {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001310 loop {
1311 match self
1312 .conn
1313 .transaction_with_behavior(behavior)
1314 .context("In with_transaction.")
1315 .and_then(|tx| f(&tx).map(|result| (result, tx)))
1316 .and_then(|(result, tx)| {
1317 tx.commit().context("In with_transaction: Failed to commit transaction.")?;
1318 Ok(result)
1319 }) {
1320 Ok(result) => break Ok(result),
1321 Err(e) => {
1322 if Self::is_locked_error(&e) {
1323 std::thread::sleep(std::time::Duration::from_micros(500));
1324 continue;
1325 } else {
1326 return Err(e).context("In with_transaction.");
1327 }
1328 }
1329 }
1330 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001331 .map(|(need_gc, result)| {
1332 if need_gc {
1333 if let Some(ref gc) = self.gc {
1334 gc.notify_gc();
1335 }
1336 }
1337 result
1338 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001339 }
1340
1341 fn is_locked_error(e: &anyhow::Error) -> bool {
1342 matches!(e.root_cause().downcast_ref::<rusqlite::ffi::Error>(),
1343 Some(rusqlite::ffi::Error {
1344 code: rusqlite::ErrorCode::DatabaseBusy,
1345 ..
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001346 })
Janis Danisevskis66784c42021-01-27 08:40:25 -08001347 | Some(rusqlite::ffi::Error {
1348 code: rusqlite::ErrorCode::DatabaseLocked,
1349 ..
1350 }))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001351 }
1352
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001353 /// Creates a new key entry and allocates a new randomized id for the new key.
1354 /// The key id gets associated with a domain and namespace but not with an alias.
1355 /// To complete key generation `rebind_alias` should be called after all of the
1356 /// key artifacts, i.e., blobs and parameters have been associated with the new
1357 /// key id. Finalizing with `rebind_alias` makes the creation of a new key entry
1358 /// atomic even if key generation is not.
Max Bires8e93d2b2021-01-14 13:17:59 -08001359 pub fn create_key_entry(
1360 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001361 domain: &Domain,
1362 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001363 km_uuid: &Uuid,
1364 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001365 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001366 Self::create_key_entry_internal(tx, domain, namespace, km_uuid).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001367 })
1368 .context("In create_key_entry.")
1369 }
1370
1371 fn create_key_entry_internal(
1372 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001373 domain: &Domain,
1374 namespace: &i64,
Max Bires8e93d2b2021-01-14 13:17:59 -08001375 km_uuid: &Uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001376 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001377 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001378 Domain::APP | Domain::SELINUX => {}
Joel Galenson0891bc12020-07-20 10:37:03 -07001379 _ => {
1380 return Err(KsError::sys())
1381 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1382 }
1383 }
Janis Danisevskisaec14592020-11-12 09:41:49 -08001384 Ok(KEY_ID_LOCK.get(
1385 Self::insert_with_retry(|id| {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001386 tx.execute(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001387 "INSERT into persistent.keyentry
Max Bires8e93d2b2021-01-14 13:17:59 -08001388 (id, key_type, domain, namespace, alias, state, km_uuid)
1389 VALUES(?, ?, ?, ?, NULL, ?, ?);",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001390 params![
1391 id,
1392 KeyType::Client,
1393 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001394 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001395 KeyLifeCycle::Existing,
1396 km_uuid,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001397 ],
Janis Danisevskisaec14592020-11-12 09:41:49 -08001398 )
1399 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001400 .context("In create_key_entry_internal")?,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001401 ))
Joel Galenson26f4d012020-07-17 14:57:21 -07001402 }
Joel Galenson33c04ad2020-08-03 11:04:38 -07001403
Max Bires2b2e6562020-09-22 11:22:36 -07001404 /// Creates a new attestation key entry and allocates a new randomized id for the new key.
1405 /// The key id gets associated with a domain and namespace later but not with an alias. The
1406 /// alias will be used to denote if a key has been signed as each key can only be bound to one
1407 /// domain and namespace pairing so there is no need to use them as a value for indexing into
1408 /// a key.
1409 pub fn create_attestation_key_entry(
1410 &mut self,
1411 maced_public_key: &[u8],
1412 raw_public_key: &[u8],
1413 private_key: &[u8],
1414 km_uuid: &Uuid,
1415 ) -> Result<()> {
1416 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1417 let key_id = KEY_ID_LOCK.get(
1418 Self::insert_with_retry(|id| {
1419 tx.execute(
1420 "INSERT into persistent.keyentry
1421 (id, key_type, domain, namespace, alias, state, km_uuid)
1422 VALUES(?, ?, NULL, NULL, NULL, ?, ?);",
1423 params![id, KeyType::Attestation, KeyLifeCycle::Live, km_uuid],
1424 )
1425 })
1426 .context("In create_key_entry")?,
1427 );
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001428 Self::set_blob_internal(
1429 &tx,
1430 key_id.0,
1431 SubComponentType::KEY_BLOB,
1432 Some(private_key),
1433 None,
1434 )?;
Max Bires2b2e6562020-09-22 11:22:36 -07001435 let mut metadata = KeyMetaData::new();
1436 metadata.add(KeyMetaEntry::AttestationMacedPublicKey(maced_public_key.to_vec()));
1437 metadata.add(KeyMetaEntry::AttestationRawPubKey(raw_public_key.to_vec()));
1438 metadata.store_in_db(key_id.0, &tx)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001439 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001440 })
1441 .context("In create_attestation_key_entry")
1442 }
1443
Janis Danisevskis377d1002021-01-27 19:07:48 -08001444 /// Set a new blob and associates it with the given key id. Each blob
1445 /// has a sub component type.
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001446 /// Each key can have one of each sub component type associated. If more
1447 /// are added only the most recent can be retrieved, and superseded blobs
Janis Danisevskis377d1002021-01-27 19:07:48 -08001448 /// will get garbage collected.
1449 /// Components SubComponentType::CERT and SubComponentType::CERT_CHAIN can be
1450 /// removed by setting blob to None.
1451 pub fn set_blob(
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001452 &mut self,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001453 key_id: &KeyIdGuard,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001454 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001455 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001456 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001457 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001458 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001459 Self::set_blob_internal(&tx, key_id.0, sc_type, blob, blob_metadata).need_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001460 })
Janis Danisevskis377d1002021-01-27 19:07:48 -08001461 .context("In set_blob.")
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001462 }
1463
Janis Danisevskiseed69842021-02-18 20:04:10 -08001464 /// Why would we insert a deleted blob? This weird function is for the purpose of legacy
1465 /// key migration in the case where we bulk delete all the keys of an app or even a user.
1466 /// We use this to insert key blobs into the database which can then be garbage collected
1467 /// lazily by the key garbage collector.
1468 pub fn set_deleted_blob(&mut self, blob: &[u8], blob_metadata: &BlobMetaData) -> Result<()> {
1469 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1470 Self::set_blob_internal(
1471 &tx,
1472 Self::UNASSIGNED_KEY_ID,
1473 SubComponentType::KEY_BLOB,
1474 Some(blob),
1475 Some(blob_metadata),
1476 )
1477 .need_gc()
1478 })
1479 .context("In set_deleted_blob.")
1480 }
1481
Janis Danisevskis377d1002021-01-27 19:07:48 -08001482 fn set_blob_internal(
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001483 tx: &Transaction,
1484 key_id: i64,
1485 sc_type: SubComponentType,
Janis Danisevskis377d1002021-01-27 19:07:48 -08001486 blob: Option<&[u8]>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001487 blob_metadata: Option<&BlobMetaData>,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001488 ) -> Result<()> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08001489 match (blob, sc_type) {
1490 (Some(blob), _) => {
1491 tx.execute(
1492 "INSERT INTO persistent.blobentry
1493 (subcomponent_type, keyentryid, blob) VALUES (?, ?, ?);",
1494 params![sc_type, key_id, blob],
1495 )
1496 .context("In set_blob_internal: Failed to insert blob.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001497 if let Some(blob_metadata) = blob_metadata {
1498 let blob_id = tx
1499 .query_row("SELECT MAX(id) FROM persistent.blobentry;", NO_PARAMS, |row| {
1500 row.get(0)
1501 })
1502 .context("In set_blob_internal: Failed to get new blob id.")?;
1503 blob_metadata
1504 .store_in_db(blob_id, tx)
1505 .context("In set_blob_internal: Trying to store blob metadata.")?;
1506 }
Janis Danisevskis377d1002021-01-27 19:07:48 -08001507 }
1508 (None, SubComponentType::CERT) | (None, SubComponentType::CERT_CHAIN) => {
1509 tx.execute(
1510 "DELETE FROM persistent.blobentry
1511 WHERE subcomponent_type = ? AND keyentryid = ?;",
1512 params![sc_type, key_id],
1513 )
1514 .context("In set_blob_internal: Failed to delete blob.")?;
1515 }
1516 (None, _) => {
1517 return Err(KsError::sys())
1518 .context("In set_blob_internal: Other blobs cannot be deleted in this way.");
1519 }
1520 }
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001521 Ok(())
1522 }
1523
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001524 /// Inserts a collection of key parameters into the `persistent.keyparameter` table
1525 /// and associates them with the given `key_id`.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001526 #[cfg(test)]
1527 fn insert_keyparameter(&mut self, key_id: &KeyIdGuard, params: &[KeyParameter]) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001528 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001529 Self::insert_keyparameter_internal(tx, key_id, params).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001530 })
1531 .context("In insert_keyparameter.")
1532 }
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001533
Janis Danisevskis66784c42021-01-27 08:40:25 -08001534 fn insert_keyparameter_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001535 tx: &Transaction,
1536 key_id: &KeyIdGuard,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001537 params: &[KeyParameter],
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001538 ) -> Result<()> {
1539 let mut stmt = tx
1540 .prepare(
1541 "INSERT into persistent.keyparameter (keyentryid, tag, data, security_level)
1542 VALUES (?, ?, ?, ?);",
1543 )
1544 .context("In insert_keyparameter_internal: Failed to prepare statement.")?;
1545
Janis Danisevskis66784c42021-01-27 08:40:25 -08001546 for p in params.iter() {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001547 stmt.insert(params![
1548 key_id.0,
1549 p.get_tag().0,
1550 p.key_parameter_value(),
1551 p.security_level().0
1552 ])
1553 .with_context(|| {
1554 format!("In insert_keyparameter_internal: Failed to insert {:?}", p)
1555 })?;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07001556 }
1557 Ok(())
1558 }
1559
Janis Danisevskisb42fc182020-12-15 08:41:27 -08001560 /// Insert a set of key entry specific metadata into the database.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001561 #[cfg(test)]
1562 fn insert_key_metadata(&mut self, key_id: &KeyIdGuard, metadata: &KeyMetaData) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001563 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001564 metadata.store_in_db(key_id.0, &tx).no_gc()
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001565 })
1566 .context("In insert_key_metadata.")
1567 }
1568
Max Bires2b2e6562020-09-22 11:22:36 -07001569 /// Stores a signed certificate chain signed by a remote provisioning server, keyed
1570 /// on the public key.
1571 pub fn store_signed_attestation_certificate_chain(
1572 &mut self,
1573 raw_public_key: &[u8],
Max Biresb2e1d032021-02-08 21:35:05 -08001574 batch_cert: &[u8],
Max Bires2b2e6562020-09-22 11:22:36 -07001575 cert_chain: &[u8],
1576 expiration_date: i64,
1577 km_uuid: &Uuid,
1578 ) -> Result<()> {
1579 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1580 let mut stmt = tx
1581 .prepare(
1582 "SELECT keyentryid
1583 FROM persistent.keymetadata
1584 WHERE tag = ? AND data = ? AND keyentryid IN
1585 (SELECT id
1586 FROM persistent.keyentry
1587 WHERE
1588 alias IS NULL AND
1589 domain IS NULL AND
1590 namespace IS NULL AND
1591 key_type = ? AND
1592 km_uuid = ?);",
1593 )
1594 .context("Failed to store attestation certificate chain.")?;
1595 let mut rows = stmt
1596 .query(params![
1597 KeyMetaData::AttestationRawPubKey,
1598 raw_public_key,
1599 KeyType::Attestation,
1600 km_uuid
1601 ])
1602 .context("Failed to fetch keyid")?;
1603 let key_id = db_utils::with_rows_extract_one(&mut rows, |row| {
1604 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
1605 .get(0)
1606 .context("Failed to unpack id.")
1607 })
1608 .context("Failed to get key_id.")?;
1609 let num_updated = tx
1610 .execute(
1611 "UPDATE persistent.keyentry
1612 SET alias = ?
1613 WHERE id = ?;",
1614 params!["signed", key_id],
1615 )
1616 .context("Failed to update alias.")?;
1617 if num_updated != 1 {
1618 return Err(KsError::sys()).context("Alias not updated for the key.");
1619 }
1620 let mut metadata = KeyMetaData::new();
1621 metadata.add(KeyMetaEntry::AttestationExpirationDate(DateTime::from_millis_epoch(
1622 expiration_date,
1623 )));
1624 metadata.store_in_db(key_id, &tx).context("Failed to insert key metadata.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001625 Self::set_blob_internal(
1626 &tx,
1627 key_id,
1628 SubComponentType::CERT_CHAIN,
1629 Some(cert_chain),
1630 None,
1631 )
1632 .context("Failed to insert cert chain")?;
Max Biresb2e1d032021-02-08 21:35:05 -08001633 Self::set_blob_internal(&tx, key_id, SubComponentType::CERT, Some(batch_cert), None)
1634 .context("Failed to insert cert")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001635 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001636 })
1637 .context("In store_signed_attestation_certificate_chain: ")
1638 }
1639
1640 /// Assigns the next unassigned attestation key to a domain/namespace combo that does not
1641 /// currently have a key assigned to it.
1642 pub fn assign_attestation_key(
1643 &mut self,
1644 domain: Domain,
1645 namespace: i64,
1646 km_uuid: &Uuid,
1647 ) -> Result<()> {
1648 match domain {
1649 Domain::APP | Domain::SELINUX => {}
1650 _ => {
1651 return Err(KsError::sys()).context(format!(
1652 concat!(
1653 "In assign_attestation_key: Domain {:?} ",
1654 "must be either App or SELinux.",
1655 ),
1656 domain
1657 ));
1658 }
1659 }
1660 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1661 let result = tx
1662 .execute(
1663 "UPDATE persistent.keyentry
1664 SET domain=?1, namespace=?2
1665 WHERE
1666 id =
1667 (SELECT MIN(id)
1668 FROM persistent.keyentry
1669 WHERE ALIAS IS NOT NULL
1670 AND domain IS NULL
1671 AND key_type IS ?3
1672 AND state IS ?4
1673 AND km_uuid IS ?5)
1674 AND
1675 (SELECT COUNT(*)
1676 FROM persistent.keyentry
1677 WHERE domain=?1
1678 AND namespace=?2
1679 AND key_type IS ?3
1680 AND state IS ?4
1681 AND km_uuid IS ?5) = 0;",
1682 params![
1683 domain.0 as u32,
1684 namespace,
1685 KeyType::Attestation,
1686 KeyLifeCycle::Live,
1687 km_uuid,
1688 ],
1689 )
1690 .context("Failed to assign attestation key")?;
Max Bires01f8af22021-03-02 23:24:50 -08001691 if result == 0 {
1692 return Err(KsError::Rc(ResponseCode::OUT_OF_KEYS)).context("Out of keys.");
1693 } else if result > 1 {
1694 return Err(KsError::sys())
1695 .context(format!("Expected to update 1 entry, instead updated {}", result));
Max Bires2b2e6562020-09-22 11:22:36 -07001696 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001697 Ok(()).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001698 })
1699 .context("In assign_attestation_key: ")
1700 }
1701
1702 /// Retrieves num_keys number of attestation keys that have not yet been signed by a remote
1703 /// provisioning server, or the maximum number available if there are not num_keys number of
1704 /// entries in the table.
1705 pub fn fetch_unsigned_attestation_keys(
1706 &mut self,
1707 num_keys: i32,
1708 km_uuid: &Uuid,
1709 ) -> Result<Vec<Vec<u8>>> {
1710 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1711 let mut stmt = tx
1712 .prepare(
1713 "SELECT data
1714 FROM persistent.keymetadata
1715 WHERE tag = ? AND keyentryid IN
1716 (SELECT id
1717 FROM persistent.keyentry
1718 WHERE
1719 alias IS NULL AND
1720 domain IS NULL AND
1721 namespace IS NULL AND
1722 key_type = ? AND
1723 km_uuid = ?
1724 LIMIT ?);",
1725 )
1726 .context("Failed to prepare statement")?;
1727 let rows = stmt
1728 .query_map(
1729 params![
1730 KeyMetaData::AttestationMacedPublicKey,
1731 KeyType::Attestation,
1732 km_uuid,
1733 num_keys
1734 ],
1735 |row| Ok(row.get(0)?),
1736 )?
1737 .collect::<rusqlite::Result<Vec<Vec<u8>>>>()
1738 .context("Failed to execute statement")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001739 Ok(rows).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001740 })
1741 .context("In fetch_unsigned_attestation_keys")
1742 }
1743
1744 /// Removes any keys that have expired as of the current time. Returns the number of keys
1745 /// marked unreferenced that are bound to be garbage collected.
1746 pub fn delete_expired_attestation_keys(&mut self) -> Result<i32> {
1747 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1748 let mut stmt = tx
1749 .prepare(
1750 "SELECT keyentryid, data
1751 FROM persistent.keymetadata
1752 WHERE tag = ? AND keyentryid IN
1753 (SELECT id
1754 FROM persistent.keyentry
1755 WHERE key_type = ?);",
1756 )
1757 .context("Failed to prepare query")?;
1758 let key_ids_to_check = stmt
1759 .query_map(
1760 params![KeyMetaData::AttestationExpirationDate, KeyType::Attestation],
1761 |row| Ok((row.get(0)?, row.get(1)?)),
1762 )?
1763 .collect::<rusqlite::Result<Vec<(i64, DateTime)>>>()
1764 .context("Failed to get date metadata")?;
1765 let curr_time = DateTime::from_millis_epoch(
1766 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64,
1767 );
1768 let mut num_deleted = 0;
1769 for id in key_ids_to_check.iter().filter(|kt| kt.1 < curr_time).map(|kt| kt.0) {
1770 if Self::mark_unreferenced(&tx, id)? {
1771 num_deleted += 1;
1772 }
1773 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001774 Ok(num_deleted).do_gc(num_deleted != 0)
Max Bires2b2e6562020-09-22 11:22:36 -07001775 })
1776 .context("In delete_expired_attestation_keys: ")
1777 }
1778
1779 /// Counts the number of keys that will expire by the provided epoch date and the number of
1780 /// keys not currently assigned to a domain.
1781 pub fn get_attestation_pool_status(
1782 &mut self,
1783 date: i64,
1784 km_uuid: &Uuid,
1785 ) -> Result<AttestationPoolStatus> {
1786 self.with_transaction(TransactionBehavior::Immediate, |tx| {
1787 let mut stmt = tx.prepare(
1788 "SELECT data
1789 FROM persistent.keymetadata
1790 WHERE tag = ? AND keyentryid IN
1791 (SELECT id
1792 FROM persistent.keyentry
1793 WHERE alias IS NOT NULL
1794 AND key_type = ?
1795 AND km_uuid = ?
1796 AND state = ?);",
1797 )?;
1798 let times = stmt
1799 .query_map(
1800 params![
1801 KeyMetaData::AttestationExpirationDate,
1802 KeyType::Attestation,
1803 km_uuid,
1804 KeyLifeCycle::Live
1805 ],
1806 |row| Ok(row.get(0)?),
1807 )?
1808 .collect::<rusqlite::Result<Vec<DateTime>>>()
1809 .context("Failed to execute metadata statement")?;
1810 let expiring =
1811 times.iter().filter(|time| time < &&DateTime::from_millis_epoch(date)).count()
1812 as i32;
1813 stmt = tx.prepare(
1814 "SELECT alias, domain
1815 FROM persistent.keyentry
1816 WHERE key_type = ? AND km_uuid = ? AND state = ?;",
1817 )?;
1818 let rows = stmt
1819 .query_map(params![KeyType::Attestation, km_uuid, KeyLifeCycle::Live], |row| {
1820 Ok((row.get(0)?, row.get(1)?))
1821 })?
1822 .collect::<rusqlite::Result<Vec<(Option<String>, Option<u32>)>>>()
1823 .context("Failed to execute keyentry statement")?;
1824 let mut unassigned = 0i32;
1825 let mut attested = 0i32;
1826 let total = rows.len() as i32;
1827 for (alias, domain) in rows {
1828 match (alias, domain) {
1829 (Some(_alias), None) => {
1830 attested += 1;
1831 unassigned += 1;
1832 }
1833 (Some(_alias), Some(_domain)) => {
1834 attested += 1;
1835 }
1836 _ => {}
1837 }
1838 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001839 Ok(AttestationPoolStatus { expiring, unassigned, attested, total }).no_gc()
Max Bires2b2e6562020-09-22 11:22:36 -07001840 })
1841 .context("In get_attestation_pool_status: ")
1842 }
1843
1844 /// Fetches the private key and corresponding certificate chain assigned to a
1845 /// domain/namespace pair. Will either return nothing if the domain/namespace is
1846 /// not assigned, or one CertificateChain.
1847 pub fn retrieve_attestation_key_and_cert_chain(
1848 &mut self,
1849 domain: Domain,
1850 namespace: i64,
1851 km_uuid: &Uuid,
1852 ) -> Result<Option<CertificateChain>> {
1853 match domain {
1854 Domain::APP | Domain::SELINUX => {}
1855 _ => {
1856 return Err(KsError::sys())
1857 .context(format!("Domain {:?} must be either App or SELinux.", domain));
1858 }
1859 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001860 self.with_transaction(TransactionBehavior::Deferred, |tx| {
1861 let mut stmt = tx.prepare(
1862 "SELECT subcomponent_type, blob
Max Bires2b2e6562020-09-22 11:22:36 -07001863 FROM persistent.blobentry
1864 WHERE keyentryid IN
1865 (SELECT id
1866 FROM persistent.keyentry
1867 WHERE key_type = ?
1868 AND domain = ?
1869 AND namespace = ?
1870 AND state = ?
1871 AND km_uuid = ?);",
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001872 )?;
1873 let rows = stmt
1874 .query_map(
1875 params![
1876 KeyType::Attestation,
1877 domain.0 as u32,
1878 namespace,
1879 KeyLifeCycle::Live,
1880 km_uuid
1881 ],
1882 |row| Ok((row.get(0)?, row.get(1)?)),
1883 )?
1884 .collect::<rusqlite::Result<Vec<(SubComponentType, Vec<u8>)>>>()
Max Biresb2e1d032021-02-08 21:35:05 -08001885 .context("query failed.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001886 if rows.is_empty() {
1887 return Ok(None).no_gc();
Max Biresb2e1d032021-02-08 21:35:05 -08001888 } else if rows.len() != 3 {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001889 return Err(KsError::sys()).context(format!(
1890 concat!(
Max Biresb2e1d032021-02-08 21:35:05 -08001891 "Expected to get a single attestation",
1892 "key, cert, and cert chain for a total of 3 entries, but instead got {}."
1893 ),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001894 rows.len()
1895 ));
Max Bires2b2e6562020-09-22 11:22:36 -07001896 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001897 let mut km_blob: Vec<u8> = Vec::new();
1898 let mut cert_chain_blob: Vec<u8> = Vec::new();
Max Biresb2e1d032021-02-08 21:35:05 -08001899 let mut batch_cert_blob: Vec<u8> = Vec::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001900 for row in rows {
1901 let sub_type: SubComponentType = row.0;
1902 match sub_type {
1903 SubComponentType::KEY_BLOB => {
1904 km_blob = row.1;
1905 }
1906 SubComponentType::CERT_CHAIN => {
1907 cert_chain_blob = row.1;
1908 }
Max Biresb2e1d032021-02-08 21:35:05 -08001909 SubComponentType::CERT => {
1910 batch_cert_blob = row.1;
1911 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001912 _ => Err(KsError::sys()).context("Unknown or incorrect subcomponent type.")?,
1913 }
1914 }
1915 Ok(Some(CertificateChain {
1916 private_key: ZVec::try_from(km_blob)?,
Max Biresb2e1d032021-02-08 21:35:05 -08001917 batch_cert: ZVec::try_from(batch_cert_blob)?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001918 cert_chain: ZVec::try_from(cert_chain_blob)?,
1919 }))
1920 .no_gc()
1921 })
Max Biresb2e1d032021-02-08 21:35:05 -08001922 .context("In retrieve_attestation_key_and_cert_chain:")
Max Bires2b2e6562020-09-22 11:22:36 -07001923 }
1924
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001925 /// Updates the alias column of the given key id `newid` with the given alias,
1926 /// and atomically, removes the alias, domain, and namespace from another row
1927 /// with the same alias-domain-namespace tuple if such row exits.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001928 /// Returns Ok(true) if an old key was marked unreferenced as a hint to the garbage
1929 /// collector.
1930 fn rebind_alias(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001931 tx: &Transaction,
Janis Danisevskisaec14592020-11-12 09:41:49 -08001932 newid: &KeyIdGuard,
Joel Galenson33c04ad2020-08-03 11:04:38 -07001933 alias: &str,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001934 domain: &Domain,
1935 namespace: &i64,
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001936 ) -> Result<bool> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08001937 match *domain {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07001938 Domain::APP | Domain::SELINUX => {}
Joel Galenson33c04ad2020-08-03 11:04:38 -07001939 _ => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001940 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001941 "In rebind_alias: Domain {:?} must be either App or SELinux.",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07001942 domain
1943 ));
Joel Galenson33c04ad2020-08-03 11:04:38 -07001944 }
1945 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001946 let updated = tx
1947 .execute(
1948 "UPDATE persistent.keyentry
1949 SET alias = NULL, domain = NULL, namespace = NULL, state = ?
Joel Galenson33c04ad2020-08-03 11:04:38 -07001950 WHERE alias = ? AND domain = ? AND namespace = ?;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001951 params![KeyLifeCycle::Unreferenced, alias, domain.0 as u32, namespace],
1952 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001953 .context("In rebind_alias: Failed to rebind existing entry.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001954 let result = tx
1955 .execute(
1956 "UPDATE persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001957 SET alias = ?, state = ?
1958 WHERE id = ? AND domain = ? AND namespace = ? AND state = ?;",
1959 params![
1960 alias,
1961 KeyLifeCycle::Live,
1962 newid.0,
1963 domain.0 as u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001964 *namespace,
Max Bires8e93d2b2021-01-14 13:17:59 -08001965 KeyLifeCycle::Existing,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001966 ],
Joel Galenson33c04ad2020-08-03 11:04:38 -07001967 )
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001968 .context("In rebind_alias: Failed to set alias.")?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07001969 if result != 1 {
Joel Galenson33c04ad2020-08-03 11:04:38 -07001970 return Err(KsError::sys()).context(format!(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001971 "In rebind_alias: Expected to update a single entry but instead updated {}.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07001972 result
1973 ));
1974 }
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001975 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001976 }
1977
1978 /// Store a new key in a single transaction.
1979 /// The function creates a new key entry, populates the blob, key parameter, and metadata
1980 /// fields, and rebinds the given alias to the new key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08001981 /// The boolean returned is a hint for the garbage collector. If true, a key was replaced,
1982 /// is now unreferenced and needs to be collected.
Janis Danisevskis66784c42021-01-27 08:40:25 -08001983 pub fn store_new_key(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001984 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08001985 key: &KeyDescriptor,
1986 params: &[KeyParameter],
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001987 blob_info: &(&[u8], &BlobMetaData),
Max Bires8e93d2b2021-01-14 13:17:59 -08001988 cert_info: &CertificateInfo,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001989 metadata: &KeyMetaData,
Max Bires8e93d2b2021-01-14 13:17:59 -08001990 km_uuid: &Uuid,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08001991 ) -> Result<KeyIdGuard> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08001992 let (alias, domain, namespace) = match key {
1993 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
1994 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
1995 (alias, key.domain, nspace)
1996 }
1997 _ => {
1998 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
1999 .context("In store_new_key: Need alias and domain must be APP or SELINUX.")
2000 }
2001 };
2002 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002003 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002004 .context("Trying to create new key entry.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002005 let (blob, blob_metadata) = *blob_info;
2006 Self::set_blob_internal(
2007 tx,
2008 key_id.id(),
2009 SubComponentType::KEY_BLOB,
2010 Some(blob),
2011 Some(&blob_metadata),
2012 )
2013 .context("Trying to insert the key blob.")?;
Max Bires8e93d2b2021-01-14 13:17:59 -08002014 if let Some(cert) = &cert_info.cert {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002015 Self::set_blob_internal(tx, key_id.id(), SubComponentType::CERT, Some(&cert), None)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002016 .context("Trying to insert the certificate.")?;
2017 }
Max Bires8e93d2b2021-01-14 13:17:59 -08002018 if let Some(cert_chain) = &cert_info.cert_chain {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002019 Self::set_blob_internal(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002020 tx,
2021 key_id.id(),
2022 SubComponentType::CERT_CHAIN,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002023 Some(&cert_chain),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002024 None,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002025 )
2026 .context("Trying to insert the certificate chain.")?;
2027 }
2028 Self::insert_keyparameter_internal(tx, &key_id, params)
2029 .context("Trying to insert key parameters.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002030 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002031 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002032 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002033 Ok(key_id).do_gc(need_gc)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002034 })
2035 .context("In store_new_key.")
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002036 }
2037
Janis Danisevskis377d1002021-01-27 19:07:48 -08002038 /// Store a new certificate
2039 /// The function creates a new key entry, populates the blob field and metadata, and rebinds
2040 /// the given alias to the new cert.
Max Bires8e93d2b2021-01-14 13:17:59 -08002041 pub fn store_new_certificate(
2042 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002043 key: &KeyDescriptor,
Max Bires8e93d2b2021-01-14 13:17:59 -08002044 cert: &[u8],
2045 km_uuid: &Uuid,
2046 ) -> Result<KeyIdGuard> {
Janis Danisevskis377d1002021-01-27 19:07:48 -08002047 let (alias, domain, namespace) = match key {
2048 KeyDescriptor { alias: Some(alias), domain: Domain::APP, nspace, blob: None }
2049 | KeyDescriptor { alias: Some(alias), domain: Domain::SELINUX, nspace, blob: None } => {
2050 (alias, key.domain, nspace)
2051 }
2052 _ => {
2053 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT)).context(
2054 "In store_new_certificate: Need alias and domain must be APP or SELINUX.",
2055 )
2056 }
2057 };
2058 self.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002059 let key_id = Self::create_key_entry_internal(tx, &domain, namespace, km_uuid)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002060 .context("Trying to create new key entry.")?;
2061
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002062 Self::set_blob_internal(
2063 tx,
2064 key_id.id(),
2065 SubComponentType::CERT_CHAIN,
2066 Some(cert),
2067 None,
2068 )
2069 .context("Trying to insert certificate.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002070
2071 let mut metadata = KeyMetaData::new();
2072 metadata.add(KeyMetaEntry::CreationDate(
2073 DateTime::now().context("Trying to make creation time.")?,
2074 ));
2075
2076 metadata.store_in_db(key_id.id(), tx).context("Trying to insert key metadata.")?;
2077
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002078 let need_gc = Self::rebind_alias(tx, &key_id, &alias, &domain, namespace)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002079 .context("Trying to rebind alias.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002080 Ok(key_id).do_gc(need_gc)
Janis Danisevskis377d1002021-01-27 19:07:48 -08002081 })
2082 .context("In store_new_certificate.")
2083 }
2084
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002085 // Helper function loading the key_id given the key descriptor
2086 // tuple comprising domain, namespace, and alias.
2087 // Requires a valid transaction.
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002088 fn load_key_entry_id(tx: &Transaction, key: &KeyDescriptor, key_type: KeyType) -> Result<i64> {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002089 let alias = key
2090 .alias
2091 .as_ref()
2092 .map_or_else(|| Err(KsError::sys()), Ok)
2093 .context("In load_key_entry_id: Alias must be specified.")?;
2094 let mut stmt = tx
2095 .prepare(
2096 "SELECT id FROM persistent.keyentry
2097 WHERE
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002098 key_type = ?
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002099 AND domain = ?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002100 AND namespace = ?
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002101 AND alias = ?
2102 AND state = ?;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002103 )
2104 .context("In load_key_entry_id: Failed to select from keyentry table.")?;
2105 let mut rows = stmt
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002106 .query(params![key_type, key.domain.0 as u32, key.nspace, alias, KeyLifeCycle::Live])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002107 .context("In load_key_entry_id: Failed to read from keyentry table.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002108 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002109 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002110 .get(0)
2111 .context("Failed to unpack id.")
2112 })
2113 .context("In load_key_entry_id.")
2114 }
2115
2116 /// This helper function completes the access tuple of a key, which is required
2117 /// to perform access control. The strategy depends on the `domain` field in the
2118 /// key descriptor.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002119 /// * Domain::SELINUX: The access tuple is complete and this function only loads
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002120 /// the key_id for further processing.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002121 /// * Domain::APP: Like Domain::SELINUX, but the tuple is completed by `caller_uid`
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002122 /// which serves as the namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002123 /// * Domain::GRANT: The grant table is queried for the `key_id` and the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002124 /// `access_vector`.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002125 /// * Domain::KEY_ID: The keyentry table is queried for the owning `domain` and
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002126 /// `namespace`.
2127 /// In each case the information returned is sufficient to perform the access
2128 /// check and the key id can be used to load further key artifacts.
2129 fn load_access_tuple(
2130 tx: &Transaction,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002131 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002132 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002133 caller_uid: u32,
2134 ) -> Result<(i64, KeyDescriptor, Option<KeyPermSet>)> {
2135 match key.domain {
2136 // Domain App or SELinux. In this case we load the key_id from
2137 // the keyentry database for further loading of key components.
2138 // We already have the full access tuple to perform access control.
2139 // The only distinction is that we use the caller_uid instead
2140 // of the caller supplied namespace if the domain field is
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002141 // Domain::APP.
2142 Domain::APP | Domain::SELINUX => {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002143 let mut access_key = key.clone();
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002144 if access_key.domain == Domain::APP {
2145 access_key.nspace = caller_uid as i64;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002146 }
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002147 let key_id = Self::load_key_entry_id(&tx, &access_key, key_type)
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002148 .with_context(|| format!("With key.domain = {:?}.", access_key.domain))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002149
2150 Ok((key_id, access_key, None))
2151 }
2152
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002153 // Domain::GRANT. In this case we load the key_id and the access_vector
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002154 // from the grant table.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002155 Domain::GRANT => {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002156 let mut stmt = tx
2157 .prepare(
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002158 "SELECT keyentryid, access_vector FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002159 WHERE grantee = ? AND id = ?;",
2160 )
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002161 .context("Domain::GRANT prepare statement failed")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002162 let mut rows = stmt
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002163 .query(params![caller_uid as i64, key.nspace])
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002164 .context("Domain:Grant: query failed.")?;
2165 let (key_id, access_vector): (i64, i32) =
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002166 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002167 let r =
2168 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002169 Ok((
2170 r.get(0).context("Failed to unpack key_id.")?,
2171 r.get(1).context("Failed to unpack access_vector.")?,
2172 ))
2173 })
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002174 .context("Domain::GRANT.")?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002175 Ok((key_id, key.clone(), Some(access_vector.into())))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002176 }
2177
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002178 // Domain::KEY_ID. In this case we load the domain and namespace from the
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002179 // keyentry database because we need them for access control.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002180 Domain::KEY_ID => {
Janis Danisevskis45760022021-01-19 16:34:10 -08002181 let (domain, namespace): (Domain, i64) = {
2182 let mut stmt = tx
2183 .prepare(
2184 "SELECT domain, namespace FROM persistent.keyentry
2185 WHERE
2186 id = ?
2187 AND state = ?;",
2188 )
2189 .context("Domain::KEY_ID: prepare statement failed")?;
2190 let mut rows = stmt
2191 .query(params![key.nspace, KeyLifeCycle::Live])
2192 .context("Domain::KEY_ID: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002193 db_utils::with_rows_extract_one(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002194 let r =
2195 row.map_or_else(|| Err(KsError::Rc(ResponseCode::KEY_NOT_FOUND)), Ok)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002196 Ok((
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002197 Domain(r.get(0).context("Failed to unpack domain.")?),
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002198 r.get(1).context("Failed to unpack namespace.")?,
2199 ))
2200 })
Janis Danisevskis45760022021-01-19 16:34:10 -08002201 .context("Domain::KEY_ID.")?
2202 };
2203
2204 // We may use a key by id after loading it by grant.
2205 // In this case we have to check if the caller has a grant for this particular
2206 // key. We can skip this if we already know that the caller is the owner.
2207 // But we cannot know this if domain is anything but App. E.g. in the case
2208 // of Domain::SELINUX we have to speculatively check for grants because we have to
2209 // consult the SEPolicy before we know if the caller is the owner.
2210 let access_vector: Option<KeyPermSet> =
2211 if domain != Domain::APP || namespace != caller_uid as i64 {
2212 let access_vector: Option<i32> = tx
2213 .query_row(
2214 "SELECT access_vector FROM persistent.grant
2215 WHERE grantee = ? AND keyentryid = ?;",
2216 params![caller_uid as i64, key.nspace],
2217 |row| row.get(0),
2218 )
2219 .optional()
2220 .context("Domain::KEY_ID: query grant failed.")?;
2221 access_vector.map(|p| p.into())
2222 } else {
2223 None
2224 };
2225
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002226 let key_id = key.nspace;
Janis Danisevskis66784c42021-01-27 08:40:25 -08002227 let mut access_key: KeyDescriptor = key.clone();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002228 access_key.domain = domain;
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002229 access_key.nspace = namespace;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002230
Janis Danisevskis45760022021-01-19 16:34:10 -08002231 Ok((key_id, access_key, access_vector))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002232 }
2233 _ => Err(anyhow!(KsError::sys())),
2234 }
2235 }
2236
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002237 fn load_blob_components(
2238 key_id: i64,
2239 load_bits: KeyEntryLoadBits,
2240 tx: &Transaction,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002241 ) -> Result<(bool, Option<(Vec<u8>, BlobMetaData)>, Option<Vec<u8>>, Option<Vec<u8>>)> {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002242 let mut stmt = tx
2243 .prepare(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002244 "SELECT MAX(id), subcomponent_type, blob FROM persistent.blobentry
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002245 WHERE keyentryid = ? GROUP BY subcomponent_type;",
2246 )
2247 .context("In load_blob_components: prepare statement failed.")?;
2248
2249 let mut rows =
2250 stmt.query(params![key_id]).context("In load_blob_components: query failed.")?;
2251
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002252 let mut key_blob: Option<(i64, Vec<u8>)> = None;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002253 let mut cert_blob: Option<Vec<u8>> = None;
2254 let mut cert_chain_blob: Option<Vec<u8>> = None;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002255 let mut has_km_blob: bool = false;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002256 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002257 let sub_type: SubComponentType =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002258 row.get(1).context("Failed to extract subcomponent_type.")?;
Janis Danisevskis377d1002021-01-27 19:07:48 -08002259 has_km_blob = has_km_blob || sub_type == SubComponentType::KEY_BLOB;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002260 match (sub_type, load_bits.load_public(), load_bits.load_km()) {
2261 (SubComponentType::KEY_BLOB, _, true) => {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002262 key_blob = Some((
2263 row.get(0).context("Failed to extract key blob id.")?,
2264 row.get(2).context("Failed to extract key blob.")?,
2265 ));
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002266 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002267 (SubComponentType::CERT, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002268 cert_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002269 Some(row.get(2).context("Failed to extract public certificate blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002270 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002271 (SubComponentType::CERT_CHAIN, true, _) => {
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002272 cert_chain_blob =
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002273 Some(row.get(2).context("Failed to extract certificate chain blob.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002274 }
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002275 (SubComponentType::CERT, _, _)
2276 | (SubComponentType::CERT_CHAIN, _, _)
2277 | (SubComponentType::KEY_BLOB, _, _) => {}
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002278 _ => Err(KsError::sys()).context("Unknown subcomponent type.")?,
2279 }
2280 Ok(())
2281 })
2282 .context("In load_blob_components.")?;
2283
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002284 let blob_info = key_blob.map_or::<Result<_>, _>(Ok(None), |(blob_id, blob)| {
2285 Ok(Some((
2286 blob,
2287 BlobMetaData::load_from_db(blob_id, tx)
2288 .context("In load_blob_components: Trying to load blob_metadata.")?,
2289 )))
2290 })?;
2291
2292 Ok((has_km_blob, blob_info, cert_blob, cert_chain_blob))
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002293 }
2294
2295 fn load_key_parameters(key_id: i64, tx: &Transaction) -> Result<Vec<KeyParameter>> {
2296 let mut stmt = tx
2297 .prepare(
2298 "SELECT tag, data, security_level from persistent.keyparameter
2299 WHERE keyentryid = ?;",
2300 )
2301 .context("In load_key_parameters: prepare statement failed.")?;
2302
2303 let mut parameters: Vec<KeyParameter> = Vec::new();
2304
2305 let mut rows =
2306 stmt.query(params![key_id]).context("In load_key_parameters: query failed.")?;
Janis Danisevskisbf15d732020-12-08 10:35:26 -08002307 db_utils::with_rows_extract_all(&mut rows, |row| {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07002308 let tag = Tag(row.get(0).context("Failed to read tag.")?);
2309 let sec_level = SecurityLevel(row.get(2).context("Failed to read sec_level.")?);
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002310 parameters.push(
2311 KeyParameter::new_from_sql(tag, &SqlField::new(1, &row), sec_level)
2312 .context("Failed to read KeyParameter.")?,
2313 );
2314 Ok(())
2315 })
2316 .context("In load_key_parameters.")?;
2317
2318 Ok(parameters)
2319 }
2320
Qi Wub9433b52020-12-01 14:52:46 +08002321 /// Decrements the usage count of a limited use key. This function first checks whether the
2322 /// usage has been exhausted, if not, decreases the usage count. If the usage count reaches
2323 /// zero, the key also gets marked unreferenced and scheduled for deletion.
2324 /// Returns Ok(true) if the key was marked unreferenced as a hint to the garbage collector.
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002325 pub fn check_and_update_key_usage_count(&mut self, key_id: i64) -> Result<()> {
Qi Wub9433b52020-12-01 14:52:46 +08002326 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2327 let limit: Option<i32> = tx
2328 .query_row(
2329 "SELECT data FROM persistent.keyparameter WHERE keyentryid = ? AND tag = ?;",
2330 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2331 |row| row.get(0),
2332 )
2333 .optional()
2334 .context("Trying to load usage count")?;
2335
2336 let limit = limit
2337 .ok_or(KsError::Km(ErrorCode::INVALID_KEY_BLOB))
2338 .context("The Key no longer exists. Key is exhausted.")?;
2339
2340 tx.execute(
2341 "UPDATE persistent.keyparameter
2342 SET data = data - 1
2343 WHERE keyentryid = ? AND tag = ? AND data > 0;",
2344 params![key_id, Tag::USAGE_COUNT_LIMIT.0],
2345 )
2346 .context("Failed to update key usage count.")?;
2347
2348 match limit {
2349 1 => Self::mark_unreferenced(tx, key_id)
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002350 .map(|need_gc| (need_gc, ()))
Qi Wub9433b52020-12-01 14:52:46 +08002351 .context("Trying to mark limited use key for deletion."),
2352 0 => Err(KsError::Km(ErrorCode::INVALID_KEY_BLOB)).context("Key is exhausted."),
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002353 _ => Ok(()).no_gc(),
Qi Wub9433b52020-12-01 14:52:46 +08002354 }
2355 })
2356 .context("In check_and_update_key_usage_count.")
2357 }
2358
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002359 /// Load a key entry by the given key descriptor.
2360 /// It uses the `check_permission` callback to verify if the access is allowed
2361 /// given the key access tuple read from the database using `load_access_tuple`.
2362 /// With `load_bits` the caller may specify which blobs shall be loaded from
2363 /// the blob database.
2364 pub fn load_key_entry(
2365 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002366 key: &KeyDescriptor,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002367 key_type: KeyType,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002368 load_bits: KeyEntryLoadBits,
2369 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002370 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
2371 ) -> Result<(KeyIdGuard, KeyEntry)> {
2372 loop {
2373 match self.load_key_entry_internal(
2374 key,
2375 key_type,
2376 load_bits,
2377 caller_uid,
2378 &check_permission,
2379 ) {
2380 Ok(result) => break Ok(result),
2381 Err(e) => {
2382 if Self::is_locked_error(&e) {
2383 std::thread::sleep(std::time::Duration::from_micros(500));
2384 continue;
2385 } else {
2386 return Err(e).context("In load_key_entry.");
2387 }
2388 }
2389 }
2390 }
2391 }
2392
2393 fn load_key_entry_internal(
2394 &mut self,
2395 key: &KeyDescriptor,
2396 key_type: KeyType,
2397 load_bits: KeyEntryLoadBits,
2398 caller_uid: u32,
2399 check_permission: &impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002400 ) -> Result<(KeyIdGuard, KeyEntry)> {
2401 // KEY ID LOCK 1/2
2402 // If we got a key descriptor with a key id we can get the lock right away.
2403 // Otherwise we have to defer it until we know the key id.
2404 let key_id_guard = match key.domain {
2405 Domain::KEY_ID => Some(KEY_ID_LOCK.get(key.nspace)),
2406 _ => None,
2407 };
2408
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002409 let tx = self
2410 .conn
Janis Danisevskisaec14592020-11-12 09:41:49 -08002411 .unchecked_transaction()
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002412 .context("In load_key_entry: Failed to initialize transaction.")?;
2413
2414 // Load the key_id and complete the access control tuple.
2415 let (key_id, access_key_descriptor, access_vector) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002416 Self::load_access_tuple(&tx, key, key_type, caller_uid)
2417 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002418
2419 // Perform access control. It is vital that we return here if the permission is denied.
2420 // So do not touch that '?' at the end.
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002421 check_permission(&access_key_descriptor, access_vector).context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002422
Janis Danisevskisaec14592020-11-12 09:41:49 -08002423 // KEY ID LOCK 2/2
2424 // If we did not get a key id lock by now, it was because we got a key descriptor
2425 // without a key id. At this point we got the key id, so we can try and get a lock.
2426 // However, we cannot block here, because we are in the middle of the transaction.
2427 // So first we try to get the lock non blocking. If that fails, we roll back the
2428 // transaction and block until we get the lock. After we successfully got the lock,
2429 // we start a new transaction and load the access tuple again.
2430 //
2431 // We don't need to perform access control again, because we already established
2432 // that the caller had access to the given key. But we need to make sure that the
2433 // key id still exists. So we have to load the key entry by key id this time.
2434 let (key_id_guard, tx) = match key_id_guard {
2435 None => match KEY_ID_LOCK.try_get(key_id) {
2436 None => {
2437 // Roll back the transaction.
2438 tx.rollback().context("In load_key_entry: Failed to roll back transaction.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002439
Janis Danisevskisaec14592020-11-12 09:41:49 -08002440 // Block until we have a key id lock.
2441 let key_id_guard = KEY_ID_LOCK.get(key_id);
2442
2443 // Create a new transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002444 let tx = self
2445 .conn
2446 .unchecked_transaction()
2447 .context("In load_key_entry: Failed to initialize transaction.")?;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002448
2449 Self::load_access_tuple(
2450 &tx,
2451 // This time we have to load the key by the retrieved key id, because the
2452 // alias may have been rebound after we rolled back the transaction.
Janis Danisevskis66784c42021-01-27 08:40:25 -08002453 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08002454 domain: Domain::KEY_ID,
2455 nspace: key_id,
2456 ..Default::default()
2457 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002458 key_type,
Janis Danisevskisaec14592020-11-12 09:41:49 -08002459 caller_uid,
2460 )
2461 .context("In load_key_entry. (deferred key lock)")?;
2462 (key_id_guard, tx)
2463 }
2464 Some(l) => (l, tx),
2465 },
2466 Some(key_id_guard) => (key_id_guard, tx),
2467 };
2468
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002469 let key_entry = Self::load_key_components(&tx, load_bits, key_id_guard.id())
2470 .context("In load_key_entry.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002471
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002472 tx.commit().context("In load_key_entry: Failed to commit transaction.")?;
2473
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002474 Ok((key_id_guard, key_entry))
2475 }
2476
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002477 fn mark_unreferenced(tx: &Transaction, key_id: i64) -> Result<bool> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002478 let updated = tx
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002479 .execute("DELETE FROM persistent.keyentry WHERE id = ?;", params![key_id])
2480 .context("Trying to delete keyentry.")?;
2481 tx.execute("DELETE FROM persistent.keymetadata WHERE keyentryid = ?;", params![key_id])
2482 .context("Trying to delete keymetadata.")?;
2483 tx.execute("DELETE FROM persistent.keyparameter WHERE keyentryid = ?;", params![key_id])
2484 .context("Trying to delete keyparameters.")?;
2485 tx.execute("DELETE FROM persistent.grant WHERE keyentryid = ?;", params![key_id])
2486 .context("Trying to delete grants.")?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002487 Ok(updated != 0)
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002488 }
2489
2490 /// Marks the given key as unreferenced and removes all of the grants to this key.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002491 /// Returns Ok(true) if a key was marked unreferenced as a hint for the garbage collector.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002492 pub fn unbind_key(
2493 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002494 key: &KeyDescriptor,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002495 key_type: KeyType,
2496 caller_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002497 check_permission: impl Fn(&KeyDescriptor, Option<KeyPermSet>) -> Result<()>,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002498 ) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002499 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2500 let (key_id, access_key_descriptor, access_vector) =
2501 Self::load_access_tuple(tx, key, key_type, caller_uid)
2502 .context("Trying to get access tuple.")?;
2503
2504 // Perform access control. It is vital that we return here if the permission is denied.
2505 // So do not touch that '?' at the end.
2506 check_permission(&access_key_descriptor, access_vector)
2507 .context("While checking permission.")?;
2508
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002509 Self::mark_unreferenced(tx, key_id)
2510 .map(|need_gc| (need_gc, ()))
2511 .context("Trying to mark the key unreferenced.")
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002512 })
2513 .context("In unbind_key.")
2514 }
2515
Max Bires8e93d2b2021-01-14 13:17:59 -08002516 fn get_key_km_uuid(tx: &Transaction, key_id: i64) -> Result<Uuid> {
2517 tx.query_row(
2518 "SELECT km_uuid FROM persistent.keyentry WHERE id = ?",
2519 params![key_id],
2520 |row| row.get(0),
2521 )
2522 .context("In get_key_km_uuid.")
2523 }
2524
Janis Danisevskisddd6e752021-02-22 18:46:55 -08002525 /// Delete all artifacts belonging to the namespace given by the domain-namespace tuple.
2526 /// This leaves all of the blob entries orphaned for subsequent garbage collection.
2527 pub fn unbind_keys_for_namespace(&mut self, domain: Domain, namespace: i64) -> Result<()> {
2528 if !(domain == Domain::APP || domain == Domain::SELINUX) {
2529 return Err(KsError::Rc(ResponseCode::INVALID_ARGUMENT))
2530 .context("In unbind_keys_for_namespace.");
2531 }
2532 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2533 tx.execute(
2534 "DELETE FROM persistent.keymetadata
2535 WHERE keyentryid IN (
2536 SELECT id FROM persistent.keyentry
2537 WHERE domain = ? AND namespace = ?
2538 );",
2539 params![domain.0, namespace],
2540 )
2541 .context("Trying to delete keymetadata.")?;
2542 tx.execute(
2543 "DELETE FROM persistent.keyparameter
2544 WHERE keyentryid IN (
2545 SELECT id FROM persistent.keyentry
2546 WHERE domain = ? AND namespace = ?
2547 );",
2548 params![domain.0, namespace],
2549 )
2550 .context("Trying to delete keyparameters.")?;
2551 tx.execute(
2552 "DELETE FROM persistent.grant
2553 WHERE keyentryid IN (
2554 SELECT id FROM persistent.keyentry
2555 WHERE domain = ? AND namespace = ?
2556 );",
2557 params![domain.0, namespace],
2558 )
2559 .context("Trying to delete grants.")?;
2560 tx.execute(
2561 "DELETE FROM persistent.keyentry WHERE domain = ? AND namespace = ?;",
2562 params![domain.0, namespace],
2563 )
2564 .context("Trying to delete keyentry.")?;
2565 Ok(()).need_gc()
2566 })
2567 .context("In unbind_keys_for_namespace")
2568 }
2569
Hasini Gunasingheda895552021-01-27 19:34:37 +00002570 /// Delete the keys created on behalf of the user, denoted by the user id.
2571 /// Delete all the keys unless 'keep_non_super_encrypted_keys' set to true.
2572 /// Returned boolean is to hint the garbage collector to delete the unbound keys.
2573 /// The caller of this function should notify the gc if the returned value is true.
2574 pub fn unbind_keys_for_user(
2575 &mut self,
2576 user_id: u32,
2577 keep_non_super_encrypted_keys: bool,
2578 ) -> Result<()> {
2579 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2580 let mut stmt = tx
2581 .prepare(&format!(
2582 "SELECT id from persistent.keyentry
2583 WHERE (
2584 key_type = ?
2585 AND domain = ?
2586 AND cast ( (namespace/{aid_user_offset}) as int) = ?
2587 AND state = ?
2588 ) OR (
2589 key_type = ?
2590 AND namespace = ?
2591 AND alias = ?
2592 AND state = ?
2593 );",
2594 aid_user_offset = AID_USER_OFFSET
2595 ))
2596 .context(concat!(
2597 "In unbind_keys_for_user. ",
2598 "Failed to prepare the query to find the keys created by apps."
2599 ))?;
2600
2601 let mut rows = stmt
2602 .query(params![
2603 // WHERE client key:
2604 KeyType::Client,
2605 Domain::APP.0 as u32,
2606 user_id,
2607 KeyLifeCycle::Live,
2608 // OR super key:
2609 KeyType::Super,
2610 user_id,
2611 Self::USER_SUPER_KEY_ALIAS,
2612 KeyLifeCycle::Live
2613 ])
2614 .context("In unbind_keys_for_user. Failed to query the keys created by apps.")?;
2615
2616 let mut key_ids: Vec<i64> = Vec::new();
2617 db_utils::with_rows_extract_all(&mut rows, |row| {
2618 key_ids
2619 .push(row.get(0).context("Failed to read key id of a key created by an app.")?);
2620 Ok(())
2621 })
2622 .context("In unbind_keys_for_user.")?;
2623
2624 let mut notify_gc = false;
2625 for key_id in key_ids {
2626 if keep_non_super_encrypted_keys {
2627 // Load metadata and filter out non-super-encrypted keys.
2628 if let (_, Some((_, blob_metadata)), _, _) =
2629 Self::load_blob_components(key_id, KeyEntryLoadBits::KM, tx)
2630 .context("In unbind_keys_for_user: Trying to load blob info.")?
2631 {
2632 if blob_metadata.encrypted_by().is_none() {
2633 continue;
2634 }
2635 }
2636 }
Hasini Gunasinghe3ed5da72021-02-04 15:18:54 +00002637 notify_gc = Self::mark_unreferenced(&tx, key_id)
Hasini Gunasingheda895552021-01-27 19:34:37 +00002638 .context("In unbind_keys_for_user.")?
2639 || notify_gc;
2640 }
2641 Ok(()).do_gc(notify_gc)
2642 })
2643 .context("In unbind_keys_for_user.")
2644 }
2645
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002646 fn load_key_components(
2647 tx: &Transaction,
2648 load_bits: KeyEntryLoadBits,
2649 key_id: i64,
2650 ) -> Result<KeyEntry> {
2651 let metadata = KeyMetaData::load_from_db(key_id, &tx).context("In load_key_components.")?;
2652
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002653 let (has_km_blob, key_blob_info, cert_blob, cert_chain_blob) =
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002654 Self::load_blob_components(key_id, load_bits, &tx)
2655 .context("In load_key_components.")?;
2656
Max Bires8e93d2b2021-01-14 13:17:59 -08002657 let parameters = Self::load_key_parameters(key_id, &tx)
2658 .context("In load_key_components: Trying to load key parameters.")?;
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002659
Max Bires8e93d2b2021-01-14 13:17:59 -08002660 let km_uuid = Self::get_key_km_uuid(&tx, key_id)
2661 .context("In load_key_components: Trying to get KM uuid.")?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002662
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002663 Ok(KeyEntry {
2664 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002665 key_blob_info,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002666 cert: cert_blob,
2667 cert_chain: cert_chain_blob,
Max Bires8e93d2b2021-01-14 13:17:59 -08002668 km_uuid,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002669 parameters,
2670 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08002671 pure_cert: !has_km_blob,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002672 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002673 }
2674
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002675 /// Returns a list of KeyDescriptors in the selected domain/namespace.
2676 /// The key descriptors will have the domain, nspace, and alias field set.
2677 /// Domain must be APP or SELINUX, the caller must make sure of that.
2678 pub fn list(&mut self, domain: Domain, namespace: i64) -> Result<Vec<KeyDescriptor>> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002679 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2680 let mut stmt = tx
2681 .prepare(
2682 "SELECT alias FROM persistent.keyentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08002683 WHERE domain = ? AND namespace = ? AND alias IS NOT NULL AND state = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002684 )
2685 .context("In list: Failed to prepare.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002686
Janis Danisevskis66784c42021-01-27 08:40:25 -08002687 let mut rows = stmt
2688 .query(params![domain.0 as u32, namespace, KeyLifeCycle::Live])
2689 .context("In list: Failed to query.")?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002690
Janis Danisevskis66784c42021-01-27 08:40:25 -08002691 let mut descriptors: Vec<KeyDescriptor> = Vec::new();
2692 db_utils::with_rows_extract_all(&mut rows, |row| {
2693 descriptors.push(KeyDescriptor {
2694 domain,
2695 nspace: namespace,
2696 alias: Some(row.get(0).context("Trying to extract alias.")?),
2697 blob: None,
2698 });
2699 Ok(())
2700 })
2701 .context("In list: Failed to extract rows.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002702 Ok(descriptors).no_gc()
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002703 })
Janis Danisevskise92a5e62020-12-02 12:57:41 -08002704 }
2705
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002706 /// Adds a grant to the grant table.
2707 /// Like `load_key_entry` this function loads the access tuple before
2708 /// it uses the callback for a permission check. Upon success,
2709 /// it inserts the `grantee_uid`, `key_id`, and `access_vector` into the
2710 /// grant table. The new row will have a randomized id, which is used as
2711 /// grant id in the namespace field of the resulting KeyDescriptor.
2712 pub fn grant(
2713 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002714 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002715 caller_uid: u32,
2716 grantee_uid: u32,
2717 access_vector: KeyPermSet,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002718 check_permission: impl Fn(&KeyDescriptor, &KeyPermSet) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002719 ) -> Result<KeyDescriptor> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002720 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2721 // Load the key_id and complete the access control tuple.
2722 // We ignore the access vector here because grants cannot be granted.
2723 // The access vector returned here expresses the permissions the
2724 // grantee has if key.domain == Domain::GRANT. But this vector
2725 // cannot include the grant permission by design, so there is no way the
2726 // subsequent permission check can pass.
2727 // We could check key.domain == Domain::GRANT and fail early.
2728 // But even if we load the access tuple by grant here, the permission
2729 // check denies the attempt to create a grant by grant descriptor.
2730 let (key_id, access_key_descriptor, _) =
2731 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2732 .context("In grant")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002733
Janis Danisevskis66784c42021-01-27 08:40:25 -08002734 // Perform access control. It is vital that we return here if the permission
2735 // was denied. So do not touch that '?' at the end of the line.
2736 // This permission check checks if the caller has the grant permission
2737 // for the given key and in addition to all of the permissions
2738 // expressed in `access_vector`.
2739 check_permission(&access_key_descriptor, &access_vector)
2740 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002741
Janis Danisevskis66784c42021-01-27 08:40:25 -08002742 let grant_id = if let Some(grant_id) = tx
2743 .query_row(
2744 "SELECT id FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002745 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002746 params![key_id, grantee_uid],
2747 |row| row.get(0),
2748 )
2749 .optional()
2750 .context("In grant: Failed get optional existing grant id.")?
2751 {
2752 tx.execute(
2753 "UPDATE persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002754 SET access_vector = ?
2755 WHERE id = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002756 params![i32::from(access_vector), grant_id],
Joel Galenson845f74b2020-09-09 14:11:55 -07002757 )
Janis Danisevskis66784c42021-01-27 08:40:25 -08002758 .context("In grant: Failed to update existing grant.")?;
2759 grant_id
2760 } else {
2761 Self::insert_with_retry(|id| {
2762 tx.execute(
2763 "INSERT INTO persistent.grant (id, grantee, keyentryid, access_vector)
2764 VALUES (?, ?, ?, ?);",
2765 params![id, grantee_uid, key_id, i32::from(access_vector)],
2766 )
2767 })
2768 .context("In grant")?
2769 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002770
Janis Danisevskis66784c42021-01-27 08:40:25 -08002771 Ok(KeyDescriptor { domain: Domain::GRANT, nspace: grant_id, alias: None, blob: None })
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002772 .no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002773 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002774 }
2775
2776 /// This function checks permissions like `grant` and `load_key_entry`
2777 /// before removing a grant from the grant table.
2778 pub fn ungrant(
2779 &mut self,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002780 key: &KeyDescriptor,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002781 caller_uid: u32,
2782 grantee_uid: u32,
Janis Danisevskis66784c42021-01-27 08:40:25 -08002783 check_permission: impl Fn(&KeyDescriptor) -> Result<()>,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002784 ) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002785 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2786 // Load the key_id and complete the access control tuple.
2787 // We ignore the access vector here because grants cannot be granted.
2788 let (key_id, access_key_descriptor, _) =
2789 Self::load_access_tuple(&tx, key, KeyType::Client, caller_uid)
2790 .context("In ungrant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002791
Janis Danisevskis66784c42021-01-27 08:40:25 -08002792 // Perform access control. We must return here if the permission
2793 // was denied. So do not touch the '?' at the end of this line.
2794 check_permission(&access_key_descriptor)
2795 .context("In grant: check_permission failed.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002796
Janis Danisevskis66784c42021-01-27 08:40:25 -08002797 tx.execute(
2798 "DELETE FROM persistent.grant
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002799 WHERE keyentryid = ? AND grantee = ?;",
Janis Danisevskis66784c42021-01-27 08:40:25 -08002800 params![key_id, grantee_uid],
2801 )
2802 .context("Failed to delete grant.")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002803
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002804 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002805 })
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002806 }
2807
Joel Galenson845f74b2020-09-09 14:11:55 -07002808 // Generates a random id and passes it to the given function, which will
2809 // try to insert it into a database. If that insertion fails, retry;
2810 // otherwise return the id.
2811 fn insert_with_retry(inserter: impl Fn(i64) -> rusqlite::Result<usize>) -> Result<i64> {
2812 loop {
Janis Danisevskiseed69842021-02-18 20:04:10 -08002813 let newid: i64 = match random() {
2814 Self::UNASSIGNED_KEY_ID => continue, // UNASSIGNED_KEY_ID cannot be assigned.
2815 i => i,
2816 };
Joel Galenson845f74b2020-09-09 14:11:55 -07002817 match inserter(newid) {
2818 // If the id already existed, try again.
2819 Err(rusqlite::Error::SqliteFailure(
2820 libsqlite3_sys::Error {
2821 code: libsqlite3_sys::ErrorCode::ConstraintViolation,
2822 extended_code: libsqlite3_sys::SQLITE_CONSTRAINT_UNIQUE,
2823 },
2824 _,
2825 )) => (),
2826 Err(e) => {
2827 return Err(e).context("In insert_with_retry: failed to insert into database.")
2828 }
2829 _ => return Ok(newid),
2830 }
2831 }
2832 }
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002833
2834 /// Insert or replace the auth token based on the UNIQUE constraint of the auth token table
2835 pub fn insert_auth_token(&mut self, auth_token: &HardwareAuthToken) -> Result<()> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08002836 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2837 tx.execute(
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002838 "INSERT OR REPLACE INTO perboot.authtoken (challenge, user_id, auth_id,
2839 authenticator_type, timestamp, mac, time_received) VALUES(?, ?, ?, ?, ?, ?, ?);",
2840 params![
2841 auth_token.challenge,
2842 auth_token.userId,
2843 auth_token.authenticatorId,
2844 auth_token.authenticatorType.0 as i32,
2845 auth_token.timestamp.milliSeconds as i64,
2846 auth_token.mac,
2847 MonotonicRawTime::now(),
2848 ],
2849 )
2850 .context("In insert_auth_token: failed to insert auth token into the database")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002851 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002852 })
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002853 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002854
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002855 /// Find the newest auth token matching the given predicate.
2856 pub fn find_auth_token_entry<F>(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002857 &mut self,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002858 p: F,
2859 ) -> Result<Option<(AuthTokenEntry, MonotonicRawTime)>>
2860 where
2861 F: Fn(&AuthTokenEntry) -> bool,
2862 {
2863 self.with_transaction(TransactionBehavior::Deferred, |tx| {
2864 let mut stmt = tx
2865 .prepare("SELECT * from perboot.authtoken ORDER BY time_received DESC;")
2866 .context("Prepare statement failed.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002867
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002868 let mut rows = stmt.query(NO_PARAMS).context("Failed to query.")?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002869
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002870 while let Some(row) = rows.next().context("Failed to get next row.")? {
2871 let entry = AuthTokenEntry::new(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002872 HardwareAuthToken {
2873 challenge: row.get(1)?,
2874 userId: row.get(2)?,
2875 authenticatorId: row.get(3)?,
2876 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
2877 timestamp: Timestamp { milliSeconds: row.get(5)? },
2878 mac: row.get(6)?,
2879 },
2880 row.get(7)?,
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002881 );
2882 if p(&entry) {
2883 return Ok(Some((
2884 entry,
2885 Self::get_last_off_body(tx)
2886 .context("In find_auth_token_entry: Trying to get last off body")?,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002887 )))
2888 .no_gc();
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002889 }
2890 }
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002891 Ok(None).no_gc()
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002892 })
2893 .context("In find_auth_token_entry.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002894 }
2895
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002896 /// Insert last_off_body into the metadata table at the initialization of auth token table
Janis Danisevskis66784c42021-01-27 08:40:25 -08002897 pub fn insert_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2898 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2899 tx.execute(
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002900 "INSERT OR REPLACE INTO perboot.metadata (key, value) VALUES (?, ?);",
2901 params!["last_off_body", last_off_body],
2902 )
2903 .context("In insert_last_off_body: failed to insert.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002904 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002905 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002906 }
2907
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002908 /// Update last_off_body when on_device_off_body is called
Janis Danisevskis66784c42021-01-27 08:40:25 -08002909 pub fn update_last_off_body(&mut self, last_off_body: MonotonicRawTime) -> Result<()> {
2910 self.with_transaction(TransactionBehavior::Immediate, |tx| {
2911 tx.execute(
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002912 "UPDATE perboot.metadata SET value = ? WHERE key = ?;",
2913 params![last_off_body, "last_off_body"],
2914 )
2915 .context("In update_last_off_body: failed to update.")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002916 Ok(()).no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002917 })
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002918 }
2919
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002920 /// Get last_off_body time when finding auth tokens
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002921 fn get_last_off_body(tx: &Transaction) -> Result<MonotonicRawTime> {
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08002922 tx.query_row(
2923 "SELECT value from perboot.metadata WHERE key = ?;",
2924 params!["last_off_body"],
2925 |row| Ok(row.get(0)?),
2926 )
2927 .context("In get_last_off_body: query_row failed.")
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002928 }
Joel Galenson26f4d012020-07-17 14:57:21 -07002929}
2930
2931#[cfg(test)]
2932mod tests {
2933
2934 use super::*;
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07002935 use crate::key_parameter::{
2936 Algorithm, BlockMode, Digest, EcCurve, HardwareAuthenticatorType, KeyOrigin, KeyParameter,
2937 KeyParameterValue, KeyPurpose, PaddingMode, SecurityLevel,
2938 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002939 use crate::key_perm_set;
2940 use crate::permission::{KeyPerm, KeyPermSet};
Hasini Gunasingheda895552021-01-27 19:34:37 +00002941 use crate::super_key::SuperKeyManager;
Janis Danisevskis2a8330a2021-01-20 15:34:26 -08002942 use keystore2_test_utils::TempDir;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002943 use android_hardware_security_keymint::aidl::android::hardware::security::keymint::{
2944 HardwareAuthToken::HardwareAuthToken,
2945 HardwareAuthenticatorType::HardwareAuthenticatorType as kmhw_authenticator_type,
Janis Danisevskisc3a496b2021-01-05 10:37:22 -08002946 };
2947 use android_hardware_security_secureclock::aidl::android::hardware::security::secureclock::{
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00002948 Timestamp::Timestamp,
2949 };
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07002950 use rusqlite::NO_PARAMS;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002951 use rusqlite::{Error, TransactionBehavior};
Joel Galenson0891bc12020-07-20 10:37:03 -07002952 use std::cell::RefCell;
Janis Danisevskisaec14592020-11-12 09:41:49 -08002953 use std::sync::atomic::{AtomicU8, Ordering};
2954 use std::sync::Arc;
2955 use std::thread;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00002956 use std::time::{Duration, SystemTime};
Janis Danisevskis66784c42021-01-27 08:40:25 -08002957 #[cfg(disabled)]
2958 use std::time::Instant;
Joel Galenson0891bc12020-07-20 10:37:03 -07002959
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002960 fn new_test_db() -> Result<KeystoreDB> {
2961 let conn = KeystoreDB::make_connection("file::memory:", "file::memory:")?;
2962
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002963 let mut db = KeystoreDB { conn, gc: None };
Janis Danisevskis66784c42021-01-27 08:40:25 -08002964 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002965 KeystoreDB::init_tables(tx).context("Failed to initialize tables.").no_gc()
Janis Danisevskis66784c42021-01-27 08:40:25 -08002966 })?;
2967 Ok(db)
Janis Danisevskis4df44f42020-08-26 14:40:03 -07002968 }
2969
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002970 fn new_test_db_with_gc<F>(path: &Path, cb: F) -> Result<KeystoreDB>
2971 where
2972 F: Fn(&Uuid, &[u8]) -> Result<()> + Send + 'static,
2973 {
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002974 let super_key = Arc::new(SuperKeyManager::new());
2975
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002976 let gc_db = KeystoreDB::new(path, None).expect("Failed to open test gc db_connection.");
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00002977 let gc = Gc::new_init_with(Default::default(), move || (Box::new(cb), gc_db, super_key));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002978
2979 KeystoreDB::new(path, Some(gc))
2980 }
2981
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002982 fn rebind_alias(
2983 db: &mut KeystoreDB,
2984 newid: &KeyIdGuard,
2985 alias: &str,
2986 domain: Domain,
2987 namespace: i64,
2988 ) -> Result<bool> {
2989 db.with_transaction(TransactionBehavior::Immediate, |tx| {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08002990 KeystoreDB::rebind_alias(tx, newid, alias, &domain, &namespace).no_gc()
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08002991 })
2992 .context("In rebind_alias.")
2993 }
2994
Janis Danisevskisb42fc182020-12-15 08:41:27 -08002995 #[test]
2996 fn datetime() -> Result<()> {
2997 let conn = Connection::open_in_memory()?;
2998 conn.execute("CREATE TABLE test (ts DATETIME);", NO_PARAMS)?;
2999 let now = SystemTime::now();
3000 let duration = Duration::from_secs(1000);
3001 let then = now.checked_sub(duration).unwrap();
3002 let soon = now.checked_add(duration).unwrap();
3003 conn.execute(
3004 "INSERT INTO test (ts) VALUES (?), (?), (?);",
3005 params![DateTime::try_from(now)?, DateTime::try_from(then)?, DateTime::try_from(soon)?],
3006 )?;
3007 let mut stmt = conn.prepare("SELECT ts FROM test ORDER BY ts ASC;")?;
3008 let mut rows = stmt.query(NO_PARAMS)?;
3009 assert_eq!(DateTime::try_from(then)?, rows.next()?.unwrap().get(0)?);
3010 assert_eq!(DateTime::try_from(now)?, rows.next()?.unwrap().get(0)?);
3011 assert_eq!(DateTime::try_from(soon)?, rows.next()?.unwrap().get(0)?);
3012 assert!(rows.next()?.is_none());
3013 assert!(DateTime::try_from(then)? < DateTime::try_from(now)?);
3014 assert!(DateTime::try_from(then)? < DateTime::try_from(soon)?);
3015 assert!(DateTime::try_from(now)? < DateTime::try_from(soon)?);
3016 Ok(())
3017 }
3018
Joel Galenson0891bc12020-07-20 10:37:03 -07003019 // Ensure that we're using the "injected" random function, not the real one.
3020 #[test]
3021 fn test_mocked_random() {
3022 let rand1 = random();
3023 let rand2 = random();
3024 let rand3 = random();
3025 if rand1 == rand2 {
3026 assert_eq!(rand2 + 1, rand3);
3027 } else {
3028 assert_eq!(rand1 + 1, rand2);
3029 assert_eq!(rand2, rand3);
3030 }
3031 }
Joel Galenson26f4d012020-07-17 14:57:21 -07003032
Joel Galenson26f4d012020-07-17 14:57:21 -07003033 // Test that we have the correct tables.
3034 #[test]
3035 fn test_tables() -> Result<()> {
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003036 let db = new_test_db()?;
Joel Galenson26f4d012020-07-17 14:57:21 -07003037 let tables = db
3038 .conn
Joel Galenson2aab4432020-07-22 15:27:57 -07003039 .prepare("SELECT name from persistent.sqlite_master WHERE type='table' ORDER BY name;")?
Joel Galenson26f4d012020-07-17 14:57:21 -07003040 .query_map(params![], |row| row.get(0))?
3041 .collect::<rusqlite::Result<Vec<String>>>()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003042 assert_eq!(tables.len(), 6);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003043 assert_eq!(tables[0], "blobentry");
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003044 assert_eq!(tables[1], "blobmetadata");
3045 assert_eq!(tables[2], "grant");
3046 assert_eq!(tables[3], "keyentry");
3047 assert_eq!(tables[4], "keymetadata");
3048 assert_eq!(tables[5], "keyparameter");
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003049 let tables = db
3050 .conn
3051 .prepare("SELECT name from perboot.sqlite_master WHERE type='table' ORDER BY name;")?
3052 .query_map(params![], |row| row.get(0))?
3053 .collect::<rusqlite::Result<Vec<String>>>()?;
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003054
3055 assert_eq!(tables.len(), 2);
3056 assert_eq!(tables[0], "authtoken");
3057 assert_eq!(tables[1], "metadata");
Joel Galenson2aab4432020-07-22 15:27:57 -07003058 Ok(())
3059 }
3060
3061 #[test]
Hasini Gunasinghe557b1032020-11-10 01:35:30 +00003062 fn test_auth_token_table_invariant() -> Result<()> {
3063 let mut db = new_test_db()?;
3064 let auth_token1 = HardwareAuthToken {
3065 challenge: i64::MAX,
3066 userId: 200,
3067 authenticatorId: 200,
3068 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3069 timestamp: Timestamp { milliSeconds: 500 },
3070 mac: String::from("mac").into_bytes(),
3071 };
3072 db.insert_auth_token(&auth_token1)?;
3073 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3074 assert_eq!(auth_tokens_returned.len(), 1);
3075
3076 // insert another auth token with the same values for the columns in the UNIQUE constraint
3077 // of the auth token table and different value for timestamp
3078 let auth_token2 = HardwareAuthToken {
3079 challenge: i64::MAX,
3080 userId: 200,
3081 authenticatorId: 200,
3082 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3083 timestamp: Timestamp { milliSeconds: 600 },
3084 mac: String::from("mac").into_bytes(),
3085 };
3086
3087 db.insert_auth_token(&auth_token2)?;
3088 let mut auth_tokens_returned = get_auth_tokens(&mut db)?;
3089 assert_eq!(auth_tokens_returned.len(), 1);
3090
3091 if let Some(auth_token) = auth_tokens_returned.pop() {
3092 assert_eq!(auth_token.auth_token.timestamp.milliSeconds, 600);
3093 }
3094
3095 // insert another auth token with the different values for the columns in the UNIQUE
3096 // constraint of the auth token table
3097 let auth_token3 = HardwareAuthToken {
3098 challenge: i64::MAX,
3099 userId: 201,
3100 authenticatorId: 200,
3101 authenticatorType: kmhw_authenticator_type(kmhw_authenticator_type::PASSWORD.0),
3102 timestamp: Timestamp { milliSeconds: 600 },
3103 mac: String::from("mac").into_bytes(),
3104 };
3105
3106 db.insert_auth_token(&auth_token3)?;
3107 let auth_tokens_returned = get_auth_tokens(&mut db)?;
3108 assert_eq!(auth_tokens_returned.len(), 2);
3109
3110 Ok(())
3111 }
3112
3113 // utility function for test_auth_token_table_invariant()
3114 fn get_auth_tokens(db: &mut KeystoreDB) -> Result<Vec<AuthTokenEntry>> {
3115 let mut stmt = db.conn.prepare("SELECT * from perboot.authtoken;")?;
3116
3117 let auth_token_entries: Vec<AuthTokenEntry> = stmt
3118 .query_map(NO_PARAMS, |row| {
3119 Ok(AuthTokenEntry::new(
3120 HardwareAuthToken {
3121 challenge: row.get(1)?,
3122 userId: row.get(2)?,
3123 authenticatorId: row.get(3)?,
3124 authenticatorType: HardwareAuthenticatorType(row.get(4)?),
3125 timestamp: Timestamp { milliSeconds: row.get(5)? },
3126 mac: row.get(6)?,
3127 },
3128 row.get(7)?,
3129 ))
3130 })?
3131 .collect::<Result<Vec<AuthTokenEntry>, Error>>()?;
3132 Ok(auth_token_entries)
3133 }
3134
3135 #[test]
Joel Galenson2aab4432020-07-22 15:27:57 -07003136 fn test_persistence_for_files() -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003137 let temp_dir = TempDir::new("persistent_db_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003138 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003139
Janis Danisevskis66784c42021-01-27 08:40:25 -08003140 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003141 let entries = get_keyentry(&db)?;
3142 assert_eq!(entries.len(), 1);
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003143
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003144 let db = KeystoreDB::new(temp_dir.path(), None)?;
Joel Galenson2aab4432020-07-22 15:27:57 -07003145
3146 let entries_new = get_keyentry(&db)?;
3147 assert_eq!(entries, entries_new);
3148 Ok(())
3149 }
3150
3151 #[test]
Joel Galenson0891bc12020-07-20 10:37:03 -07003152 fn test_create_key_entry() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003153 fn extractor(ke: &KeyEntryRow) -> (Domain, i64, Option<&str>, Uuid) {
3154 (ke.domain.unwrap(), ke.namespace.unwrap(), ke.alias.as_deref(), ke.km_uuid.unwrap())
Joel Galenson0891bc12020-07-20 10:37:03 -07003155 }
3156
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003157 let mut db = new_test_db()?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003158
Janis Danisevskis66784c42021-01-27 08:40:25 -08003159 db.create_key_entry(&Domain::APP, &100, &KEYSTORE_UUID)?;
3160 db.create_key_entry(&Domain::SELINUX, &101, &KEYSTORE_UUID)?;
Joel Galenson0891bc12020-07-20 10:37:03 -07003161
3162 let entries = get_keyentry(&db)?;
3163 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003164 assert_eq!(extractor(&entries[0]), (Domain::APP, 100, None, KEYSTORE_UUID));
3165 assert_eq!(extractor(&entries[1]), (Domain::SELINUX, 101, None, KEYSTORE_UUID));
Joel Galenson0891bc12020-07-20 10:37:03 -07003166
3167 // Test that we must pass in a valid Domain.
3168 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003169 db.create_key_entry(&Domain::GRANT, &102, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003170 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003171 );
3172 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003173 db.create_key_entry(&Domain::BLOB, &103, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003174 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003175 );
3176 check_result_is_error_containing_string(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003177 db.create_key_entry(&Domain::KEY_ID, &104, &KEYSTORE_UUID),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003178 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson0891bc12020-07-20 10:37:03 -07003179 );
3180
3181 Ok(())
3182 }
3183
Joel Galenson33c04ad2020-08-03 11:04:38 -07003184 #[test]
Max Bires2b2e6562020-09-22 11:22:36 -07003185 fn test_add_unsigned_key() -> Result<()> {
3186 let mut db = new_test_db()?;
3187 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3188 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3189 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3190 db.create_attestation_key_entry(
3191 &public_key,
3192 &raw_public_key,
3193 &private_key,
3194 &KEYSTORE_UUID,
3195 )?;
3196 let keys = db.fetch_unsigned_attestation_keys(5, &KEYSTORE_UUID)?;
3197 assert_eq!(keys.len(), 1);
3198 assert_eq!(keys[0], public_key);
3199 Ok(())
3200 }
3201
3202 #[test]
3203 fn test_store_signed_attestation_certificate_chain() -> Result<()> {
3204 let mut db = new_test_db()?;
3205 let expiration_date: i64 = 20;
3206 let namespace: i64 = 30;
3207 let base_byte: u8 = 1;
3208 let loaded_values =
3209 load_attestation_key_pool(&mut db, expiration_date, namespace, base_byte)?;
3210 let chain =
3211 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
3212 assert_eq!(true, chain.is_some());
3213 let cert_chain = chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003214 assert_eq!(cert_chain.private_key.to_vec(), loaded_values.priv_key);
3215 assert_eq!(cert_chain.batch_cert.to_vec(), loaded_values.batch_cert);
3216 assert_eq!(cert_chain.cert_chain.to_vec(), loaded_values.cert_chain);
Max Bires2b2e6562020-09-22 11:22:36 -07003217 Ok(())
3218 }
3219
3220 #[test]
3221 fn test_get_attestation_pool_status() -> Result<()> {
3222 let mut db = new_test_db()?;
3223 let namespace: i64 = 30;
3224 load_attestation_key_pool(
3225 &mut db, 10, /* expiration */
3226 namespace, 0x01, /* base_byte */
3227 )?;
3228 load_attestation_key_pool(&mut db, 20 /* expiration */, namespace + 1, 0x02)?;
3229 load_attestation_key_pool(&mut db, 40 /* expiration */, namespace + 2, 0x03)?;
3230 let mut status = db.get_attestation_pool_status(9 /* expiration */, &KEYSTORE_UUID)?;
3231 assert_eq!(status.expiring, 0);
3232 assert_eq!(status.attested, 3);
3233 assert_eq!(status.unassigned, 0);
3234 assert_eq!(status.total, 3);
3235 assert_eq!(
3236 db.get_attestation_pool_status(15 /* expiration */, &KEYSTORE_UUID)?.expiring,
3237 1
3238 );
3239 assert_eq!(
3240 db.get_attestation_pool_status(25 /* expiration */, &KEYSTORE_UUID)?.expiring,
3241 2
3242 );
3243 assert_eq!(
3244 db.get_attestation_pool_status(60 /* expiration */, &KEYSTORE_UUID)?.expiring,
3245 3
3246 );
3247 let public_key: Vec<u8> = vec![0x01, 0x02, 0x03];
3248 let private_key: Vec<u8> = vec![0x04, 0x05, 0x06];
3249 let raw_public_key: Vec<u8> = vec![0x07, 0x08, 0x09];
3250 let cert_chain: Vec<u8> = vec![0x0a, 0x0b, 0x0c];
Max Biresb2e1d032021-02-08 21:35:05 -08003251 let batch_cert: Vec<u8> = vec![0x0d, 0x0e, 0x0f];
Max Bires2b2e6562020-09-22 11:22:36 -07003252 db.create_attestation_key_entry(
3253 &public_key,
3254 &raw_public_key,
3255 &private_key,
3256 &KEYSTORE_UUID,
3257 )?;
3258 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3259 assert_eq!(status.attested, 3);
3260 assert_eq!(status.unassigned, 0);
3261 assert_eq!(status.total, 4);
3262 db.store_signed_attestation_certificate_chain(
3263 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08003264 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07003265 &cert_chain,
3266 20,
3267 &KEYSTORE_UUID,
3268 )?;
3269 status = db.get_attestation_pool_status(0 /* expiration */, &KEYSTORE_UUID)?;
3270 assert_eq!(status.attested, 4);
3271 assert_eq!(status.unassigned, 1);
3272 assert_eq!(status.total, 4);
3273 Ok(())
3274 }
3275
3276 #[test]
3277 fn test_remove_expired_certs() -> Result<()> {
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003278 let temp_dir =
3279 TempDir::new("test_remove_expired_certs_").expect("Failed to create temp dir.");
3280 let mut db = new_test_db_with_gc(temp_dir.path(), |_, _| Ok(()))?;
Max Bires2b2e6562020-09-22 11:22:36 -07003281 let expiration_date: i64 =
3282 SystemTime::now().duration_since(SystemTime::UNIX_EPOCH)?.as_millis() as i64 + 10000;
3283 let namespace: i64 = 30;
3284 let namespace_del1: i64 = 45;
3285 let namespace_del2: i64 = 60;
3286 let entry_values = load_attestation_key_pool(
3287 &mut db,
3288 expiration_date,
3289 namespace,
3290 0x01, /* base_byte */
3291 )?;
3292 load_attestation_key_pool(&mut db, 45, namespace_del1, 0x02)?;
3293 load_attestation_key_pool(&mut db, 60, namespace_del2, 0x03)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003294
3295 let blob_entry_row_count: u32 = db
3296 .conn
3297 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3298 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003299 // We expect 9 rows here because there are three blobs per attestation key, i.e.,
3300 // one key, one certificate chain, and one certificate.
3301 assert_eq!(blob_entry_row_count, 9);
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003302
Max Bires2b2e6562020-09-22 11:22:36 -07003303 assert_eq!(db.delete_expired_attestation_keys()?, 2);
3304
3305 let mut cert_chain =
3306 db.retrieve_attestation_key_and_cert_chain(Domain::APP, namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003307 assert!(cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003308 let value = cert_chain.unwrap();
Max Biresb2e1d032021-02-08 21:35:05 -08003309 assert_eq!(entry_values.batch_cert, value.batch_cert.to_vec());
3310 assert_eq!(entry_values.cert_chain, value.cert_chain.to_vec());
3311 assert_eq!(entry_values.priv_key, value.private_key.to_vec());
Max Bires2b2e6562020-09-22 11:22:36 -07003312
3313 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3314 Domain::APP,
3315 namespace_del1,
3316 &KEYSTORE_UUID,
3317 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003318 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003319 cert_chain = db.retrieve_attestation_key_and_cert_chain(
3320 Domain::APP,
3321 namespace_del2,
3322 &KEYSTORE_UUID,
3323 )?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003324 assert!(!cert_chain.is_some());
Max Bires2b2e6562020-09-22 11:22:36 -07003325
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003326 // Give the garbage collector half a second to catch up.
3327 std::thread::sleep(Duration::from_millis(500));
Max Bires2b2e6562020-09-22 11:22:36 -07003328
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003329 let blob_entry_row_count: u32 = db
3330 .conn
3331 .query_row("SELECT COUNT(id) FROM persistent.blobentry;", NO_PARAMS, |row| row.get(0))
3332 .expect("Failed to get blob entry row count.");
Max Biresb2e1d032021-02-08 21:35:05 -08003333 // There shound be 3 blob entries left, because we deleted two of the attestation
3334 // key entries with three blobs each.
3335 assert_eq!(blob_entry_row_count, 3);
Max Bires2b2e6562020-09-22 11:22:36 -07003336
Max Bires2b2e6562020-09-22 11:22:36 -07003337 Ok(())
3338 }
3339
3340 #[test]
Joel Galenson33c04ad2020-08-03 11:04:38 -07003341 fn test_rebind_alias() -> Result<()> {
Max Bires8e93d2b2021-01-14 13:17:59 -08003342 fn extractor(
3343 ke: &KeyEntryRow,
3344 ) -> (Option<Domain>, Option<i64>, Option<&str>, Option<Uuid>) {
3345 (ke.domain, ke.namespace, ke.alias.as_deref(), ke.km_uuid)
Joel Galenson33c04ad2020-08-03 11:04:38 -07003346 }
3347
Janis Danisevskis4df44f42020-08-26 14:40:03 -07003348 let mut db = new_test_db()?;
Janis Danisevskis66784c42021-01-27 08:40:25 -08003349 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
3350 db.create_key_entry(&Domain::APP, &42, &KEYSTORE_UUID)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003351 let entries = get_keyentry(&db)?;
3352 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003353 assert_eq!(
3354 extractor(&entries[0]),
3355 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3356 );
3357 assert_eq!(
3358 extractor(&entries[1]),
3359 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3360 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003361
3362 // Test that the first call to rebind_alias sets the alias.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003363 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[0].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003364 let entries = get_keyentry(&db)?;
3365 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003366 assert_eq!(
3367 extractor(&entries[0]),
3368 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3369 );
3370 assert_eq!(
3371 extractor(&entries[1]),
3372 (Some(Domain::APP), Some(42), None, Some(KEYSTORE_UUID))
3373 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003374
3375 // Test that the second call to rebind_alias also empties the old one.
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003376 rebind_alias(&mut db, &KEY_ID_LOCK.get(entries[1].id), "foo", Domain::APP, 42)?;
Joel Galenson33c04ad2020-08-03 11:04:38 -07003377 let entries = get_keyentry(&db)?;
3378 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003379 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3380 assert_eq!(
3381 extractor(&entries[1]),
3382 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3383 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003384
3385 // Test that we must pass in a valid Domain.
3386 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003387 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::GRANT, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003388 "Domain Domain(1) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003389 );
3390 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003391 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::BLOB, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003392 "Domain Domain(3) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003393 );
3394 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003395 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::KEY_ID, 42),
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003396 "Domain Domain(4) must be either App or SELinux.",
Joel Galenson33c04ad2020-08-03 11:04:38 -07003397 );
3398
3399 // Test that we correctly handle setting an alias for something that does not exist.
3400 check_result_is_error_containing_string(
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08003401 rebind_alias(&mut db, &KEY_ID_LOCK.get(0), "foo", Domain::SELINUX, 42),
Joel Galenson33c04ad2020-08-03 11:04:38 -07003402 "Expected to update a single entry but instead updated 0",
3403 );
3404 // Test that we correctly abort the transaction in this case.
3405 let entries = get_keyentry(&db)?;
3406 assert_eq!(entries.len(), 2);
Max Bires8e93d2b2021-01-14 13:17:59 -08003407 assert_eq!(extractor(&entries[0]), (None, None, None, Some(KEYSTORE_UUID)));
3408 assert_eq!(
3409 extractor(&entries[1]),
3410 (Some(Domain::APP), Some(42), Some("foo"), Some(KEYSTORE_UUID))
3411 );
Joel Galenson33c04ad2020-08-03 11:04:38 -07003412
3413 Ok(())
3414 }
3415
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003416 #[test]
3417 fn test_grant_ungrant() -> Result<()> {
3418 const CALLER_UID: u32 = 15;
3419 const GRANTEE_UID: u32 = 12;
3420 const SELINUX_NAMESPACE: i64 = 7;
3421
3422 let mut db = new_test_db()?;
3423 db.conn.execute(
Max Bires8e93d2b2021-01-14 13:17:59 -08003424 "INSERT INTO persistent.keyentry (id, key_type, domain, namespace, alias, state, km_uuid)
3425 VALUES (1, 0, 0, 15, 'key', 1, ?), (2, 0, 2, 7, 'yek', 1, ?);",
3426 params![KEYSTORE_UUID, KEYSTORE_UUID],
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003427 )?;
3428 let app_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003429 domain: super::Domain::APP,
3430 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003431 alias: Some("key".to_string()),
3432 blob: None,
3433 };
3434 const PVEC1: KeyPermSet = key_perm_set![KeyPerm::use_(), KeyPerm::get_info()];
3435 const PVEC2: KeyPermSet = key_perm_set![KeyPerm::use_()];
3436
3437 // Reset totally predictable random number generator in case we
3438 // are not the first test running on this thread.
3439 reset_random();
3440 let next_random = 0i64;
3441
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003442 let app_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003443 .grant(&app_key, CALLER_UID, GRANTEE_UID, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003444 assert_eq!(*a, PVEC1);
3445 assert_eq!(
3446 *k,
3447 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003448 domain: super::Domain::APP,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003449 // namespace must be set to the caller_uid.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003450 nspace: CALLER_UID as i64,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003451 alias: Some("key".to_string()),
3452 blob: None,
3453 }
3454 );
3455 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003456 })
3457 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003458
3459 assert_eq!(
3460 app_granted_key,
3461 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003462 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003463 // The grantid is next_random due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003464 nspace: next_random,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003465 alias: None,
3466 blob: None,
3467 }
3468 );
3469
3470 let selinux_key = KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003471 domain: super::Domain::SELINUX,
3472 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003473 alias: Some("yek".to_string()),
3474 blob: None,
3475 };
3476
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003477 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003478 .grant(&selinux_key, CALLER_UID, 12, PVEC1, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003479 assert_eq!(*a, PVEC1);
3480 assert_eq!(
3481 *k,
3482 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003483 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003484 // namespace must be the supplied SELinux
3485 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003486 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003487 alias: Some("yek".to_string()),
3488 blob: None,
3489 }
3490 );
3491 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003492 })
3493 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003494
3495 assert_eq!(
3496 selinux_granted_key,
3497 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003498 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003499 // The grantid is next_random + 1 due to the mock random number generator.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003500 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003501 alias: None,
3502 blob: None,
3503 }
3504 );
3505
3506 // This should update the existing grant with PVEC2.
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003507 let selinux_granted_key = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003508 .grant(&selinux_key, CALLER_UID, 12, PVEC2, |k, a| {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003509 assert_eq!(*a, PVEC2);
3510 assert_eq!(
3511 *k,
3512 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003513 domain: super::Domain::SELINUX,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003514 // namespace must be the supplied SELinux
3515 // namespace.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003516 nspace: SELINUX_NAMESPACE,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003517 alias: Some("yek".to_string()),
3518 blob: None,
3519 }
3520 );
3521 Ok(())
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003522 })
3523 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003524
3525 assert_eq!(
3526 selinux_granted_key,
3527 KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003528 domain: super::Domain::GRANT,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003529 // Same grant id as before. The entry was only updated.
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003530 nspace: next_random + 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003531 alias: None,
3532 blob: None,
3533 }
3534 );
3535
3536 {
3537 // Limiting scope of stmt, because it borrows db.
3538 let mut stmt = db
3539 .conn
Janis Danisevskisbf15d732020-12-08 10:35:26 -08003540 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003541 let mut rows =
3542 stmt.query_map::<(i64, u32, i64, KeyPermSet), _, _>(NO_PARAMS, |row| {
3543 Ok((
3544 row.get(0)?,
3545 row.get(1)?,
3546 row.get(2)?,
3547 KeyPermSet::from(row.get::<_, i32>(3)?),
3548 ))
3549 })?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003550
3551 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003552 assert_eq!(r, (next_random, GRANTEE_UID, 1, PVEC1));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003553 let r = rows.next().unwrap().unwrap();
Janis Danisevskisee10b5f2020-09-22 16:42:35 -07003554 assert_eq!(r, (next_random + 1, GRANTEE_UID, 2, PVEC2));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003555 assert!(rows.next().is_none());
3556 }
3557
3558 debug_dump_keyentry_table(&mut db)?;
3559 println!("app_key {:?}", app_key);
3560 println!("selinux_key {:?}", selinux_key);
3561
Janis Danisevskis66784c42021-01-27 08:40:25 -08003562 db.ungrant(&app_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
3563 db.ungrant(&selinux_key, CALLER_UID, GRANTEE_UID, |_| Ok(()))?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003564
3565 Ok(())
3566 }
3567
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003568 static TEST_KEY_BLOB: &[u8] = b"my test blob";
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003569 static TEST_CERT_BLOB: &[u8] = b"my test cert";
3570 static TEST_CERT_CHAIN_BLOB: &[u8] = b"my test cert_chain";
3571
3572 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003573 fn test_set_blob() -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003574 let key_id = KEY_ID_LOCK.get(3000);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003575 let mut db = new_test_db()?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003576 let mut blob_metadata = BlobMetaData::new();
3577 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
3578 db.set_blob(
3579 &key_id,
3580 SubComponentType::KEY_BLOB,
3581 Some(TEST_KEY_BLOB),
3582 Some(&blob_metadata),
3583 )?;
3584 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
3585 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003586 drop(key_id);
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003587
3588 let mut stmt = db.conn.prepare(
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003589 "SELECT subcomponent_type, keyentryid, blob, id FROM persistent.blobentry
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003590 ORDER BY subcomponent_type ASC;",
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003591 )?;
3592 let mut rows = stmt
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003593 .query_map::<((SubComponentType, i64, Vec<u8>), i64), _, _>(NO_PARAMS, |row| {
3594 Ok(((row.get(0)?, row.get(1)?, row.get(2)?), row.get(3)?))
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003595 })?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003596 let (r, id) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003597 assert_eq!(r, (SubComponentType::KEY_BLOB, 3000, TEST_KEY_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003598 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003599 assert_eq!(r, (SubComponentType::CERT, 3000, TEST_CERT_BLOB.to_vec()));
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003600 let (r, _) = rows.next().unwrap().unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003601 assert_eq!(r, (SubComponentType::CERT_CHAIN, 3000, TEST_CERT_CHAIN_BLOB.to_vec()));
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003602
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08003603 drop(rows);
3604 drop(stmt);
3605
3606 assert_eq!(
3607 db.with_transaction(TransactionBehavior::Immediate, |tx| {
3608 BlobMetaData::load_from_db(id, tx).no_gc()
3609 })
3610 .expect("Should find blob metadata."),
3611 blob_metadata
3612 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003613 Ok(())
3614 }
3615
3616 static TEST_ALIAS: &str = "my super duper key";
3617
3618 #[test]
3619 fn test_insert_and_load_full_keyentry_domain_app() -> Result<()> {
3620 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003621 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003622 .context("test_insert_and_load_full_keyentry_domain_app")?
3623 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003624 let (_key_guard, key_entry) = db
3625 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003626 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003627 domain: Domain::APP,
3628 nspace: 0,
3629 alias: Some(TEST_ALIAS.to_string()),
3630 blob: None,
3631 },
3632 KeyType::Client,
3633 KeyEntryLoadBits::BOTH,
3634 1,
3635 |_k, _av| Ok(()),
3636 )
3637 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003638 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003639
3640 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003641 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003642 domain: Domain::APP,
3643 nspace: 0,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003644 alias: Some(TEST_ALIAS.to_string()),
3645 blob: None,
3646 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003647 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003648 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003649 |_, _| Ok(()),
3650 )
3651 .unwrap();
3652
3653 assert_eq!(
3654 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3655 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003656 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003657 domain: Domain::APP,
3658 nspace: 0,
3659 alias: Some(TEST_ALIAS.to_string()),
3660 blob: None,
3661 },
3662 KeyType::Client,
3663 KeyEntryLoadBits::NONE,
3664 1,
3665 |_k, _av| Ok(()),
3666 )
3667 .unwrap_err()
3668 .root_cause()
3669 .downcast_ref::<KsError>()
3670 );
3671
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003672 Ok(())
3673 }
3674
3675 #[test]
Janis Danisevskis377d1002021-01-27 19:07:48 -08003676 fn test_insert_and_load_certificate_entry_domain_app() -> Result<()> {
3677 let mut db = new_test_db()?;
3678
3679 db.store_new_certificate(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003680 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003681 domain: Domain::APP,
3682 nspace: 1,
3683 alias: Some(TEST_ALIAS.to_string()),
3684 blob: None,
3685 },
3686 TEST_CERT_BLOB,
Max Bires8e93d2b2021-01-14 13:17:59 -08003687 &KEYSTORE_UUID,
Janis Danisevskis377d1002021-01-27 19:07:48 -08003688 )
3689 .expect("Trying to insert cert.");
3690
3691 let (_key_guard, mut key_entry) = db
3692 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003693 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003694 domain: Domain::APP,
3695 nspace: 1,
3696 alias: Some(TEST_ALIAS.to_string()),
3697 blob: None,
3698 },
3699 KeyType::Client,
3700 KeyEntryLoadBits::PUBLIC,
3701 1,
3702 |_k, _av| Ok(()),
3703 )
3704 .expect("Trying to read certificate entry.");
3705
3706 assert!(key_entry.pure_cert());
3707 assert!(key_entry.cert().is_none());
3708 assert_eq!(key_entry.take_cert_chain(), Some(TEST_CERT_BLOB.to_vec()));
3709
3710 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003711 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003712 domain: Domain::APP,
3713 nspace: 1,
3714 alias: Some(TEST_ALIAS.to_string()),
3715 blob: None,
3716 },
3717 KeyType::Client,
3718 1,
3719 |_, _| Ok(()),
3720 )
3721 .unwrap();
3722
3723 assert_eq!(
3724 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3725 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003726 &KeyDescriptor {
Janis Danisevskis377d1002021-01-27 19:07:48 -08003727 domain: Domain::APP,
3728 nspace: 1,
3729 alias: Some(TEST_ALIAS.to_string()),
3730 blob: None,
3731 },
3732 KeyType::Client,
3733 KeyEntryLoadBits::NONE,
3734 1,
3735 |_k, _av| Ok(()),
3736 )
3737 .unwrap_err()
3738 .root_cause()
3739 .downcast_ref::<KsError>()
3740 );
3741
3742 Ok(())
3743 }
3744
3745 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003746 fn test_insert_and_load_full_keyentry_domain_selinux() -> Result<()> {
3747 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003748 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003749 .context("test_insert_and_load_full_keyentry_domain_selinux")?
3750 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003751 let (_key_guard, key_entry) = db
3752 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003753 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003754 domain: Domain::SELINUX,
3755 nspace: 1,
3756 alias: Some(TEST_ALIAS.to_string()),
3757 blob: None,
3758 },
3759 KeyType::Client,
3760 KeyEntryLoadBits::BOTH,
3761 1,
3762 |_k, _av| Ok(()),
3763 )
3764 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08003765 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003766
3767 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003768 &KeyDescriptor {
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07003769 domain: Domain::SELINUX,
3770 nspace: 1,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003771 alias: Some(TEST_ALIAS.to_string()),
3772 blob: None,
3773 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003774 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003775 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003776 |_, _| Ok(()),
3777 )
3778 .unwrap();
3779
3780 assert_eq!(
3781 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3782 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003783 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003784 domain: Domain::SELINUX,
3785 nspace: 1,
3786 alias: Some(TEST_ALIAS.to_string()),
3787 blob: None,
3788 },
3789 KeyType::Client,
3790 KeyEntryLoadBits::NONE,
3791 1,
3792 |_k, _av| Ok(()),
3793 )
3794 .unwrap_err()
3795 .root_cause()
3796 .downcast_ref::<KsError>()
3797 );
3798
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003799 Ok(())
3800 }
3801
3802 #[test]
3803 fn test_insert_and_load_full_keyentry_domain_key_id() -> Result<()> {
3804 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003805 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003806 .context("test_insert_and_load_full_keyentry_domain_key_id")?
3807 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003808 let (_, key_entry) = db
3809 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003810 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003811 KeyType::Client,
3812 KeyEntryLoadBits::BOTH,
3813 1,
3814 |_k, _av| Ok(()),
3815 )
3816 .unwrap();
3817
Qi Wub9433b52020-12-01 14:52:46 +08003818 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003819
3820 db.unbind_key(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003821 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08003822 KeyType::Client,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003823 1,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003824 |_, _| Ok(()),
3825 )
3826 .unwrap();
3827
3828 assert_eq!(
3829 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3830 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003831 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003832 KeyType::Client,
3833 KeyEntryLoadBits::NONE,
3834 1,
3835 |_k, _av| Ok(()),
3836 )
3837 .unwrap_err()
3838 .root_cause()
3839 .downcast_ref::<KsError>()
3840 );
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003841
3842 Ok(())
3843 }
3844
3845 #[test]
Qi Wub9433b52020-12-01 14:52:46 +08003846 fn test_check_and_update_key_usage_count_with_limited_use_key() -> Result<()> {
3847 let mut db = new_test_db()?;
3848 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(123))
3849 .context("test_check_and_update_key_usage_count_with_limited_use_key")?
3850 .0;
3851 // Update the usage count of the limited use key.
3852 db.check_and_update_key_usage_count(key_id)?;
3853
3854 let (_key_guard, key_entry) = db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003855 &KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, alias: None, blob: None },
Qi Wub9433b52020-12-01 14:52:46 +08003856 KeyType::Client,
3857 KeyEntryLoadBits::BOTH,
3858 1,
3859 |_k, _av| Ok(()),
3860 )?;
3861
3862 // The usage count is decremented now.
3863 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, Some(122)));
3864
3865 Ok(())
3866 }
3867
3868 #[test]
3869 fn test_check_and_update_key_usage_count_with_exhausted_limited_use_key() -> Result<()> {
3870 let mut db = new_test_db()?;
3871 let key_id = make_test_key_entry(&mut db, Domain::SELINUX, 1, TEST_ALIAS, Some(1))
3872 .context("test_check_and_update_key_usage_count_with_exhausted_limited_use_key")?
3873 .0;
3874 // Update the usage count of the limited use key.
3875 db.check_and_update_key_usage_count(key_id).expect(concat!(
3876 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3877 "This should succeed."
3878 ));
3879
3880 // Try to update the exhausted limited use key.
3881 let e = db.check_and_update_key_usage_count(key_id).expect_err(concat!(
3882 "In test_check_and_update_key_usage_count_with_exhausted_limited_use_key: ",
3883 "This should fail."
3884 ));
3885 assert_eq!(
3886 &KsError::Km(ErrorCode::INVALID_KEY_BLOB),
3887 e.root_cause().downcast_ref::<KsError>().unwrap()
3888 );
3889
3890 Ok(())
3891 }
3892
3893 #[test]
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003894 fn test_insert_and_load_full_keyentry_from_grant() -> Result<()> {
3895 let mut db = new_test_db()?;
Qi Wub9433b52020-12-01 14:52:46 +08003896 let key_id = make_test_key_entry(&mut db, Domain::APP, 1, TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08003897 .context("test_insert_and_load_full_keyentry_from_grant")?
3898 .0;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003899
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003900 let granted_key = db
3901 .grant(
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 1,
3909 2,
3910 key_perm_set![KeyPerm::use_()],
3911 |_k, _av| Ok(()),
3912 )
3913 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003914
3915 debug_dump_grant_table(&mut db)?;
3916
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003917 let (_key_guard, key_entry) = db
Janis Danisevskis66784c42021-01-27 08:40:25 -08003918 .load_key_entry(&granted_key, KeyType::Client, KeyEntryLoadBits::BOTH, 2, |k, av| {
3919 assert_eq!(Domain::GRANT, k.domain);
3920 assert!(av.unwrap().includes(KeyPerm::use_()));
3921 Ok(())
3922 })
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003923 .unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003924
Qi Wub9433b52020-12-01 14:52:46 +08003925 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003926
Janis Danisevskis66784c42021-01-27 08:40:25 -08003927 db.unbind_key(&granted_key, KeyType::Client, 2, |_, _| Ok(())).unwrap();
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003928
3929 assert_eq!(
3930 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
3931 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003932 &granted_key,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08003933 KeyType::Client,
3934 KeyEntryLoadBits::NONE,
3935 2,
3936 |_k, _av| Ok(()),
3937 )
3938 .unwrap_err()
3939 .root_cause()
3940 .downcast_ref::<KsError>()
3941 );
3942
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07003943 Ok(())
3944 }
3945
Janis Danisevskis45760022021-01-19 16:34:10 -08003946 // This test attempts to load a key by key id while the caller is not the owner
3947 // but a grant exists for the given key and the caller.
3948 #[test]
3949 fn test_insert_and_load_full_keyentry_from_grant_by_key_id() -> Result<()> {
3950 let mut db = new_test_db()?;
3951 const OWNER_UID: u32 = 1u32;
3952 const GRANTEE_UID: u32 = 2u32;
3953 const SOMEONE_ELSE_UID: u32 = 3u32;
3954 let key_id = make_test_key_entry(&mut db, Domain::APP, OWNER_UID as i64, TEST_ALIAS, None)
3955 .context("test_insert_and_load_full_keyentry_from_grant_by_key_id")?
3956 .0;
3957
3958 db.grant(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003959 &KeyDescriptor {
Janis Danisevskis45760022021-01-19 16:34:10 -08003960 domain: Domain::APP,
3961 nspace: 0,
3962 alias: Some(TEST_ALIAS.to_string()),
3963 blob: None,
3964 },
3965 OWNER_UID,
3966 GRANTEE_UID,
3967 key_perm_set![KeyPerm::use_()],
3968 |_k, _av| Ok(()),
3969 )
3970 .unwrap();
3971
3972 debug_dump_grant_table(&mut db)?;
3973
3974 let id_descriptor =
3975 KeyDescriptor { domain: Domain::KEY_ID, nspace: key_id, ..Default::default() };
3976
3977 let (_, key_entry) = db
3978 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003979 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003980 KeyType::Client,
3981 KeyEntryLoadBits::BOTH,
3982 GRANTEE_UID,
3983 |k, av| {
3984 assert_eq!(Domain::APP, k.domain);
3985 assert_eq!(OWNER_UID as i64, k.nspace);
3986 assert!(av.unwrap().includes(KeyPerm::use_()));
3987 Ok(())
3988 },
3989 )
3990 .unwrap();
3991
3992 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
3993
3994 let (_, key_entry) = db
3995 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08003996 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08003997 KeyType::Client,
3998 KeyEntryLoadBits::BOTH,
3999 SOMEONE_ELSE_UID,
4000 |k, av| {
4001 assert_eq!(Domain::APP, k.domain);
4002 assert_eq!(OWNER_UID as i64, k.nspace);
4003 assert!(av.is_none());
4004 Ok(())
4005 },
4006 )
4007 .unwrap();
4008
4009 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
4010
Janis Danisevskis66784c42021-01-27 08:40:25 -08004011 db.unbind_key(&id_descriptor, KeyType::Client, OWNER_UID, |_, _| Ok(())).unwrap();
Janis Danisevskis45760022021-01-19 16:34:10 -08004012
4013 assert_eq!(
4014 Some(&KsError::Rc(ResponseCode::KEY_NOT_FOUND)),
4015 db.load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004016 &id_descriptor,
Janis Danisevskis45760022021-01-19 16:34:10 -08004017 KeyType::Client,
4018 KeyEntryLoadBits::NONE,
4019 GRANTEE_UID,
4020 |_k, _av| Ok(()),
4021 )
4022 .unwrap_err()
4023 .root_cause()
4024 .downcast_ref::<KsError>()
4025 );
4026
4027 Ok(())
4028 }
4029
Janis Danisevskisaec14592020-11-12 09:41:49 -08004030 static KEY_LOCK_TEST_ALIAS: &str = "my super duper locked key";
4031
Janis Danisevskisaec14592020-11-12 09:41:49 -08004032 #[test]
4033 fn test_insert_and_load_full_keyentry_domain_app_concurrently() -> Result<()> {
4034 let handle = {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004035 let temp_dir = Arc::new(TempDir::new("id_lock_test")?);
4036 let temp_dir_clone = temp_dir.clone();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004037 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004038 let key_id = make_test_key_entry(&mut db, Domain::APP, 33, KEY_LOCK_TEST_ALIAS, None)
Janis Danisevskisaec14592020-11-12 09:41:49 -08004039 .context("test_insert_and_load_full_keyentry_domain_app")?
4040 .0;
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004041 let (_key_guard, key_entry) = db
4042 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004043 &KeyDescriptor {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004044 domain: Domain::APP,
4045 nspace: 0,
4046 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4047 blob: None,
4048 },
4049 KeyType::Client,
4050 KeyEntryLoadBits::BOTH,
4051 33,
4052 |_k, _av| Ok(()),
4053 )
4054 .unwrap();
Qi Wub9433b52020-12-01 14:52:46 +08004055 assert_eq!(key_entry, make_test_key_entry_test_vector(key_id, None));
Janis Danisevskisaec14592020-11-12 09:41:49 -08004056 let state = Arc::new(AtomicU8::new(1));
4057 let state2 = state.clone();
4058
4059 // Spawning a second thread that attempts to acquire the key id lock
4060 // for the same key as the primary thread. The primary thread then
4061 // waits, thereby forcing the secondary thread into the second stage
4062 // of acquiring the lock (see KEY ID LOCK 2/2 above).
4063 // The test succeeds if the secondary thread observes the transition
4064 // of `state` from 1 to 2, despite having a whole second to overtake
4065 // the primary thread.
4066 let handle = thread::spawn(move || {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004067 let temp_dir = temp_dir_clone;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004068 let mut db = KeystoreDB::new(temp_dir.path(), None).unwrap();
Janis Danisevskisaec14592020-11-12 09:41:49 -08004069 assert!(db
4070 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004071 &KeyDescriptor {
Janis Danisevskisaec14592020-11-12 09:41:49 -08004072 domain: Domain::APP,
4073 nspace: 0,
4074 alias: Some(KEY_LOCK_TEST_ALIAS.to_string()),
4075 blob: None,
4076 },
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004077 KeyType::Client,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004078 KeyEntryLoadBits::BOTH,
4079 33,
4080 |_k, _av| Ok(()),
4081 )
4082 .is_ok());
4083 // We should only see a 2 here because we can only return
4084 // from load_key_entry when the `_key_guard` expires,
4085 // which happens at the end of the scope.
4086 assert_eq!(2, state2.load(Ordering::Relaxed));
4087 });
4088
4089 thread::sleep(std::time::Duration::from_millis(1000));
4090
4091 assert_eq!(Ok(1), state.compare_exchange(1, 2, Ordering::Relaxed, Ordering::Relaxed));
4092
4093 // Return the handle from this scope so we can join with the
4094 // secondary thread after the key id lock has expired.
4095 handle
4096 // This is where the `_key_guard` goes out of scope,
4097 // which is the reason for concurrent load_key_entry on the same key
4098 // to unblock.
4099 };
4100 // Join with the secondary thread and unwrap, to propagate failing asserts to the
4101 // main test thread. We will not see failing asserts in secondary threads otherwise.
4102 handle.join().unwrap();
4103 Ok(())
4104 }
4105
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004106 #[test]
Janis Danisevskis66784c42021-01-27 08:40:25 -08004107 fn teset_database_busy_error_code() {
4108 let temp_dir =
4109 TempDir::new("test_database_busy_error_code_").expect("Failed to create temp dir.");
4110
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004111 let mut db1 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database1.");
4112 let mut db2 = KeystoreDB::new(temp_dir.path(), None).expect("Failed to open database2.");
Janis Danisevskis66784c42021-01-27 08:40:25 -08004113
4114 let _tx1 = db1
4115 .conn
4116 .transaction_with_behavior(TransactionBehavior::Immediate)
4117 .expect("Failed to create first transaction.");
4118
4119 let error = db2
4120 .conn
4121 .transaction_with_behavior(TransactionBehavior::Immediate)
4122 .context("Transaction begin failed.")
4123 .expect_err("This should fail.");
4124 let root_cause = error.root_cause();
4125 if let Some(rusqlite::ffi::Error { code: rusqlite::ErrorCode::DatabaseBusy, .. }) =
4126 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4127 {
4128 return;
4129 }
4130 panic!(
4131 "Unexpected error {:?} \n{:?} \n{:?}",
4132 error,
4133 root_cause,
4134 root_cause.downcast_ref::<rusqlite::ffi::Error>()
4135 )
4136 }
4137
4138 #[cfg(disabled)]
4139 #[test]
4140 fn test_large_number_of_concurrent_db_manipulations() -> Result<()> {
4141 let temp_dir = Arc::new(
4142 TempDir::new("test_large_number_of_concurrent_db_manipulations_")
4143 .expect("Failed to create temp dir."),
4144 );
4145
4146 let test_begin = Instant::now();
4147
4148 let mut db = KeystoreDB::new(temp_dir.path()).expect("Failed to open database.");
4149 const KEY_COUNT: u32 = 500u32;
4150 const OPEN_DB_COUNT: u32 = 50u32;
4151
4152 let mut actual_key_count = KEY_COUNT;
4153 // First insert KEY_COUNT keys.
4154 for count in 0..KEY_COUNT {
4155 if Instant::now().duration_since(test_begin) >= Duration::from_secs(15) {
4156 actual_key_count = count;
4157 break;
4158 }
4159 let alias = format!("test_alias_{}", count);
4160 make_test_key_entry(&mut db, Domain::APP, 1, &alias, None)
4161 .expect("Failed to make key entry.");
4162 }
4163
4164 // Insert more keys from a different thread and into a different namespace.
4165 let temp_dir1 = temp_dir.clone();
4166 let handle1 = thread::spawn(move || {
4167 let mut db = KeystoreDB::new(temp_dir1.path()).expect("Failed to open database.");
4168
4169 for count in 0..actual_key_count {
4170 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4171 return;
4172 }
4173 let alias = format!("test_alias_{}", count);
4174 make_test_key_entry(&mut db, Domain::APP, 2, &alias, None)
4175 .expect("Failed to make key entry.");
4176 }
4177
4178 // then unbind them again.
4179 for count in 0..actual_key_count {
4180 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4181 return;
4182 }
4183 let key = KeyDescriptor {
4184 domain: Domain::APP,
4185 nspace: -1,
4186 alias: Some(format!("test_alias_{}", count)),
4187 blob: None,
4188 };
4189 db.unbind_key(&key, KeyType::Client, 2, |_, _| Ok(())).expect("Unbind Failed.");
4190 }
4191 });
4192
4193 // And start unbinding the first set of keys.
4194 let temp_dir2 = temp_dir.clone();
4195 let handle2 = thread::spawn(move || {
4196 let mut db = KeystoreDB::new(temp_dir2.path()).expect("Failed to open database.");
4197
4198 for count in 0..actual_key_count {
4199 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4200 return;
4201 }
4202 let key = KeyDescriptor {
4203 domain: Domain::APP,
4204 nspace: -1,
4205 alias: Some(format!("test_alias_{}", count)),
4206 blob: None,
4207 };
4208 db.unbind_key(&key, KeyType::Client, 1, |_, _| Ok(())).expect("Unbind Failed.");
4209 }
4210 });
4211
4212 let stop_deleting = Arc::new(AtomicU8::new(0));
4213 let stop_deleting2 = stop_deleting.clone();
4214
4215 // And delete anything that is unreferenced keys.
4216 let temp_dir3 = temp_dir.clone();
4217 let handle3 = thread::spawn(move || {
4218 let mut db = KeystoreDB::new(temp_dir3.path()).expect("Failed to open database.");
4219
4220 while stop_deleting2.load(Ordering::Relaxed) != 1 {
4221 while let Some((key_guard, _key)) =
4222 db.get_unreferenced_key().expect("Failed to get unreferenced Key.")
4223 {
4224 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4225 return;
4226 }
4227 db.purge_key_entry(key_guard).expect("Failed to purge key.");
4228 }
4229 std::thread::sleep(std::time::Duration::from_millis(100));
4230 }
4231 });
4232
4233 // While a lot of inserting and deleting is going on we have to open database connections
4234 // successfully and use them.
4235 // This clone is not redundant, because temp_dir needs to be kept alive until db goes
4236 // out of scope.
4237 #[allow(clippy::redundant_clone)]
4238 let temp_dir4 = temp_dir.clone();
4239 let handle4 = thread::spawn(move || {
4240 for count in 0..OPEN_DB_COUNT {
4241 if Instant::now().duration_since(test_begin) >= Duration::from_secs(40) {
4242 return;
4243 }
4244 let mut db = KeystoreDB::new(temp_dir4.path()).expect("Failed to open database.");
4245
4246 let alias = format!("test_alias_{}", count);
4247 make_test_key_entry(&mut db, Domain::APP, 3, &alias, None)
4248 .expect("Failed to make key entry.");
4249 let key = KeyDescriptor {
4250 domain: Domain::APP,
4251 nspace: -1,
4252 alias: Some(alias),
4253 blob: None,
4254 };
4255 db.unbind_key(&key, KeyType::Client, 3, |_, _| Ok(())).expect("Unbind Failed.");
4256 }
4257 });
4258
4259 handle1.join().expect("Thread 1 panicked.");
4260 handle2.join().expect("Thread 2 panicked.");
4261 handle4.join().expect("Thread 4 panicked.");
4262
4263 stop_deleting.store(1, Ordering::Relaxed);
4264 handle3.join().expect("Thread 3 panicked.");
4265
4266 Ok(())
4267 }
4268
4269 #[test]
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004270 fn list() -> Result<()> {
4271 let temp_dir = TempDir::new("list_test")?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004272 let mut db = KeystoreDB::new(temp_dir.path(), None)?;
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004273 static LIST_O_ENTRIES: &[(Domain, i64, &str)] = &[
4274 (Domain::APP, 1, "test1"),
4275 (Domain::APP, 1, "test2"),
4276 (Domain::APP, 1, "test3"),
4277 (Domain::APP, 1, "test4"),
4278 (Domain::APP, 1, "test5"),
4279 (Domain::APP, 1, "test6"),
4280 (Domain::APP, 1, "test7"),
4281 (Domain::APP, 2, "test1"),
4282 (Domain::APP, 2, "test2"),
4283 (Domain::APP, 2, "test3"),
4284 (Domain::APP, 2, "test4"),
4285 (Domain::APP, 2, "test5"),
4286 (Domain::APP, 2, "test6"),
4287 (Domain::APP, 2, "test8"),
4288 (Domain::SELINUX, 100, "test1"),
4289 (Domain::SELINUX, 100, "test2"),
4290 (Domain::SELINUX, 100, "test3"),
4291 (Domain::SELINUX, 100, "test4"),
4292 (Domain::SELINUX, 100, "test5"),
4293 (Domain::SELINUX, 100, "test6"),
4294 (Domain::SELINUX, 100, "test9"),
4295 ];
4296
4297 let list_o_keys: Vec<(i64, i64)> = LIST_O_ENTRIES
4298 .iter()
4299 .map(|(domain, ns, alias)| {
Qi Wub9433b52020-12-01 14:52:46 +08004300 let entry = make_test_key_entry(&mut db, *domain, *ns, *alias, None)
4301 .unwrap_or_else(|e| {
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004302 panic!("Failed to insert {:?} {} {}. Error {:?}", domain, ns, alias, e)
4303 });
4304 (entry.id(), *ns)
4305 })
4306 .collect();
4307
4308 for (domain, namespace) in
4309 &[(Domain::APP, 1i64), (Domain::APP, 2i64), (Domain::SELINUX, 100i64)]
4310 {
4311 let mut list_o_descriptors: Vec<KeyDescriptor> = LIST_O_ENTRIES
4312 .iter()
4313 .filter_map(|(domain, ns, alias)| match ns {
4314 ns if *ns == *namespace => Some(KeyDescriptor {
4315 domain: *domain,
4316 nspace: *ns,
4317 alias: Some(alias.to_string()),
4318 blob: None,
4319 }),
4320 _ => None,
4321 })
4322 .collect();
4323 list_o_descriptors.sort();
4324 let mut list_result = db.list(*domain, *namespace)?;
4325 list_result.sort();
4326 assert_eq!(list_o_descriptors, list_result);
4327
4328 let mut list_o_ids: Vec<i64> = list_o_descriptors
4329 .into_iter()
4330 .map(|d| {
4331 let (_, entry) = db
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004332 .load_key_entry(
Janis Danisevskis66784c42021-01-27 08:40:25 -08004333 &d,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004334 KeyType::Client,
4335 KeyEntryLoadBits::NONE,
4336 *namespace as u32,
4337 |_, _| Ok(()),
4338 )
Janis Danisevskise92a5e62020-12-02 12:57:41 -08004339 .unwrap();
4340 entry.id()
4341 })
4342 .collect();
4343 list_o_ids.sort_unstable();
4344 let mut loaded_entries: Vec<i64> = list_o_keys
4345 .iter()
4346 .filter_map(|(id, ns)| match ns {
4347 ns if *ns == *namespace => Some(*id),
4348 _ => None,
4349 })
4350 .collect();
4351 loaded_entries.sort_unstable();
4352 assert_eq!(list_o_ids, loaded_entries);
4353 }
4354 assert_eq!(Vec::<KeyDescriptor>::new(), db.list(Domain::SELINUX, 101)?);
4355
4356 Ok(())
4357 }
4358
Joel Galenson0891bc12020-07-20 10:37:03 -07004359 // Helpers
4360
4361 // Checks that the given result is an error containing the given string.
4362 fn check_result_is_error_containing_string<T>(result: Result<T>, target: &str) {
4363 let error_str = format!(
4364 "{:#?}",
4365 result.err().unwrap_or_else(|| panic!("Expected the error: {}", target))
4366 );
4367 assert!(
4368 error_str.contains(target),
4369 "The string \"{}\" should contain \"{}\"",
4370 error_str,
4371 target
4372 );
4373 }
4374
Joel Galenson2aab4432020-07-22 15:27:57 -07004375 #[derive(Debug, PartialEq)]
Joel Galenson0891bc12020-07-20 10:37:03 -07004376 #[allow(dead_code)]
4377 struct KeyEntryRow {
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004378 id: i64,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004379 key_type: KeyType,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004380 domain: Option<Domain>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004381 namespace: Option<i64>,
4382 alias: Option<String>,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004383 state: KeyLifeCycle,
Max Bires8e93d2b2021-01-14 13:17:59 -08004384 km_uuid: Option<Uuid>,
Joel Galenson0891bc12020-07-20 10:37:03 -07004385 }
4386
4387 fn get_keyentry(db: &KeystoreDB) -> Result<Vec<KeyEntryRow>> {
4388 db.conn
Joel Galenson2aab4432020-07-22 15:27:57 -07004389 .prepare("SELECT * FROM persistent.keyentry;")?
Joel Galenson0891bc12020-07-20 10:37:03 -07004390 .query_map(NO_PARAMS, |row| {
Joel Galenson0891bc12020-07-20 10:37:03 -07004391 Ok(KeyEntryRow {
4392 id: row.get(0)?,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004393 key_type: row.get(1)?,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004394 domain: match row.get(2)? {
4395 Some(i) => Some(Domain(i)),
4396 None => None,
4397 },
Joel Galenson0891bc12020-07-20 10:37:03 -07004398 namespace: row.get(3)?,
4399 alias: row.get(4)?,
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004400 state: row.get(5)?,
Max Bires8e93d2b2021-01-14 13:17:59 -08004401 km_uuid: row.get(6)?,
Joel Galenson0891bc12020-07-20 10:37:03 -07004402 })
4403 })?
4404 .map(|r| r.context("Could not read keyentry row."))
4405 .collect::<Result<Vec<_>>>()
4406 }
4407
Max Biresb2e1d032021-02-08 21:35:05 -08004408 struct RemoteProvValues {
4409 cert_chain: Vec<u8>,
4410 priv_key: Vec<u8>,
4411 batch_cert: Vec<u8>,
4412 }
4413
Max Bires2b2e6562020-09-22 11:22:36 -07004414 fn load_attestation_key_pool(
4415 db: &mut KeystoreDB,
4416 expiration_date: i64,
4417 namespace: i64,
4418 base_byte: u8,
Max Biresb2e1d032021-02-08 21:35:05 -08004419 ) -> Result<RemoteProvValues> {
Max Bires2b2e6562020-09-22 11:22:36 -07004420 let public_key: Vec<u8> = vec![base_byte, 0x02 * base_byte];
4421 let cert_chain: Vec<u8> = vec![0x03 * base_byte, 0x04 * base_byte];
4422 let priv_key: Vec<u8> = vec![0x05 * base_byte, 0x06 * base_byte];
4423 let raw_public_key: Vec<u8> = vec![0x0b * base_byte, 0x0c * base_byte];
Max Biresb2e1d032021-02-08 21:35:05 -08004424 let batch_cert: Vec<u8> = vec![base_byte * 0x0d, base_byte * 0x0e];
Max Bires2b2e6562020-09-22 11:22:36 -07004425 db.create_attestation_key_entry(&public_key, &raw_public_key, &priv_key, &KEYSTORE_UUID)?;
4426 db.store_signed_attestation_certificate_chain(
4427 &raw_public_key,
Max Biresb2e1d032021-02-08 21:35:05 -08004428 &batch_cert,
Max Bires2b2e6562020-09-22 11:22:36 -07004429 &cert_chain,
4430 expiration_date,
4431 &KEYSTORE_UUID,
4432 )?;
4433 db.assign_attestation_key(Domain::APP, namespace, &KEYSTORE_UUID)?;
Max Biresb2e1d032021-02-08 21:35:05 -08004434 Ok(RemoteProvValues { cert_chain, priv_key, batch_cert })
Max Bires2b2e6562020-09-22 11:22:36 -07004435 }
4436
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004437 // Note: The parameters and SecurityLevel associations are nonsensical. This
4438 // collection is only used to check if the parameters are preserved as expected by the
4439 // database.
Qi Wub9433b52020-12-01 14:52:46 +08004440 fn make_test_params(max_usage_count: Option<i32>) -> Vec<KeyParameter> {
4441 let mut params = vec![
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004442 KeyParameter::new(KeyParameterValue::Invalid, SecurityLevel::TRUSTED_ENVIRONMENT),
4443 KeyParameter::new(
4444 KeyParameterValue::KeyPurpose(KeyPurpose::SIGN),
4445 SecurityLevel::TRUSTED_ENVIRONMENT,
4446 ),
4447 KeyParameter::new(
4448 KeyParameterValue::KeyPurpose(KeyPurpose::DECRYPT),
4449 SecurityLevel::TRUSTED_ENVIRONMENT,
4450 ),
4451 KeyParameter::new(
4452 KeyParameterValue::Algorithm(Algorithm::RSA),
4453 SecurityLevel::TRUSTED_ENVIRONMENT,
4454 ),
4455 KeyParameter::new(KeyParameterValue::KeySize(1024), SecurityLevel::TRUSTED_ENVIRONMENT),
4456 KeyParameter::new(
4457 KeyParameterValue::BlockMode(BlockMode::ECB),
4458 SecurityLevel::TRUSTED_ENVIRONMENT,
4459 ),
4460 KeyParameter::new(
4461 KeyParameterValue::BlockMode(BlockMode::GCM),
4462 SecurityLevel::TRUSTED_ENVIRONMENT,
4463 ),
4464 KeyParameter::new(KeyParameterValue::Digest(Digest::NONE), SecurityLevel::STRONGBOX),
4465 KeyParameter::new(
4466 KeyParameterValue::Digest(Digest::MD5),
4467 SecurityLevel::TRUSTED_ENVIRONMENT,
4468 ),
4469 KeyParameter::new(
4470 KeyParameterValue::Digest(Digest::SHA_2_224),
4471 SecurityLevel::TRUSTED_ENVIRONMENT,
4472 ),
4473 KeyParameter::new(
4474 KeyParameterValue::Digest(Digest::SHA_2_256),
4475 SecurityLevel::STRONGBOX,
4476 ),
4477 KeyParameter::new(
4478 KeyParameterValue::PaddingMode(PaddingMode::NONE),
4479 SecurityLevel::TRUSTED_ENVIRONMENT,
4480 ),
4481 KeyParameter::new(
4482 KeyParameterValue::PaddingMode(PaddingMode::RSA_OAEP),
4483 SecurityLevel::TRUSTED_ENVIRONMENT,
4484 ),
4485 KeyParameter::new(
4486 KeyParameterValue::PaddingMode(PaddingMode::RSA_PSS),
4487 SecurityLevel::STRONGBOX,
4488 ),
4489 KeyParameter::new(
4490 KeyParameterValue::PaddingMode(PaddingMode::RSA_PKCS1_1_5_SIGN),
4491 SecurityLevel::TRUSTED_ENVIRONMENT,
4492 ),
4493 KeyParameter::new(KeyParameterValue::CallerNonce, SecurityLevel::TRUSTED_ENVIRONMENT),
4494 KeyParameter::new(KeyParameterValue::MinMacLength(256), SecurityLevel::STRONGBOX),
4495 KeyParameter::new(
4496 KeyParameterValue::EcCurve(EcCurve::P_224),
4497 SecurityLevel::TRUSTED_ENVIRONMENT,
4498 ),
4499 KeyParameter::new(KeyParameterValue::EcCurve(EcCurve::P_256), SecurityLevel::STRONGBOX),
4500 KeyParameter::new(
4501 KeyParameterValue::EcCurve(EcCurve::P_384),
4502 SecurityLevel::TRUSTED_ENVIRONMENT,
4503 ),
4504 KeyParameter::new(
4505 KeyParameterValue::EcCurve(EcCurve::P_521),
4506 SecurityLevel::TRUSTED_ENVIRONMENT,
4507 ),
4508 KeyParameter::new(
4509 KeyParameterValue::RSAPublicExponent(3),
4510 SecurityLevel::TRUSTED_ENVIRONMENT,
4511 ),
4512 KeyParameter::new(
4513 KeyParameterValue::IncludeUniqueID,
4514 SecurityLevel::TRUSTED_ENVIRONMENT,
4515 ),
4516 KeyParameter::new(KeyParameterValue::BootLoaderOnly, SecurityLevel::STRONGBOX),
4517 KeyParameter::new(KeyParameterValue::RollbackResistance, SecurityLevel::STRONGBOX),
4518 KeyParameter::new(
4519 KeyParameterValue::ActiveDateTime(1234567890),
4520 SecurityLevel::STRONGBOX,
4521 ),
4522 KeyParameter::new(
4523 KeyParameterValue::OriginationExpireDateTime(1234567890),
4524 SecurityLevel::TRUSTED_ENVIRONMENT,
4525 ),
4526 KeyParameter::new(
4527 KeyParameterValue::UsageExpireDateTime(1234567890),
4528 SecurityLevel::TRUSTED_ENVIRONMENT,
4529 ),
4530 KeyParameter::new(
4531 KeyParameterValue::MinSecondsBetweenOps(1234567890),
4532 SecurityLevel::TRUSTED_ENVIRONMENT,
4533 ),
4534 KeyParameter::new(
4535 KeyParameterValue::MaxUsesPerBoot(1234567890),
4536 SecurityLevel::TRUSTED_ENVIRONMENT,
4537 ),
4538 KeyParameter::new(KeyParameterValue::UserID(1), SecurityLevel::STRONGBOX),
4539 KeyParameter::new(KeyParameterValue::UserSecureID(42), SecurityLevel::STRONGBOX),
4540 KeyParameter::new(
4541 KeyParameterValue::NoAuthRequired,
4542 SecurityLevel::TRUSTED_ENVIRONMENT,
4543 ),
4544 KeyParameter::new(
4545 KeyParameterValue::HardwareAuthenticatorType(HardwareAuthenticatorType::PASSWORD),
4546 SecurityLevel::TRUSTED_ENVIRONMENT,
4547 ),
4548 KeyParameter::new(KeyParameterValue::AuthTimeout(1234567890), SecurityLevel::SOFTWARE),
4549 KeyParameter::new(KeyParameterValue::AllowWhileOnBody, SecurityLevel::SOFTWARE),
4550 KeyParameter::new(
4551 KeyParameterValue::TrustedUserPresenceRequired,
4552 SecurityLevel::TRUSTED_ENVIRONMENT,
4553 ),
4554 KeyParameter::new(
4555 KeyParameterValue::TrustedConfirmationRequired,
4556 SecurityLevel::TRUSTED_ENVIRONMENT,
4557 ),
4558 KeyParameter::new(
4559 KeyParameterValue::UnlockedDeviceRequired,
4560 SecurityLevel::TRUSTED_ENVIRONMENT,
4561 ),
4562 KeyParameter::new(
4563 KeyParameterValue::ApplicationID(vec![1u8, 2u8, 3u8, 4u8]),
4564 SecurityLevel::SOFTWARE,
4565 ),
4566 KeyParameter::new(
4567 KeyParameterValue::ApplicationData(vec![4u8, 3u8, 2u8, 1u8]),
4568 SecurityLevel::SOFTWARE,
4569 ),
4570 KeyParameter::new(
4571 KeyParameterValue::CreationDateTime(12345677890),
4572 SecurityLevel::SOFTWARE,
4573 ),
4574 KeyParameter::new(
4575 KeyParameterValue::KeyOrigin(KeyOrigin::GENERATED),
4576 SecurityLevel::TRUSTED_ENVIRONMENT,
4577 ),
4578 KeyParameter::new(
4579 KeyParameterValue::RootOfTrust(vec![3u8, 2u8, 1u8, 4u8]),
4580 SecurityLevel::TRUSTED_ENVIRONMENT,
4581 ),
4582 KeyParameter::new(KeyParameterValue::OSVersion(1), SecurityLevel::TRUSTED_ENVIRONMENT),
4583 KeyParameter::new(KeyParameterValue::OSPatchLevel(2), SecurityLevel::SOFTWARE),
4584 KeyParameter::new(
4585 KeyParameterValue::UniqueID(vec![4u8, 3u8, 1u8, 2u8]),
4586 SecurityLevel::SOFTWARE,
4587 ),
4588 KeyParameter::new(
4589 KeyParameterValue::AttestationChallenge(vec![4u8, 3u8, 1u8, 2u8]),
4590 SecurityLevel::TRUSTED_ENVIRONMENT,
4591 ),
4592 KeyParameter::new(
4593 KeyParameterValue::AttestationApplicationID(vec![4u8, 3u8, 1u8, 2u8]),
4594 SecurityLevel::TRUSTED_ENVIRONMENT,
4595 ),
4596 KeyParameter::new(
4597 KeyParameterValue::AttestationIdBrand(vec![4u8, 3u8, 1u8, 2u8]),
4598 SecurityLevel::TRUSTED_ENVIRONMENT,
4599 ),
4600 KeyParameter::new(
4601 KeyParameterValue::AttestationIdDevice(vec![4u8, 3u8, 1u8, 2u8]),
4602 SecurityLevel::TRUSTED_ENVIRONMENT,
4603 ),
4604 KeyParameter::new(
4605 KeyParameterValue::AttestationIdProduct(vec![4u8, 3u8, 1u8, 2u8]),
4606 SecurityLevel::TRUSTED_ENVIRONMENT,
4607 ),
4608 KeyParameter::new(
4609 KeyParameterValue::AttestationIdSerial(vec![4u8, 3u8, 1u8, 2u8]),
4610 SecurityLevel::TRUSTED_ENVIRONMENT,
4611 ),
4612 KeyParameter::new(
4613 KeyParameterValue::AttestationIdIMEI(vec![4u8, 3u8, 1u8, 2u8]),
4614 SecurityLevel::TRUSTED_ENVIRONMENT,
4615 ),
4616 KeyParameter::new(
4617 KeyParameterValue::AttestationIdMEID(vec![4u8, 3u8, 1u8, 2u8]),
4618 SecurityLevel::TRUSTED_ENVIRONMENT,
4619 ),
4620 KeyParameter::new(
4621 KeyParameterValue::AttestationIdManufacturer(vec![4u8, 3u8, 1u8, 2u8]),
4622 SecurityLevel::TRUSTED_ENVIRONMENT,
4623 ),
4624 KeyParameter::new(
4625 KeyParameterValue::AttestationIdModel(vec![4u8, 3u8, 1u8, 2u8]),
4626 SecurityLevel::TRUSTED_ENVIRONMENT,
4627 ),
4628 KeyParameter::new(
4629 KeyParameterValue::VendorPatchLevel(3),
4630 SecurityLevel::TRUSTED_ENVIRONMENT,
4631 ),
4632 KeyParameter::new(
4633 KeyParameterValue::BootPatchLevel(4),
4634 SecurityLevel::TRUSTED_ENVIRONMENT,
4635 ),
4636 KeyParameter::new(
4637 KeyParameterValue::AssociatedData(vec![4u8, 3u8, 1u8, 2u8]),
4638 SecurityLevel::TRUSTED_ENVIRONMENT,
4639 ),
4640 KeyParameter::new(
4641 KeyParameterValue::Nonce(vec![4u8, 3u8, 1u8, 2u8]),
4642 SecurityLevel::TRUSTED_ENVIRONMENT,
4643 ),
4644 KeyParameter::new(
4645 KeyParameterValue::MacLength(256),
4646 SecurityLevel::TRUSTED_ENVIRONMENT,
4647 ),
4648 KeyParameter::new(
4649 KeyParameterValue::ResetSinceIdRotation,
4650 SecurityLevel::TRUSTED_ENVIRONMENT,
4651 ),
4652 KeyParameter::new(
4653 KeyParameterValue::ConfirmationToken(vec![5u8, 5u8, 5u8, 5u8]),
4654 SecurityLevel::TRUSTED_ENVIRONMENT,
4655 ),
Qi Wub9433b52020-12-01 14:52:46 +08004656 ];
4657 if let Some(value) = max_usage_count {
4658 params.push(KeyParameter::new(
4659 KeyParameterValue::UsageCountLimit(value),
4660 SecurityLevel::SOFTWARE,
4661 ));
4662 }
4663 params
Janis Danisevskis3f322cb2020-09-03 14:46:22 -07004664 }
4665
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004666 fn make_test_key_entry(
4667 db: &mut KeystoreDB,
Janis Danisevskisc5b210b2020-09-11 13:27:37 -07004668 domain: Domain,
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004669 namespace: i64,
4670 alias: &str,
Qi Wub9433b52020-12-01 14:52:46 +08004671 max_usage_count: Option<i32>,
Janis Danisevskisaec14592020-11-12 09:41:49 -08004672 ) -> Result<KeyIdGuard> {
Janis Danisevskis66784c42021-01-27 08:40:25 -08004673 let key_id = db.create_key_entry(&domain, &namespace, &KEYSTORE_UUID)?;
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004674 let mut blob_metadata = BlobMetaData::new();
4675 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4676 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4677 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4678 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4679 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4680
4681 db.set_blob(
4682 &key_id,
4683 SubComponentType::KEY_BLOB,
4684 Some(TEST_KEY_BLOB),
4685 Some(&blob_metadata),
4686 )?;
4687 db.set_blob(&key_id, SubComponentType::CERT, Some(TEST_CERT_BLOB), None)?;
4688 db.set_blob(&key_id, SubComponentType::CERT_CHAIN, Some(TEST_CERT_CHAIN_BLOB), None)?;
Qi Wub9433b52020-12-01 14:52:46 +08004689
4690 let params = make_test_params(max_usage_count);
4691 db.insert_keyparameter(&key_id, &params)?;
4692
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004693 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004694 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004695 db.insert_key_metadata(&key_id, &metadata)?;
Janis Danisevskis4507f3b2021-01-13 16:34:39 -08004696 rebind_alias(db, &key_id, alias, domain, namespace)?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004697 Ok(key_id)
4698 }
4699
Qi Wub9433b52020-12-01 14:52:46 +08004700 fn make_test_key_entry_test_vector(key_id: i64, max_usage_count: Option<i32>) -> KeyEntry {
4701 let params = make_test_params(max_usage_count);
4702
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004703 let mut blob_metadata = BlobMetaData::new();
4704 blob_metadata.add(BlobMetaEntry::EncryptedBy(EncryptedBy::Password));
4705 blob_metadata.add(BlobMetaEntry::Salt(vec![1, 2, 3]));
4706 blob_metadata.add(BlobMetaEntry::Iv(vec![2, 3, 1]));
4707 blob_metadata.add(BlobMetaEntry::AeadTag(vec![3, 1, 2]));
4708 blob_metadata.add(BlobMetaEntry::KmUuid(KEYSTORE_UUID));
4709
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004710 let mut metadata = KeyMetaData::new();
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004711 metadata.add(KeyMetaEntry::CreationDate(DateTime::from_millis_epoch(123456789)));
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004712
4713 KeyEntry {
4714 id: key_id,
Janis Danisevskis7e8b4622021-02-13 10:01:59 -08004715 key_blob_info: Some((TEST_KEY_BLOB.to_vec(), blob_metadata)),
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004716 cert: Some(TEST_CERT_BLOB.to_vec()),
4717 cert_chain: Some(TEST_CERT_CHAIN_BLOB.to_vec()),
Max Bires8e93d2b2021-01-14 13:17:59 -08004718 km_uuid: KEYSTORE_UUID,
Qi Wub9433b52020-12-01 14:52:46 +08004719 parameters: params,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004720 metadata,
Janis Danisevskis377d1002021-01-27 19:07:48 -08004721 pure_cert: false,
Janis Danisevskisb42fc182020-12-15 08:41:27 -08004722 }
4723 }
4724
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004725 fn debug_dump_keyentry_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004726 let mut stmt = db.conn.prepare(
Max Bires8e93d2b2021-01-14 13:17:59 -08004727 "SELECT id, key_type, domain, namespace, alias, state, km_uuid FROM persistent.keyentry;",
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004728 )?;
Max Bires8e93d2b2021-01-14 13:17:59 -08004729 let rows = stmt.query_map::<(i64, KeyType, i32, i64, String, KeyLifeCycle, Uuid), _, _>(
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004730 NO_PARAMS,
4731 |row| {
Max Bires8e93d2b2021-01-14 13:17:59 -08004732 Ok((
4733 row.get(0)?,
4734 row.get(1)?,
4735 row.get(2)?,
4736 row.get(3)?,
4737 row.get(4)?,
4738 row.get(5)?,
4739 row.get(6)?,
4740 ))
Janis Danisevskis93927dd2020-12-23 12:23:08 -08004741 },
4742 )?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004743
4744 println!("Key entry table rows:");
4745 for r in rows {
Max Bires8e93d2b2021-01-14 13:17:59 -08004746 let (id, key_type, domain, namespace, alias, state, km_uuid) = r.unwrap();
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004747 println!(
Max Bires8e93d2b2021-01-14 13:17:59 -08004748 " id: {} KeyType: {:?} Domain: {} Namespace: {} Alias: {} State: {:?} KmUuid: {:?}",
4749 id, key_type, domain, namespace, alias, state, km_uuid
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004750 );
4751 }
4752 Ok(())
4753 }
4754
4755 fn debug_dump_grant_table(db: &mut KeystoreDB) -> Result<()> {
Janis Danisevskisbf15d732020-12-08 10:35:26 -08004756 let mut stmt = db
4757 .conn
4758 .prepare("SELECT id, grantee, keyentryid, access_vector FROM persistent.grant;")?;
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004759 let rows = stmt.query_map::<(i64, i64, i64, i64), _, _>(NO_PARAMS, |row| {
4760 Ok((row.get(0)?, row.get(1)?, row.get(2)?, row.get(3)?))
4761 })?;
4762
4763 println!("Grant table rows:");
4764 for r in rows {
4765 let (id, gt, ki, av) = r.unwrap();
4766 println!(" id: {} grantee: {} key_id: {} access_vector: {}", id, gt, ki, av);
4767 }
4768 Ok(())
4769 }
4770
Joel Galenson0891bc12020-07-20 10:37:03 -07004771 // Use a custom random number generator that repeats each number once.
4772 // This allows us to test repeated elements.
4773
4774 thread_local! {
4775 static RANDOM_COUNTER: RefCell<i64> = RefCell::new(0);
4776 }
4777
Janis Danisevskis63f7bc82020-09-03 10:12:56 -07004778 fn reset_random() {
4779 RANDOM_COUNTER.with(|counter| {
4780 *counter.borrow_mut() = 0;
4781 })
4782 }
4783
Joel Galenson0891bc12020-07-20 10:37:03 -07004784 pub fn random() -> i64 {
4785 RANDOM_COUNTER.with(|counter| {
4786 let result = *counter.borrow() / 2;
4787 *counter.borrow_mut() += 1;
4788 result
4789 })
4790 }
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004791
4792 #[test]
4793 fn test_last_off_body() -> Result<()> {
4794 let mut db = new_test_db()?;
Janis Danisevskis5ed8c532021-01-11 14:19:42 -08004795 db.insert_last_off_body(MonotonicRawTime::now())?;
Hasini Gunasinghef70cf8e2020-11-11 01:02:41 +00004796 let tx = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4797 let last_off_body_1 = KeystoreDB::get_last_off_body(&tx)?;
4798 tx.commit()?;
4799 let one_second = Duration::from_secs(1);
4800 thread::sleep(one_second);
4801 db.update_last_off_body(MonotonicRawTime::now())?;
4802 let tx2 = db.conn.transaction_with_behavior(TransactionBehavior::Immediate)?;
4803 let last_off_body_2 = KeystoreDB::get_last_off_body(&tx2)?;
4804 tx2.commit()?;
4805 assert!(last_off_body_1.seconds() < last_off_body_2.seconds());
4806 Ok(())
4807 }
Hasini Gunasingheda895552021-01-27 19:34:37 +00004808
4809 #[test]
4810 fn test_unbind_keys_for_user() -> Result<()> {
4811 let mut db = new_test_db()?;
4812 db.unbind_keys_for_user(1, false)?;
4813
4814 make_test_key_entry(&mut db, Domain::APP, 210000, TEST_ALIAS, None)?;
4815 make_test_key_entry(&mut db, Domain::APP, 110000, TEST_ALIAS, None)?;
4816 db.unbind_keys_for_user(2, false)?;
4817
4818 assert_eq!(1, db.list(Domain::APP, 110000)?.len());
4819 assert_eq!(0, db.list(Domain::APP, 210000)?.len());
4820
4821 db.unbind_keys_for_user(1, true)?;
4822 assert_eq!(0, db.list(Domain::APP, 110000)?.len());
4823
4824 Ok(())
4825 }
4826
4827 #[test]
4828 fn test_store_super_key() -> Result<()> {
4829 let mut db = new_test_db()?;
4830 let pw = "xyzabc".as_bytes();
4831 let super_key = keystore2_crypto::generate_aes256_key()?;
4832 let secret = String::from("keystore2 is great.");
4833 let secret_bytes = secret.into_bytes();
4834 let (encrypted_secret, iv, tag) =
4835 keystore2_crypto::aes_gcm_encrypt(&secret_bytes, &super_key)?;
4836
4837 let (encrypted_super_key, metadata) =
4838 SuperKeyManager::encrypt_with_password(&super_key, &pw)?;
4839 db.store_super_key(1, &(&encrypted_super_key, &metadata))?;
4840
Hasini Gunasinghedeab85d2021-02-01 21:10:02 +00004841 //check if super key exists
4842 assert!(db.key_exists(Domain::APP, 1, "USER_SUPER_KEY", KeyType::Super)?);
4843
Hasini Gunasinghe731e3c82021-02-06 00:56:28 +00004844 let (_, key_entry) = db.load_super_key(1)?.unwrap();
Hasini Gunasingheda895552021-01-27 19:34:37 +00004845 let loaded_super_key = SuperKeyManager::extract_super_key_from_key_entry(key_entry, &pw)?;
4846
4847 let decrypted_secret_bytes = keystore2_crypto::aes_gcm_decrypt(
4848 &encrypted_secret,
4849 &iv,
4850 &tag,
4851 &loaded_super_key.get_key(),
4852 )?;
4853 let decrypted_secret = String::from_utf8((&decrypted_secret_bytes).to_vec())?;
4854 assert_eq!(String::from("keystore2 is great."), decrypted_secret);
4855 Ok(())
4856 }
Joel Galenson26f4d012020-07-17 14:57:21 -07004857}